DarkRadiant Script Reference: Difference between revisions

From The DarkMod Wiki
Jump to navigationJump to search
 
(78 intermediate revisions by the same user not shown)
Line 35: Line 35:
* <tt>AABB getWorldAABB()</tt> Returns the bounding box (absolute coordinates) of this node. This includes the bounding boxes of all child nodes as well.
* <tt>AABB getWorldAABB()</tt> Returns the bounding box (absolute coordinates) of this node. This includes the bounding boxes of all child nodes as well.
* <tt>SceneNode getParent()</tt> Returns the parent of this node. If this node doesn't have a parent, a NULL node is returned.
* <tt>SceneNode getParent()</tt> Returns the parent of this node. If this node doesn't have a parent, a NULL node is returned.
* <tt>string getNodeType()</tt> Returns the type string of this node. Possible values: "map", "entity", "primitive", "unknown"
* <tt>string getNodeType()</tt> Returns the type string of this node. Possible values: "map", "entity", "patch", "brush", "model", "particle", "entityconnection", "mergeaction", "unknown"
* <tt>traverse(SceneNodeVisitor visitor)</tt> Traverses this Node and all its children using the given Visitor object. See the tutorial about scenegraph traversal for more information.
* <tt>traverse(SceneNodeVisitor visitor)</tt> Traverses this Node and all its children using the given Visitor object. See the tutorial about scenegraph traversal for more information.
* <tt>traverseChildren(SceneNodeVisitor visitor)</tt> Traverses all the children of this node using the given Visitor object. See the tutorial about scenegraph traversal for more information. (since 1.8.1)
* <tt>traverseChildren(SceneNodeVisitor visitor)</tt> Traverses all the children of this node using the given Visitor object. See the tutorial about scenegraph traversal for more information. (since 1.8.1)
Line 268: Line 268:
* <tt>int getNumTriangles()</tt> Returns the number of tris of this surface.
* <tt>int getNumTriangles()</tt> Returns the number of tris of this surface.
* <tt>int getNumVertices()</tt> Returns the number of vertices of this surface.
* <tt>int getNumVertices()</tt> Returns the number of vertices of this surface.
* <tt>ArbitraryMeshVertex getVertex(int vertexIndex)</tt> Get a specific vertex of this surface, holding vertex, colour, tangent, normal, etc.
* <tt>MeshVertex getVertex(int vertexIndex)</tt> Get a specific vertex of this surface, holding vertex, colour, tangent, normal, etc.
* <tt>ModelPolygon getPolygon(int polygonIndex)</tt> Returns a specific polygon from this model surface. Don't expect this to be fast as things are returned by value. This is merely to provide read access to the model polygons for scripts and plugins.
* <tt>ModelPolygon getPolygon(int polygonIndex)</tt> Returns a specific polygon from this model surface. Don't expect this to be fast as things are returned by value. This is merely to provide read access to the model polygons for scripts and plugins.


===== ArbitraryMeshVertex =====
===== MeshVertex =====
An ArbitraryMeshVertex is a structure representing a model vertex. It holds the 3D coordinates, the texture coordinates, normal, tangent and bitangent vectors as well as the vertex colour (since 1.5.0).
A MeshVertex is a structure representing a model vertex. It holds the 3D coordinates, the texture coordinates, normal, tangent and bitangent vectors as well as the vertex colour (since 1.5.0).
(This type has been named ArbitraryMeshVertex until 2.14.)
* <tt>Vector2 texcoord</tt> The 2D texture coordinates
* <tt>Vector2 texcoord</tt> The 2D texture coordinates
* <tt>Vector3 vertex</tt> The 3D coordinates
* <tt>Vector3 vertex</tt> The 3D coordinates
Line 281: Line 282:


===== ModelPolygon =====
===== ModelPolygon =====
A model polygon is a triangle holding three ArbitraryMeshVertex structures a, b and c (since 1.5.0).
A model polygon is a triangle holding three MeshVertex structures a, b and c (since 1.5.0).
* <tt>ArbitraryMeshVertex a</tt> The first vertex of this polygon
* <tt>MeshVertex a</tt> The first vertex of this polygon
* <tt>ArbitraryMeshVertex b</tt> The second vertex of this polygon
* <tt>MeshVertex b</tt> The second vertex of this polygon
* <tt>ArbitraryMeshVertex c</tt> The third vertex of this polygon
* <tt>MeshVertex c</tt> The third vertex of this polygon
 
=== GlobalDeclarationManager ===
The declaration manager (available since 3.1.0) offers methods to interact with the declarations like Materials, Skins, ModelDefs defined throughout the mod. It can iterate through existing declarations, find them, manipulate them and even save them back to disk. See also the [https://github.com/codereader/DarkRadiant/blob/master/install/scripts/test.py Test Python Script] (scripts/test.py) in DarkRadiant's installation location.
 
* <tt>Declaration findDeclaration(Declaration.Type type, string name)</tt> Finds a named declaration. If the declaration is not found, a NULL object is returned, see <tt>Declaration.isNull</tt>.
* <tt>Declaration findOrCreateDeclaration(Declaration.Type type, string name)</tt> Finds an existing named declaration or creates an empty one if no declaration with that name exists yet. Will always return a non-null object.
* <tt>Declaration foreachDeclaration(Declaration.Type type, DeclarationVisitor visitor)</tt> Calls the <tt>visit</tt> method of the given visitor class, see the example below.
* <tt>bool renameDeclaration(Declaration.Type type, string oldName, string newName)</tt> Renames the declaration from oldName to newName. The new name must not be in use by any other declaration, and it must be different from oldName, otherwise renaming will fail. Returns true if the old declaration existed and could successfully be renamed, false on any failure.
* <tt>removeDeclaration(Declaration.Type type, string name)</tt> Removes the given declaration from the internal dictionaries. This doesn't remove the declaration from the source files, so this operation will not survive a reloadDeclarations command. Used to remove temporary decls in edit scenarios.
* <tt>reloadDeclarations()</tt> Reload all declarations. All declaration references your script may hold will stay intact, only their contents will be refreshed.
* <tt>saveDeclaration(Declaration decl)</tt> Saves the given declaration to a physical declaration file. Depending on the original location of the declaration the outcome will be different (see notes below).
 
'''Notes on saveDeclaration'''
 
It is required for the declaration to have valid file information set on its syntax block, otherwise the declaration manager will not know where to save it to.
* Case #1: Newly created declarations (created through findOrCreateDeclaration): The decl will be appended to the given file. The file will be created if required.
* Case #2: Existing declarations (with their original file being a physical file): The decl in the file will be replaced with its new syntax block. All the content before and after the declaration will be left untouched.
* Case #3: Existing declarations (with their original file being stored within a PK4): The decl file will be copied and saved to its corresponding physical location, effectively creating a file that will override the one in the PK4. The decl will be merged into the file just like in case #2
 
==== Declaration.Type ====
An enumeration of the available decl types supported by DarkRadiant:
* Declaration.Type.'''Material'''
* Declaration.Type.'''Table'''
* Declaration.Type.'''EntityDef'''
* Declaration.Type.'''SoundShader'''
* Declaration.Type.'''ModelDef'''
* Declaration.Type.'''Particle'''
* Declaration.Type.'''Skin'''
 
==== Declaration ====
Represents a generic declaration as defined in the .mtr, .skin and .def files throughout the active mod or mission project.
* <tt>bool isNull()</tt> Returns true if this is a NULL object, e.g. if a non-existent declaration has been requested through DeclarationManager.findDeclaration
* <tt>string getDeclName()</tt> Returns the name of this declaration, e.g. "textures/common/caulk"
* <tt>Type getDeclType()</tt> Returns the declaration type, e.g. Declaration.Type.Skin
* <tt>DeclarationBlockSyntax getBlockSyntax()</tt> Returns the syntax block containing the raw source text
* <tt>setBlockSyntax(DeclarationBlockSyntax syntax)</tt> Assigns a new syntax block to this declaration
* <tt>string getDeclFilePath()</tt> Returns the mod-relative path of the file this declaration has been defined in (e.g. "materials/test.mtr")
* <tt>setDeclFilePath(string folder, string filename)</tt> Sets the mod-relative folder and filename of this declaration (useful right before saving a newly created declaration), Example: setDeclFilePath("materials/", "test.mtr")
 
==== DeclarationBlockSyntax ====
The syntax block contains the raw text contents as found in the file the declaration was defined in. The <tt>contents</tt> property holds the source text excluding the name and the outermost surrounding curly braces, so only the inner part is stored here. It can be modified and saved back into a declaration using <tt>setBlockSyntax</tt>.
* <tt>typeName</tt> Returns typename as defined in the source file (can also be empty if none was specified)
* <tt>name</tt> Returns the name of this block
* <tt>contents</tt> Returns the raw contents of this block, excluding the name and the outermost surrounding curly braces
* <tt>modName</tt> Returns the name of the mod/FM/project this block has been declared in.
 
==== DeclarationVisitor ====
A DeclarationVisitor can be used to iterate over all existing declarations of a given type. It just needs a single method definition named visit:
* <tt>visit(Declaration decl)</tt> Is called for each known Declaration.
 
This code example can be used as template when writing scripts for declarations; it shows how to print the name and filename of each skin declaration:
import darkradiant as dr
# Test implementing a DeclarationManager interface
class TestDeclarationVisitor(dr.DeclarationVisitor) :
    def visit(self, decl):
        print(str(decl.getDeclType()) + ": " + decl.getDeclName() + " defined in " + decl.getDeclFilePath())
visitor= TestDeclarationVisitor()
GlobalDeclarationManager.foreachDeclaration(Declaration.Type.Skin, visitor)


=== Entity Classes ===
=== Entity Classes ===
Line 423: Line 484:
The GlobalMap object represents the currently loaded map. Its interface is quite thin at the moment:
The GlobalMap object represents the currently loaded map. Its interface is quite thin at the moment:
* <tt>SceneNode getWorldSpawn()</tt> Returns the worldspawn of the currently loaded map. This can be a NULL node if no map is active or no worldspawn has been created yet.
* <tt>SceneNode getWorldSpawn()</tt> Returns the worldspawn of the currently loaded map. This can be a NULL node if no map is active or no worldspawn has been created yet.
* <tt>SceneNode getRoot()</tt> Returns the root node of the currently loaded map. This can be a NULL node if no map is active. (since 2.13.0)
* <tt>bool isModified()</tt> Returns true (1) if the current map has been modified. (since 2.13.0)
* <tt>string getMapName()</tt> Returns the name of the currently loaded map. This is "unnammed.map" for an unsaved map.
* <tt>string getMapName()</tt> Returns the name of the currently loaded map. This is "unnammed.map" for an unsaved map.
* <tt>MapEditMode getEditMode()</tt> Returns the current edit mode. This is either <tt>MapEditMode.Normal</tt> or <tt>MapEditMode.Merge</tt> (since 2.13.0)
* <tt>setEditMode(MapEditMode mode)</tt> Sets the current edit mode. (since 2.13.0)
* <tt>StringList getPointFileList()</tt> Gets the list of available point files for the current map. (since 2.13.0)
* <tt>showPointFile(string path)</tt> Loads and displays the given point file. (since 2.13.0)
* <tt>isPointTraceVisible()</tt> Returns true (1) if there's a point file visualisation active. (since 2.13.0)


=== Math Objects ===
=== Math Objects ===
Line 483: Line 551:
The "Radiant" module plays a slightly different role for scripting than it does for the "internal" C++ code. Here, it provides some "convenience" methods.
The "Radiant" module plays a slightly different role for scripting than it does for the "internal" C++ code. Here, it provides some "convenience" methods.
* <tt>EntityNode findEntityByClassname(string name)</tt> Returns the first matching entity with the given classname in the current scenegraph. Returns a NULL node if nothing is found.
* <tt>EntityNode findEntityByClassname(string name)</tt> Returns the first matching entity with the given classname in the current scenegraph. Returns a NULL node if nothing is found.
* <tt>EntityNode findEntityName(string name)</tt> Returns the entity with the given name in the current scenegraph. Returns a NULL node if nothing is found (since 3.6.0).
Example:
Example:
  worldspawn = Radiant.findEntityByClassname("worldspawn")
  worldspawn = Radiant.findEntityByClassname("worldspawn")
worldspawn.setKeyValue('test', 'success')
print('Worldspawn edited')
Or:
worldspawn = Radiant.findEntityByName("world")
  worldspawn.setKeyValue('test', 'success')
  worldspawn.setKeyValue('test', 'success')
  print('Worldspawn edited')
  print('Worldspawn edited')
Line 493: Line 567:
* <tt>foreachSelected(SelectionVisitor visitor)</tt> Visits the current selection using the given Visitor object (not counting components).
* <tt>foreachSelected(SelectionVisitor visitor)</tt> Visits the current selection using the given Visitor object (not counting components).
* <tt>foreachSelectedComponent(SelectionVisitor visitor)</tt> Visits the current '''component''' selection using the given Visitor object.
* <tt>foreachSelectedComponent(SelectionVisitor visitor)</tt> Visits the current '''component''' selection using the given Visitor object.
* <tt>foreachSelectedFace(SelectedFaceVisitor visitor)</tt> Visits all selected faces using the given FaceVisitor object (since 2.13.0).
* <tt>setSelectedAll(bool selected)</tt> Sets the selection status of all objects in the scenegraph (not counting components like Vertices and Edges).
* <tt>setSelectedAll(bool selected)</tt> Sets the selection status of all objects in the scenegraph (not counting components like Vertices and Edges).
* <tt>setSelectedAllComponents(bool selected)</tt> Sets the selection status of all components in the scenegraph (Vertices, Edges, Faces).
* <tt>setSelectedAllComponents(bool selected)</tt> Sets the selection status of all components in the scenegraph (Vertices, Edges, Faces).
* <tt>SceneNode ultimateSelected()</tt> Returns a reference to the last selected object. Will throw an exception if called with an empty selection, so check first using getSelectionInfo().
* <tt>SceneNode ultimateSelected()</tt> Returns a reference to the last selected object. Will throw an exception if called with an empty selection, so check first using getSelectionInfo().
* <tt>SceneNode penultimateSelected()</tt> Returns a reference to the penultimate selected object. Will throw an exception if called with less than two objects selected, so check first using getSelectionInfo().
* <tt>SceneNode penultimateSelected()</tt> Returns a reference to the penultimate selected object. Will throw an exception if called with less than two objects selected, so check first using getSelectionInfo().
==== Visiting Faces ====
The following snippet calls the <tt>visitFace</tt> method for every selected face in the scene:
# Visit every selected face
import darkradiant as dr
class FaceVisitor(dr.SelectedFaceVisitor) :
def visitFace(self, face):
print(face.getShader())
visitor = FaceVisitor()
GlobalSelectionSystem.foreachSelectedFace(visitor)


==== SelectionInfo ====
==== SelectionInfo ====
Line 558: Line 645:
  groupWalker = SelectionGroupWalker()
  groupWalker = SelectionGroupWalker()
  group.foreachNode(groupWalker)
  group.foreachNode(groupWalker)
=== GlobalLayerManager ===
The GlobalLayerManager instance provides methods for organising and manipulating layers. (since 2.10.0).
* <tt>int createLayer(string name)</tt> Creates a new layer with the given name, returns the ID.
* <tt>deleteLayer(int id)</tt> Deletes the layer with the given ID.
* <tt>foreachLayer(LayerVisitor visitor)</tt> Calls the given visitor object with the id and name of each layer.
* <tt>int getLayerID(string name)</tt> Looks up the ID for the given named layer, returns -1 if the layer doesn't exist.
* <tt>string getLayerName(int id)</tt> Looks up the name for the given layer ID, returns an empty string if the layer doesn't exist.
* <tt>bool layerExists(int id)</tt> Returns true if the layer with the given ID exists, false otherwise.
* <tt>bool renameLayer(int id, string newName)</tt> Renames the layer with the given ID, returns true on success.
* <tt>int getFirstVisibleLayer()</tt> Returns the ID of the first visible layer.
* <tt>int getActiveLayer()</tt> Returns the ID of the active layer.
* <tt>setActiveLayer(int id)</tt> Makes the layer with the given ID the active layer.
* <tt>bool layerIsVisible(int id)</tt> Returns true if the layer with the given ID is visible, false otherwise.
* <tt>bool layerIsVisible(string name)</tt> Returns true if the layer with the given name is visible, false otherwise.
* <tt>setLayerVisibility(string name, bool visible)</tt> Makes the layer with the given name visible or invisible, depending on the value of the "visible" flag.
* <tt>setLayerVisibility(int id, bool visible)</tt> Makes the layer with the given ID visible or invisible, depending on the value of the "visible" flag.
* <tt>addSelectionToLayer(int id)</tt> Adds the current map selection to the layer with the given ID.
* <tt>addSelectionToLayer(string name)</tt> Adds the current map selection to the layer with the given name.
* <tt>moveSelectionToLayer(int id)</tt> Moves the current map selection to the layer with the given ID.
* <tt>moveSelectionToLayer(string name)</tt> Moves the current map selection to the layer with the given name.
* <tt>removeSelectionFromLayer(int id)</tt> Removes the current map selection from the layer with the given ID.
* <tt>removeSelectionFromLayer(string name)</tt> Removes the current map selection from the layer with the given name.
* <tt>setSelected(int id, bool selected)</tt> Selects or deselects all members of the layer with the given ID.
==== LayerVisitor ====
Create an object deriving from this LayerVisitor and use it to visit every layer in the loaded map.
* <tt>visit(int layerId, string layerName)</tt> Required method which is called for every layer when using <tt>GlobalLayerManager.foreachLayer()</tt>
'''Example'''
import darkradiant as dr
class LayerPrinter(dr.LayerVisitor):
    def visit(self, layerID, layerName):
        print(layerID, layerName)
layerPrinter = LayerPrinter()
GlobalLayerManager.foreachLayer(layerPrinter)


=== GlobalMaterialManager ===
=== GlobalMaterialManager ===
Line 596: Line 719:
* <tt>string getShaderFileName()</tt> Returns the filename this shader is defined in (e.g. "materials/tdm_stone_brick.mtr")
* <tt>string getShaderFileName()</tt> Returns the filename this shader is defined in (e.g. "materials/tdm_stone_brick.mtr")
* <tt>string getDescription()</tt> Returns the description string as parsed from the material.
* <tt>string getDescription()</tt> Returns the description string as parsed from the material.
* <tt>bool isModified()</tt> Returns true (1) if this material has been modified (programmatically). (since 2.12)
* <tt>string getDefinition()</tt> Returns the parsed (or generated) material definition source (the part between the two outermost curly braces).
* <tt>bool isVisible()</tt> Returns true if this shader is visible, i.e. not currently filtered.
* <tt>bool isVisible()</tt> Returns true if this shader is visible, i.e. not currently filtered.
* <tt>bool isAmbientLight()</tt> Returns true (1) if this is an ambient light material.
* <tt>bool isAmbientLight()</tt> Returns true (1) if this is an ambient light material.
* <tt>bool isBlendLight()</tt> Returns true (1) if this is a blend light material.
* <tt>bool isBlendLight()</tt> Returns true (1) if this is a blend light material.
* <tt>bool isFogLight()</tt> Returns true (1) if this is a fog light material.
* <tt>bool isFogLight()</tt> Returns true (1) if this is a fog light material.
* <tt>bool isCubicLight()</tt> Returns true (1) if this is a cubic light material. (since 2.12)
* <tt>string getEditorImageExpressionString()</tt> Returns the qer_editorImage part (since 2.12)
* <tt>string getEditorImageExpressionString()</tt> Returns the qer_editorImage part (since 2.12)
* <tt>float getSortRequest()</tt> Returns the value of the "sort" keyword in this material (since 2.12)
* <tt>float getPolygonOffset()</tt> Return a polygon offset if one is defined. The default is 0. (since 2.12)
* <tt>Material.ClampType getClampType()</tt> Get the desired texture repeat behaviour (since 2.12)
* <tt>Material.CullType getCullType()</tt> Get the cull type (none, back, front) (since 2.12)
* <tt>int getMaterialFlags()</tt> Get the combined bit flags that are set on this material (see Material.Flag below) (since 2.12)
* <tt>int getSurfaceFlags()</tt> Get the combined bit surface flags that are set on this material (see Material.SurfaceFlag below) (since 2.12)
* <tt>Material.SurfaceType getSurfaceType()</tt> Get the surface type (wood, flesh, etc.) of this material (see Material.SurfaceType below) (since 2.12)
* <tt>Material.DeformType getDeformType()</tt> Get the deform type (flare, sprite, ...) of this material (see Material.DeformType below) (since 2.12)
* <tt>string getDeformExpressionString(int index)</tt> Returns the shader expression used to define the deform parameters (valid indices in [0..2]) (since 2.12)
* <tt>string getDeformDeclName()</tt> Used for DeformType.PARTICLE/PARTICLE2; defines the name of the particle def (since 2.12)
* <tt>int getSpectrum()</tt> Returns the spectrum of this shader, 0 is the default value (even without keyword in the material) (since 2.12)
* <tt>Material.DecalInfo getDecalInfo()</tt> Returns the decal info structure of this material (since 2.12)
* <tt>Material.Coverage getCoverage()</tt> The evaluated coverage of this material (see Material.Coverage below) (since 2.12)
* <tt>string getLightFalloffExpressionString()</tt> Returns the map expression used to define the light falloff image (since 2.12)
* <tt>MaterialStage.MapType getLightFalloffCubeMapType()</tt> Returns the map type of the light falloff image (cubeMap, map) (since 2.12)
* <tt>string getGuiSurfArgument()</tt> The argument to the "guisurf" keyword, if not entity[2]3]. In case entity[2]3] is set, the corresponding surface flags are enabled (since 2.12)
* <tt>string getRenderBumpArguments()</tt> Returns the argument string after the renderbump keyword, or an empty string if no statement is present (since 2.12)
* <tt>string getRenderBumpFlatArguments()</tt> Returns the argument string after the renderbumpflat keyword, or an empty string if no statement is present (since 2.12)
* <tt>(List of ScriptMaterialStage) getAllStages()</tt> Returns the list of all stages in this material (since 2.12)
* <tt>int getNumStages()</tt> Return the number of stages in this material (since 2.12)
* <tt>MaterialStage getStage(int index)</tt> Returns the stage with the given index (since 2.12)


The following methods can only be called on materials that can be modified, otherwise an exception will be thrown. Check <tt>GlobalMaterialManager.materialCanBeModified()</tt> first.
The following methods can only be called on materials that can be modified, otherwise an exception will be thrown. Check <tt>GlobalMaterialManager.materialCanBeModified()</tt> first.
* <tt>revertModifications()</tt> Undo all changes to this material since it was last saved(since 2.12)
* <tt>EditableMaterialStage getEditableStage(int index)</tt> Returns the editable stage with the given index (since 2.12)
* <tt>setShaderFileName(string fullPath)</tt> Set the mtr file name to define where this material should be saved to (since 2.12)
* <tt>setDescription(string description)</tt> Set the material description (since 2.12)
* <tt>setEditorImageExpressionFromString(string editorImagePath)</tt> Sets the qer_editorImage path of this material. (since 2.12)
* <tt>setEditorImageExpressionFromString(string editorImagePath)</tt> Sets the qer_editorImage path of this material. (since 2.12)
* <tt>setSortRequest(float/SortRequest value)</tt> Sets the sort request value of this material. See the predefined SortRequest values below (since 2.12)
* <tt>resetSortRequest()</tt> Resets the sort request value of this material to its default. (since 2.12)
* <tt>setPolygonOffset(float offset)</tt> Set the polygon offset of this material (since 2.12)
* <tt>clearPolygonOffset()</tt> Removes the polygon offset from this material (since 2.12)
* <tt>setClampType(Material.ClampType type)</tt> Set the desired texture repeat behaviour (see Material.ClampType below) (since 2.12)
* <tt>setCullType(Material.CullType type)</tt> Set the cull type (see Material.CullType below) (since 2.12)
* <tt>setMaterialFlag(Material.Flag flag)</tt> Set the given material flag (see Material.Flag below) (since 2.12)
* <tt>clearMaterialFlag(Material.Flag flag)</tt> Clear the given material flag (see Material.Flag below) (since 2.12)
* <tt>setSurfaceFlag(Material.SurfaceFlag flag)</tt> Set the given surface flag (see Material.SurfaceFlag below) (since 2.12)
* <tt>clearSurfaceFlag(Material.SurfaceFlag flag)</tt> Clear the given surface flag (see Material.SurfaceFlag below) (since 2.12)
* <tt>setSurfaceType(Material.SurfaceType type)</tt> Set the surface type (wood, flesh, etc.) of this material (see Material.SurfaceType below) (since 2.12)
* <tt>setSpectrum(int spectrum)</tt> Sets the spectrum of this material (since 2.12)
* <tt>setIsAmbientLight(int newValue)</tt> Pass true (1) to enable the ambient light flag on this material (since 2.12)
* <tt>setIsBlendLight(int newValue)</tt> Pass true (1) to enable the blend light flag on this material (since 2.12)
* <tt>setIsFogLight(int newValue)</tt> Pass true (1) to enable the fog light flag on this material (since 2.12)
* <tt>setIsCubicLight(int newValue)</tt> Pass true (1) to enable the cubic light flag on this material (since 2.12)
* <tt>setLightFalloffExpressionFromString(string expression)</tt> Set the light falloff map expression (since 2.12)
* <tt>setLightFalloffCubeMapType(MaterialStage.MapType type)</tt> Set the map type of the light falloff image (since 2.12)
* <tt>int addStage(MaterialStage.Type type)</tt> Create a new stage with the given type, returns the index of the new stage (since 2.12)
* <tt>removeStage(int index)</tt> Removes the stage with the new index (since 2.12)
* <tt>int duplicateStage(int index)</tt> Duplicates the stage with the given index, returns the index of the new stage (since 2.12)
* <tt>swapStagePosition(int first, int second)</tt> Swaps the position of the two given stages. (since 2.12)
* <tt>Material.FrobStageType getFrobStageType()</tt> Returns the frob stage type used by this material. (since 3.8.0) - see [[#Material.FrobStageType|FrobStageType]]
* <tt>setFrobStageType(Material.FrobStageType type)</tt> Sets the frob stage type used by this material. (since 3.8.0)
* <tt>string getFrobStageMapExpressionString()</tt> Returns the frob stage map expression used for frob stage type TEXTURE. (since 3.8.0)
* <tt>setFrobStageMapExpressionFromString(string expression)</tt> Sets the frob stage map expression used for frob stage type TEXTURE. (since 3.8.0)
* <tt>Vector3 getFrobStageRgbParameter(int index)</tt> Returns one of the two frob stage RGB parameters (index can be 0 or 1), as used by this material. (since 3.8.0)
* <tt>setFrobStageParameter(double value)</tt> Assigns the same value to all three RGB components of the frob stage parameter with the given index (which can be 0 or 1). (since 3.8.0)
* <tt>setFrobStageRgbParameter(Vector3 rgb)</tt> Sets the RGB components of the frob stage parameter with the given index (which can be 0 or 1). (since 3.8.0)
==== Material.SurfaceType ====
* Material.SurfaceType.'''DEFAULT'''
* Material.SurfaceType.'''METAL'''
* Material.SurfaceType.'''STONE'''
* Material.SurfaceType.'''FLESH'''
* Material.SurfaceType.'''WOOD'''
* Material.SurfaceType.'''CARDBOARD'''
* Material.SurfaceType.'''LIQUID'''
* Material.SurfaceType.'''GLASS'''
* Material.SurfaceType.'''PLASTIC'''
* Material.SurfaceType.'''RICOCHET'''
* Material.SurfaceType.'''AASOBSTACLE'''
* Material.SurfaceType.'''SURFTYPE10'''
* Material.SurfaceType.'''SURFTYPE11'''
* Material.SurfaceType.'''SURFTYPE12'''
* Material.SurfaceType.'''SURFTYPE13'''
* Material.SurfaceType.'''SURFTYPE14'''
* Material.SurfaceType.'''SURFTYPE15'''
==== Material.Flag ====
These are bit flags that can be set/cleared/combined on a material.
* Material.Flag.'''NOSHADOWS'''
* Material.Flag.'''NOSELFSHADOW'''
* Material.Flag.'''FORCESHADOWS'''
* Material.Flag.'''NOOVERLAYS'''
* Material.Flag.'''FORCEOVERLAYS'''
* Material.Flag.'''TRANSLUCENT'''
* Material.Flag.'''FORCEOPAQUE'''
* Material.Flag.'''NOFOG'''
* Material.Flag.'''NOPORTALFOG'''
* Material.Flag.'''UNSMOOTHEDTANGENTS'''
* Material.Flag.'''MIRROR'''
* Material.Flag.'''POLYGONOFFSET'''
* Material.Flag.'''ISLIGHTGEMSURF'''
==== Material.SurfaceFlag ====
Various flags that can be set/cleared/combined on a material
* Material.SurfaceFlag.'''SOLID'''
* Material.SurfaceFlag.'''OPAQUE'''
* Material.SurfaceFlag.'''WATER'''
* Material.SurfaceFlag.'''PLAYERCLIP'''
* Material.SurfaceFlag.'''MONSTERCLIP'''
* Material.SurfaceFlag.'''MOVEABLECLIP'''
* Material.SurfaceFlag.'''IKCLIP'''
* Material.SurfaceFlag.'''BLOOD'''
* Material.SurfaceFlag.'''TRIGGER'''
* Material.SurfaceFlag.'''AASSOLID'''
* Material.SurfaceFlag.'''AASOBSTACLE'''
* Material.SurfaceFlag.'''FLASHLIGHT_TRIGGER'''
* Material.SurfaceFlag.'''NONSOLID'''
* Material.SurfaceFlag.'''NULLNORMAL'''
* Material.SurfaceFlag.'''AREAPORTAL'''
* Material.SurfaceFlag.'''NOCARVE'''
* Material.SurfaceFlag.'''DISCRETE'''
* Material.SurfaceFlag.'''NOFRAGMENT'''
* Material.SurfaceFlag.'''SLICK'''
* Material.SurfaceFlag.'''COLLISION'''
* Material.SurfaceFlag.'''NOIMPACT'''
* Material.SurfaceFlag.'''NODAMAGE'''
* Material.SurfaceFlag.'''LADDER'''
* Material.SurfaceFlag.'''NOSTEPS'''
* Material.SurfaceFlag.'''GUISURF'''
* Material.SurfaceFlag.'''ENTITYGUI'''
* Material.SurfaceFlag.'''ENTITYGUI2'''
* Material.SurfaceFlag.'''ENTITYGUI3'''
==== Material.SortRequest ====
Pre-defined sort request constants as corresponding to the TDM engine code:
* Material.SortRequest.'''SUBVIEW'''
* Material.SortRequest.'''GUI'''
* Material.SortRequest.'''BAD'''
* Material.SortRequest.'''OPAQUE'''
* Material.SortRequest.'''PORTAL_SKY'''
* Material.SortRequest.'''DECAL'''
* Material.SortRequest.'''FAR'''
* Material.SortRequest.'''MEDIUM'''
* Material.SortRequest.'''CLOSE'''
* Material.SortRequest.'''ALMOST_NEAREST'''
* Material.SortRequest.'''NEAREST'''
* Material.SortRequest.'''AFTER_FOG'''
* Material.SortRequest.'''POST_PROCESS'''
==== Material.ClampType ====
* Material.ClampType.'''REPEAT''' default = no clamping
* Material.ClampType.'''NOREPEAT''' "clamp"
* Material.ClampType.'''ZEROCLAMP''' zeroclamp"
* Material.ClampType.'''ALPHAZEROCLAMP''' "alphazeroclamp"
==== Material.CullType ====
* Material.CullType.'''BACK''' (default)
* Material.CullType.'''FRONT''' (backsided)
* Material.CullType.'''NONE''' (twosided)
==== Material.DeformType ====
* Material.DeformType.'''NONE'''
* Material.DeformType.'''SPRITE'''
* Material.DeformType.'''TUBE'''
* Material.DeformType.'''FLARE'''
* Material.DeformType.'''EXPAND'''
* Material.DeformType.'''MOVE'''
* Material.DeformType.'''TURBULENT'''
* Material.DeformType.'''EYEBALL'''
* Material.DeformType.'''PARTICLE'''
* Material.DeformType.'''PARTICLE2'''
==== Material.DecalInfo ====
* <tt>int stayMilliSeconds</tt>
* <tt>int fadeMilliSeconds</tt>
* <tt>Vector4 startColour</tt>
* <tt>Vector4 endColour</tt>
==== Material.Coverage ====
* Material.Coverage.'''UNDETERMINED'''
* Material.Coverage.'''OPAQUE'''
* Material.Coverage.'''PERFORATED'''
* Material.Coverage.'''TRANSLUCENT'''
==== Material.FrobStageType ====
Frob stage types supported by TDM 2.11+, see also the descriptive comments on the [https://bugs.thedarkmod.com/view.php?id=5427#c15337 corresponding tracker entry]
* Material.FrobStageType.'''DEFAULT'''
* Material.FrobStageType.'''DIFFUSE'''
* Material.FrobStageType.'''TEXTURE'''
* Material.FrobStageType.'''NONE'''
=== MaterialStage ===
Note: There are two material stage interfaces, this one covers the read-only methods. If you intend to modify a stage, be sure to use the <tt>EditableMaterialStage</tt> type, which can be acquired through <tt>Material.getEditableStage</tt>
* <tt>MaterialStage.Type getType()</tt> Returns the blend type of this stage (diffuse, specular, blend) (since 2.12)
* <tt>MaterialStage.MapType getMapType()</tt> Get the map type used by this stage (see MaterialStage.MapType below) (since 2.12)
* <tt>string getMapExpressionString()</tt> The map expression used to generate/define the texture of this stage (since 2.12)
* <tt>int getStageFlags()</tt> Returns the combined stage flags value (see MaterialStage.Flag below) (since 2.12)
* <tt>pair getBlendFuncStrings()</tt> Get the blend strings as defined in the material def, e.g. "add" or "gl_one, gl_zero". Returns a tuple of size 2. (since 2.12)
* <tt>Material.ClampType getClampType()</tt> Each stage can have its own clamp type, overriding the per-material one (since 2.12)
* <tt>MaterialStage.TexGenType getTexGenType()</tt> Returns the texgen type: normal, reflect, skybox, etc., use getTexGenParam(i) to retrieve the wobblesky parameters [0..2] (see MaterialStage.TexGenType below) (since 2.12)
* <tt>string getTexGenExpressionString(int index)</tt> TexGen type wobblesky has 3 parameters, get the expressions used to calculate them here. Index in [0..2] (since 2.12)
* <tt>string getColourExpressionString(MaterialStage.ColourComponent selector)</tt> Returns the expression to calculate the R/G/B/A vertex colour values. The selectors RGB and RGBA will only return a non-empty string if all the expressions are actually the same.(since 2.12)
* <tt>MaterialStage.VertexColourMode getVertexColourMode()</tt> Returns the vertex colour mode, if specified (see MaterialStage.VertexColourMode below) (since 2.12)
* <tt>List(MaterialStage.Transformation) getTransformations() The list of transformations defined in this stage, in the order they appear in the declaration (since 2.12)</tt>
* <tt>Vector2 getRenderMapSize()</tt> Returns the dimensions specifying the map size for stages using the "mirrorRenderMap", "remoteRenderMap" keywords. (since 2.12)
* <tt>string getAlphaTestExpressionString()</tt> Get the alpha test expression of this stage (since 2.12)
* <tt>string getConditionExpressionString()</tt> Get the condition expression of this stage (since 2.12)
* <tt>string getVertexProgram()</tt> Returns the name of this stage's vertex program (since 2.12)
* <tt>string getFragmentProgram()</tt> Returns the name of this stage's fragment program (since 2.12)
* <tt>int getNumVertexParms()</tt> The number of defined vertex parameters (since 2.12)
* <tt>int getNumFragmentMaps()</tt> Returns the number of fragment maps in this stage (since 2.12)
* <tt>MaterialStage.VertexParm getVertexParm(int index)</tt> Returns the indexed vertex parm used in this stage (since 2.12)
* <tt>MaterialStage.FragmentMap getFragmentMap(int index)</tt> Returns the indexed fragment map used in this stage (since 2.12)
* <tt>float getPrivatePolygonOffset()</tt> Returns the private polygon offset of this stage(since 2.12)
=== EditableMaterialStage ===
Note: There are two material stage interfaces, this one covers the writeable one. An <tt>EditableMaterialStage</tt> offers all the functions of a read-only <tt>MaterialStage</tt> plus all the methods to change the stage properties. If you don't intend to modify a stage, consider using the read-only type returned by <tt>Material.getStage</tt> instead.
* <tt>setStageFlag(MaterialStage.Flag flag)</tt> Sets the given stage flag (see MaterialStage.Flag below) (since 2.12)
* <tt>clearStageFlag(MaterialStage.Flag flag)</tt> Clears the given stage flag (see MaterialStage.Flag below) (since 2.12)
* <tt>setMapType(MaterialStage.MapType type)</tt> Sets the map type of this stage (cubemap, map, mirrorrendermap, etc.) (see MaterialStage.MapType below) (since 2.12)
* <tt>setMapExpressionFromString(string expression)</tt> Sets the map expression (an image path, or a more complex map expression) (since 2.12)
* <tt>setBlendFuncStrings(StringPair blendFuncStrings)</tt> Sets the blend func strings of this stage, passed as pair of strings, e.g. ["gl_one", "gl_zero"]. (since 2.12)
* <tt>setAlphaTestExpressionFromString(string expression)</tt> Sets the alpha test expression of this stage (since 2.12)
* <tt>int addTransformation(MaterialStage.TransformType type, string expression1, string expression2)</tt> Appends a new transformation to this stage with the given parameters, returning the index of the newly created slot. (since 2.12)
* <tt>int updateTransformation(int index, MaterialStage.TransformType type, string expression1, string expression2)</tt> Updates an existing transformation of this stage to the given parameters. (since 2.12)
* <tt>int removeTransformation(int index)</tt> Removes an existing transformation from this stage. (since 2.12)
* <tt>setColourExpressionFromString(MaterialStage.ColourComponent selector, string expression)</tt> Sets the R/G/B/A/RGB/RGBA colour expression to use in this stage (since 2.12)
* <tt>setConditionExpressionFromString(string expression)</tt> Sets the condition expression which enables/disables this stage depending on its value (since 2.12)
* <tt>setTexGenType(MaterialStage.TexGenType type)</tt> Sets the texgen type of this stage (see MaterialStage.TexGenType below) (since 2.12)
* <tt>setTexGenExpressionFromString(int index, string expression)</tt> Sets one of the three texgen expressions used in the wobble sky texgen type (index in [0..2]) (since 2.12)
* <tt>setVertexColourMode(MaterialStage.VertexColourMode mode)</tt> Sets the vertex colour mode of this stage (see MaterialStage.VertexColourMode below) (since 2.12)
* <tt>setClampType(Material.ClampType type)</tt> Sets the clamp type of this stage, overriding the one defined in the material. (since 2.12)
* <tt>setPrivatePolygonOffset(float offset)</tt> Sets the private polygon offset of this stage. (since 2.12)
* <tt>setRenderMapSize(Vector2 dimensions)</tt> Sets the dimensions of the render map used by the render map expressions. (since 2.12)
* <tt>setSoundMapWaveForm(bool waveForm)</tt> Sets the waveform property for stages using the soundmap expression. (since 2.12)
* <tt>setVideoMapProperties(string filePath, bool looping)</tt> Sets the path and loop properties for stages using the videomap expression. (since 2.12)
=== Stage Structures and Enumerations ===
==== MaterialStage.Type ====
* MaterialStage.Type.'''DIFFUSE'''
* MaterialStage.Type.'''BUMP'''
* MaterialStage.Type.'''SPECULAR'''
* MaterialStage.Type.'''BLEND'''
==== MaterialStage.MapType ====
* MaterialStage.MapType.'''MAP'''
* MaterialStage.MapType.'''CUBEMAP'''
* MaterialStage.MapType.'''CAMERACUBEMAP'''
* MaterialStage.MapType.'''VIDEOMAP'''
* MaterialStage.MapType.'''SOUNDMAP'''
* MaterialStage.MapType.'''MIRRORRENDERMAP'''
* MaterialStage.MapType.'''REMOTERENDERMAP'''
==== MaterialStage.Flag ====
* MaterialStage.Flag.'''IGNORE_ALPHATEST'''
* MaterialStage.Flag.'''FILTER_NEAREST'''
* MaterialStage.Flag.'''FILTER_LINEAR'''
* MaterialStage.Flag.'''HIGHQUALITY'''
* MaterialStage.Flag.'''FORCE_HIGHQUALITY'''
* MaterialStage.Flag.'''NO_PICMIP'''
* MaterialStage.Flag.'''MASK_RED'''
* MaterialStage.Flag.'''MASK_GREEN'''
* MaterialStage.Flag.'''MASK_BLUE'''
* MaterialStage.Flag.'''MASK_ALPHA'''
* MaterialStage.Flag.'''MASK_DEPTH'''
* MaterialStage.Flag.'''IGNORE_DEPTH'''
==== MaterialStage.TexGenType ====
* MaterialStage.TexGenType.'''NORMAL'''
* MaterialStage.TexGenType.'''REFLECT'''
* MaterialStage.TexGenType.'''SCREEN'''
* MaterialStage.TexGenType.'''SKYBOX'''
* MaterialStage.TexGenType.'''WOBBLESKY'''
==== MaterialStage.ColourComponent ====
* MaterialStage.ColourComponent.'''RED'''
* MaterialStage.ColourComponent.'''GREEN'''
* MaterialStage.ColourComponent.'''BLUE'''
* MaterialStage.ColourComponent.'''ALPHA'''
* MaterialStage.ColourComponent.'''RGB'''
* MaterialStage.ColourComponent.'''RGBA'''
==== MaterialStage.VertexColourMode ====
* MaterialStage.VertexColourMode.'''NONE'''
* MaterialStage.VertexColourMode.'''MULTIPLY'''
* MaterialStage.VertexColourMode.'''INVERSE_MULTIPLY'''
==== MaterialStage.TransformType ====
* MaterialStage.TransformType.'''TRANSLATE'''
* MaterialStage.TransformType.'''SCALE'''
* MaterialStage.TransformType.'''ROTATE'''
* MaterialStage.TransformType.'''CENTERSCALE'''
* MaterialStage.TransformType.'''SHEAR'''
==== MaterialStage.Transformation ====
* <tt>MaterialStage.TransformType type</tt> The type of this transformation
* <tt>string expression1</tt> The first expression string
* <tt>string expression2</tt> The second expression string (always empty for TransformType.Rotate)
==== MaterialStage.VertexParm ====
* <tt>int index</tt> The index of this vertex parameter
* <tt>List(string) expression</tt> The list of expressions defining this parameter's values (max. 4)
==== MaterialStage.FragmentMap ====
* <tt>int index</tt> The index of this fragment map
* <tt>List(string) options</tt> The list of options passed to this map
* <tt>string mapExpression</tt> The map expression used in this fragment map


=== GlobalDialogManager ===
=== GlobalDialogManager ===
Line 733: Line 1,156:
* <tt>float getFarClipPlaneDistance()</tt> Returns the distance of the camera's cubic clip plane
* <tt>float getFarClipPlaneDistance()</tt> Returns the distance of the camera's cubic clip plane
* <tt>setFarClipPlaneDistance(float newDistance)</tt> Sets the distance of the camera's cubic clip plane
* <tt>setFarClipPlaneDistance(float newDistance)</tt> Sets the distance of the camera's cubic clip plane
* <tt>refresh()</tt> Requests a repaint of the camera view (since 2.13.0)


==== Example Code ====
==== Example Code ====
Line 740: Line 1,164:
  print(camview.getCameraOrigin())
  print(camview.getCameraOrigin())
  camview.setCameraOrigin(dr.Vector3(50,0,50))
  camview.setCameraOrigin(dr.Vector3(50,0,50))
=== GlobalFxManager ===
The FX manager (available since 3.3.0) exposes methods to interact with FX declarations.
* <tt>FxDeclaration findFx(string name)</tt> Finds a named FX declaration. If the declaration is not found, a NULL object is returned, see <tt>FxDeclaration.isNull</tt>.
Example code: 
fx = GlobalFxManager.findFx("fx/sparks")
if not fx.isNull:
    print(fx.getDeclName())
==== FxDeclaration ====
Represents an FX declaration as defined in the .fx file. It inherits all methods from a generic '''Declaration''' object (see DeclarationManager interface).
* <tt>bool isNull()</tt> Returns true if this is a NULL object, e.g. if a non-existent declaration has been requested through GlobalFxManager.findFx
* <tt>string getBindTo()</tt> Returns the name of this declaration, e.g. "fx/sparks"
* <tt>int getNumActions()</tt> Returns the number of actions defined in this effect.
* <tt>FxAction getAction(int index)</tt> Returns the i-th action (index is starting with 0)
==== FxAction ====
The FxAction object offers methods to check the various values set on a single action block.
* <tt>FxAction.Type getActionType()</tt> Returns the type of this action, see '''FxAction.Type''' below.
* <tt>string getName()</tt> Returns the name of this action (which might be an empty string)
* <tt>float getDelayInSeconds()</tt> Returns the action delay in seconds
* <tt>float getDurationInSeconds()</tt> Action duration in seconds, before it is killed or restarted
* <tt>bool getIgnoreMaster()</tt> True: Don't shake the entity this effect is attached to
* <tt>float getShakeTimeInSeconds()</tt> Shake parameter
* <tt>float getShakeAmplitude()</tt> Shake parameter
* <tt>float getShakeDistance()</tt> Shake parameter
* <tt>bool getShakeFalloff()</tt> Shake parameter
* <tt>float getShakeImpulse()</tt> Shake parameter
* <tt>bool getNoShadows()</tt> if this is 1, the light in this effect doesn't cast shadows
* <tt>string getFireSiblingAction()</tt> Causes the sibling action to happen when this action does
* <tt>float getRandomDelay()</tt> Let the delay be random between min and max (in seconds). If both are 0.0 no random delay is active and the regular delay is used instead
* <tt>float getRotate()</tt> According to the docs this is not used
* <tt>bool getTrackOrigin()</tt> Move around with the entity (vs stationary after spawning)
* <tt>bool getRestart()</tt> If this is 1, the action starts again after the 'duration' has run out
* <tt>float getFadeInTimeInSeconds()</tt> Fade in the RGB of the light or model over <time> seconds
* <tt>float getFadeOutTimeInSeconds()</tt> Fade out the light/model. Ignored if fadeIn is set, you can use 2 separate actions (tied together with uselight) if you want a light to fade in and out.
* <tt>float getDecalSize()</tt> Size of the decal (corresponds to "size" keyword)
* <tt>Vector3 getOffset()</tt> Offset from the origin of the entity (or bind point) this action is located at
* <tt>Vector3 getAxis()</tt> Axis of the model, mutually exclusive with angle
* <tt>Vector3 getAngle()</tt> Alternate way of setting the axis of the model
* <tt>string getUseLight()</tt> Returns the name of the action containing the light which should be used
* <tt>string getUseModel()</tt> Modify the model in a named sibling action. Can be used to fade out a particle in a sibling.
* <tt>string getAttachLight()</tt> Attach to external light (a light not defined in the effect) for fading.
* <tt>string getAttachEntity()</tt> Attach to an external entity
* <tt>string getLaunchProjectileDef()</tt> Launches a projectile of the given entityDef
* <tt>string getLightMaterialName()</tt> If not empty, this action spawns a light with this material
* <tt>Vector3 getLightRgbColour()</tt> For FxAction.Type.Light actions, this defines the RGB colour components
* <tt>float getLightRadius()</tt> For FxAction.Type.Light actions, this defines the radius of the spawned light
* <tt>string getModelName()</tt> Return the name of the model or particle
* <tt>string getDecalMaterialName()</tt> For FxAction.Type.Decal actions, this defines the decal material name
* <tt>bool getParticleTrackVelocity()</tt> Unused according to docs
* <tt>string getSoundShaderName()</tt> For FxAction.Type.:Sound actions: start a sound (on any channel)
* <tt>string getShockwaveDefName()</tt> For FxAction.Type.Shockwave actions: the name of the shockwave entityDef
==== FxAction.Type ====
An enumeration of the available FX action types known to DarkRadiant:
* FxAction.Type.'''Undefined'''
* FxAction.Type.'''Light'''
* FxAction.Type.'''Particle'''
* FxAction.Type.'''Decal'''
* FxAction.Type.'''Model'''
* FxAction.Type.'''Sound'''
* FxAction.Type.'''Shake'''
* FxAction.Type.'''AttachLight'''
* FxAction.Type.'''AttachEntity'''
* FxAction.Type.'''Launch'''
* FxAction.Type.'''Shockwave'''


[[Category:DarkRadiant]]
[[Category:DarkRadiant]]

Latest revision as of 06:12, 2 January 2023

DarkRadiant is offering a Python script interface which provides access to the most important functions, such as the Virtual File System, the Shader System and the Scenegraph. A complete reference of all available classes can be found later in this article.

If you just want to run the scripts, see here: Running Scripts in Darkradiant.

Entering Script Code

Script code can be brought to execution by either entering it in the ad-hoc scripting window (in the group dialog) or by saving it in a .py file in the install/scripts/ folder and running it by entering the command "RunScript yourfile.py" in the command console. Python files are loaded and interpreted each time the runscript command occurs, so it's easy to tweak your code and test it in DarkRadiant right after you hit the save button.

There is a test.py in DarkRadiant's scripts/ folder, which demonstrates large parts of this interface.

The 'darkradiant' Module

All DarkRadiant classes and types are in the darkradiant module which can be imported like this

import darkradiant as dr

One can of course omit the as dr alias, but it's less typing this way. All the "Global*" objects like GlobalShaderSystem (see below) are already exposed to scripts. The rest needs to imported from the darkradiant module and referred to by the prefix "dr".

Classes and Methods

DarkRadiant's "internal C++ code is organised into various modules. Each module provides a set of functions, for instance: the GlobalMaterialManager object provides methods to acquire information about all available shaders; the GlobalBrushCreator can be called whenever a new brush should be instanced. The script interface is following the same route and exposes most of these modules to scripting. The following should give you an overview of all the module objects available for your scripts. Examples are given whenever possible.

GlobalSceneGraph

When a map is loaded, the SceneGraph is populated with so-called SceneNodes. Each node represents an object in the map, be it a brush, a patch, an entity or a model (technically, a model is attached as child to a single entity). Each scenegraph has one single root, which can be access through the GlobalSceneGraph module.

  • SceneNode root() Returns the reference to the root node of the global scenegraph. This can return an empty "NULL" node if no map is loaded at invocation time.

SceneNode

A SceneNode provides a set of methods to gain information about its type, its position, etc. A SceneNode is a general object, its actual type can be BrushNode, PatchNode, EntityNode or ModelNode. Each SceneNode can act as parent (or container) to one or many SceneNodes, but each SceneNode can only have one parent at a time. The methods of a general SceneNode are as follows:

  • isNull() Returns true if this node is "empty", i.e. it is the NULL node. Calling methods on a NULL node doesn't have any effect.
  • addToContainer(SceneNode newContainer) Adds this node as child to the given container.
  • removeFromParent() Removes this node from any parent container. If this node has no parent, nothing happens.
  • AABB getWorldAABB() Returns the bounding box (absolute coordinates) of this node. This includes the bounding boxes of all child nodes as well.
  • SceneNode getParent() Returns the parent of this node. If this node doesn't have a parent, a NULL node is returned.
  • string getNodeType() Returns the type string of this node. Possible values: "map", "entity", "patch", "brush", "model", "particle", "entityconnection", "mergeaction", "unknown"
  • traverse(SceneNodeVisitor visitor) Traverses this Node and all its children using the given Visitor object. See the tutorial about scenegraph traversal for more information.
  • traverseChildren(SceneNodeVisitor visitor) Traverses all the children of this node using the given Visitor object. See the tutorial about scenegraph traversal for more information. (since 1.8.1)
  • setSelected(bool isSelected) Sets the selection status of this node, i.e. setSelected(1) will select this node. Not all nodes are selectable (ModelNodes, for example).
  • invertSelected() Inverts the selection status of this node, i.e. if it is selected before this call, it will be deselected. Not all nodes are selectable.
  • bool isSelected() Returns the selection status of this node. A return value true means that this node is selected.

SceneGraph Traversal

It's possible to iterate over a given node's children which happens in a distinct way. In order to do that, a "SceneNodeVisitor" object is needed which is (as the name states) "visiting" each node along the route.

A node traversal works like this: first, the node itself is visited (depth 0), then all its children (depth 1). At each node the visitor will visit all the children first, before it continues to visit the "sibling" nodes.

This is a working code example where a visitor will traverse the entire scenegraph (i.e. a whole map):

import darkradiant as dr

# This is the visitor object
class SceneWalker(dr.SceneNodeVisitor) :
 	def pre(self, node):
		# Print the type string of each visited node
		print(node.getNodeType())
		return 1

# Instantiate a new walker object
walker = SceneWalker()
GlobalSceneGraph.root().traverse(walker)

Let's say we have a simple scenegraph containing a root node. The root node has two entity nodes as children. The first entity (which is usually the worldspawn) is parent of two brush nodes, the second entity has no children (could be a light). When this scenegraph is traversed (starting from the root), the visitor will produce the following output:

entity
primitive
primitive
entity

Looking closely at this route, it is obvious that Entity 1's children are traversed before Entity 2, which is important. The visitor will always try to gain more "depth" before continuing to traverse on the same depth. It is possible to prevent traversal of a node's children: the visitor just needs to return false (0) when visiting a certain node. Let's say you don't want to traverse the worldspawn brushes, because you're interested in entities only:

import darkradiant as dr

# This visitor will NOT traverse children of entities
class EntityWalker(dr.SceneNodeVisitor) :
 	def pre(self, node):
		# Check whether we have an entity
		if node.isEntity():
			# ...
			# do something with this entity
			# ...
			return 0 # return false: don't traverse entities
		else:
			return 1 # not an entity, return true to traverse children

# Instantiate a new entity walker object
walker = EntityWalker()
GlobalSceneGraph.root().traverse(walker)

The output will be something like this:

entity
entity

You might wonder why the visit function is called pre. There is indeed a post function, which can be added to the visitor object, optionally. When the post function is defined, it will be invoked after the walker has finished traversing a node's children. This is an example:

import darkradiant as dr

# This visitor has both pre and post functions defined
class SceneWalker(dr.SceneNodeVisitor) :
	def pre(self, node):
		# Print the type string of each visited node
		print('Pre: ' + node.getNodeType())
		return 1
	def post(self, node):
		# Print the type string of each visited node
		print('Post: ' + node.getNodeType())

# Instantiate a new walker object
walker = SceneWalker()
GlobalSceneGraph.root().traverse(walker)

Using this walker, the output will be something like this:

Pre: entity
Pre: primitive
Post: primitive
Pre: primitive
Post: primitive
Post: entity
Pre: entity
Post: entity

As obvious, the visitor visited the first entity (pre), then its children are traversed, and finally the entity is visited once more (post), before the walker proceeds to the next entity. Note: the post method doesn't need to return anything, unlike the pre method. Most of the time you don't need to define a post method, but it might prove to be useful sometimes.

Special SceneNode Types

A SceneNode is just a general object. For some purposes it might be enough to have a SceneNode in your hands, but sometimes you'll want to know the actual node type, whether it is a brush, a patch, an entity or a model. Each SceneNode has a couple of is*() and get*() methods, like isBrush() and getBrush(). You can use the is*() methods to check whether a node is of a specific type, and the get*() methods to convert a SceneNode to a special node type. An example:

if node.isBrush():
	print('Node is a brush!')
else:
	print('Node is not a brush.')

If you want actually do something with a brush, more than just confirming its type, you'll want to go with this code:

brush = node.getBrush()
if not brush.isNull():
	# We've successfully converted the SceneNode into a BrushNode
	print('Found a brush with ' + str(brush.getNumFaces()) + ' faces')
else:
	print('Node is not a brush')

The above code attempts to convert an existing node to a BrushNode. This will succeed only if the node is actually of the correct type, otherwise a NULL node will be returned, which is what the code above checks. If the brush object is not the NULL node, the cast succeeded and we have a valid brushnode in our hands.

There exist analogous methods for entities, models and patches, they are called:

  • isEntity()
  • EntityNode getEntity()
  • isPatch()
  • PatchNode getPatch()
  • isModel()
  • ModelNode getModel()

Each node type provides some special methods, additionally to the ones that come with a SceneNode. A BrushNode has all the methods of a SceneNode, plus a few more.

BrushNode

  • int getNumFaces() Returns the number of faces of this brush.
  • Face getFace(int faceIndex) Returns the face with the given index (see below for further description about a Face).
  • bool empty() returns true (1) if this brush has no faces.
  • bool hasContributingFaces() Returns true (1) if this brush has contributing (non-degenerate) faces.
  • removeEmptyFaces() removes degenerate faces.
  • setShader(string newShader) Sets the shader of all faces of this brush.
  • bool hasShader(string shaderName) Returns true (1) if one or more faces of this brush carries the given shader.
  • bool hasVisibleMaterial() Returns true (1) if one or more faces of this brush carry a visible shader (since 1.3.2).
  • undoSave() Saves the current state of this brush to the UndoSystem's stack, call this before manipulating it.
  • getDetailFlag() Returns the detail/structural flag for this brush (Values: BrushDetailFlag.Detail and BrushDetailFlag.Structural). (since 1.8.1)
  • setDetailFlag(BrushDetailFlag) Sets the detail/structural flag for this brush (Values: BrushDetailFlag.Detail and BrushDetailFlag.Structural) (since 1.8.1).
Face
  • undoSave() Saves the current state of this face to the UndoSystem's stack, call this before manipulating it.
  • setShader(string newShader) Sets the shader of this face.
  • string getShader() Returns the shader name of this face.
  • shiftTexdef(s,t) shifts the texture of this face by s,t in texture space.
  • scaleTexdef(s_scale, t_scale) scales the tex def by the given factors in texture space.
  • rotateTexdef(float angle) rotates the texture by the given angle.
  • fitTexture(s_repeat, t_repeat) fits the texture to this face, so that it repeats the given amount of times.
  • flipTexture(int axis) flips the texture by the given flipAxis (0 == x-axis, 1 == y-axis)
  • normaliseTexture() This translates the texture as much towards the origin in texture space as possible without changing the world appearance.
  • Winding getWinding() Get read access to this Face's Winding object (see below).
Winding

A winding holds the vertices of a face. It can be enumerated using a foreach loop, whereas each element is of type WindingVertex. The WindingVertex members are as below, read-only:

  • Vector3 vertex the 3D coordinates of the point
  • Vector2 texcoord the UV coordinates
  • Vector3 tangent the tangent
  • Vector3 bitangent the bitangent
  • Vector3 normal the normal vector
  • unsigned adjacent the index of the adjacent WindingVertex

PatchNode

  • setDims(unsigned width, unsigned height) sets the new patch dimensions.
  • int getWidth() returns the patch width (number of columns), returns -1 if the object is not a patch.
  • int getHeight() returns the patch height (number of rows), returns -1 if the object is not a patch.
  • PatchControl ctrlAt(unsigned row, unsigned col) returns the PatchControl structure for row (h) and col (w). See below for a PatchControl description.
  • string getShader() Returns the shader name for this patch.
  • setShader(string newShaderName) Sets the shader name for this patch.
  • bool hasVisibleMaterial() returns true (1) if the patch has a visible material assigned to it, false otherwise (since 1.3.2).
  • insertColumns(unsigned colIndex) Inserts two columns before and after the column with index <colIndex>.
  • insertRows(unsigned rowIndex) Inserts two rows before and after the row with index <rowIndex>.
  • removePoints(bool columns, unsigned index) Removes columns or rows right before and after the col/row with the given index, reducing the according dimension by 2.
  • appendPoints(bool columns, bool beginning) Appends two rows or columns at the beginning or the end.
  • bool isValid() Check if the patch has invalid control points or width/height are zero
  • bool isDegenerate() Check whether all control vertices are in the same 3D spot (with minimal tolerance)
  • bool subdivionsFixed() Gets whether this patch is a patchDef3 (fixed tesselation) - Note: the typo is actually there
  • bool subdivisionsFixed() Gets whether this patch is a patchDef3 (fixed tesselation) (since 2.0.5)
  • Subdivisions getSubdivisions() Returns the x,y subdivision values (for tesselation), see Subdivision for a further description of the return value
  • setFixedSubdivisions(bool isFixed, Subdivisions divisions) Sets the subdivision of this patch: isFixed: TRUE, if this patch should be a patchDef3 (fixed tesselation), divisions: a two-component vector containing the desired subdivisions.
  • controlPointsChanged() Updates the patch tesselation matrix, call this everytime you're done with your PatchControl changes.
  • PatchMesh getTesselatedPatchMesh() Returns a (read-only) structure containing information about the current patch geometry, fully tesselated. The structure PatchMesh holds width, height and vertex information (see below).
PatchMesh

The PatchMesh holds an array of Vertex info objects, the number of which is depending on the amount of subdivisions of the patch. Members are:

  • width the width of the tesselated matrix.
  • height the height of the tesselated matrix.
  • vertices an enumerable structure containing all the vertices of the patch. Each element is of type PatchMeshVertex (see below). Changing the vertices will not affect the patch, this information is just a copy of the actual data. The vertex at w,h can be directly accessed using vertices[h*width + w].
PatchMeshVertex

A PatchMeshVertex contains information about a single vertex of the patch mesh returned by getTesselatedPatchMesh(). It has three members:

  • Vector3 vertex the 3D point of this vertex.
  • Vector2 texcoord the UV coordinates.
  • Vector3 normal the normal vector.
PatchControl

A PatchControl is a structure containing information about a patch vertex. It has the following members:

  • vertex This is a vector holding the 3D coordinates of this control point, see Vector3.
  • texcoord This is a vector holding the 2D texture coordinates of this control point, see Vector2.
Subdivisions

This is a two-component vector holding two unsigned integers, defining the number of horizontal/vertical tesselations for this patch.

  • x The number of horizontal subdivisions, e.g. patch.getSubdivisions().x()
  • y The number of vertical subdivisions, e.g. patch.getSubdivisions().y()

EntityNode

  • string getKeyValue(string key) Returns the value of the given entity key (=spawnarg).
  • setKeyValue(string key, string value) Sets the value of the named key, i.e. setKeyValue('health', '100').
  • forEachKeyValue(EntityVisitor visitor) Iterates over all spawnargs of this entity. This requires an EntityVisitor object, which will visit all spawnargs (see below).
  • bool isModel() Returns true if this entity is a model.
  • bool isOfType(string className) Returns true if this entity is of type or inherits from the given entity class name. className is treated case-sensitively (new in 1.8.1).
  • bool isInherited(string key) Returns true (1) when the given key is an inherited one.
  • EntityClass getEntityClass() Returns the reference to the EntityClass (the object representing the entityDef) of this entity.
  • EntityKeyValuePairs getKeyValuePairs(string prefix) Returns a list of all spawnargs on this entity matching the given prefix. This does not include inherited keyvalues.
EntityVisitor

An EntityVisitor object can be used to traverse the list of spawnargs on a given entity. Such an object just needs to implement a single visit function, see this example:

import darkradiant as dr

# This is the prototype of an EntityVisitor object
class MyEntityVisitor(dr.EntityVisitor) :
	def visit(self, key, value):
		print('Worldspawn has spawnarg: ' + key + ' = ' + value)

worldspawn = GlobalMap.getWorldSpawn()
if not worldspawn.isNull():
	ev = MyEntityVisitor()

	# Cast the node onto an entity
	worldspawnent = worldspawn.getEntity()

	worldspawnent.forEachKeyValue(ev)

ModelNode

ModelNodes provide access to the model geometry and shaders, e.g. a chest model of a specific entity. ModelNodes are usually encountered as child of an EntityNode. ModelNodes cannot have any child nodes.

  • string getFilename() Returns the filename (without path) of this model.
  • string getModelPath() Returns the VFS path which can be used to load this model from the modelcache.
  • int getSurfaceCount() Return the number of material surfaces on this model. Each material surface consists of a set of polygons sharing the same material.
  • int getVertexCount() Return the number of vertices in this model, equal to the sum of the vertex count from each surface.
  • int getPolyCount() Return the number of triangles in this model, equal to the sum of the triangle count from each surface.
  • MaterialList getActiveMaterials() Return a vector of strings listing the active materials used in this model, after any skin remaps. The list is owned by the model instance.
  • ModelSurface getSurface(int surfaceIndex) Retrieve the interface of a specific surface, to get access to the surface's polygons and vertices. (since 1.5.0)
ModelSurface

A ModelSurface represents a single mesh, which is part of a model. Each ModelSurface consists of a set of vertices, forming polygons using the same material/shader (since 1.5.0).

  • string getDefaultMaterial() Get the name of the default material for this surface, i.e. the name of the material without any skin applied.
  • string getActiveMaterial() Get the name of the currently mapped material (with skin applied) (since 2.6.0)
  • int getNumTriangles() Returns the number of tris of this surface.
  • int getNumVertices() Returns the number of vertices of this surface.
  • MeshVertex getVertex(int vertexIndex) Get a specific vertex of this surface, holding vertex, colour, tangent, normal, etc.
  • ModelPolygon getPolygon(int polygonIndex) Returns a specific polygon from this model surface. Don't expect this to be fast as things are returned by value. This is merely to provide read access to the model polygons for scripts and plugins.
MeshVertex

A MeshVertex is a structure representing a model vertex. It holds the 3D coordinates, the texture coordinates, normal, tangent and bitangent vectors as well as the vertex colour (since 1.5.0). (This type has been named ArbitraryMeshVertex until 2.14.)

  • Vector2 texcoord The 2D texture coordinates
  • Vector3 vertex The 3D coordinates
  • Vector3 normal The vertex normal
  • Vector3 tangent The tangent vector
  • Vector3 bitangent The bitangent vector
  • Vector3 colour The vertex colour
ModelPolygon

A model polygon is a triangle holding three MeshVertex structures a, b and c (since 1.5.0).

  • MeshVertex a The first vertex of this polygon
  • MeshVertex b The second vertex of this polygon
  • MeshVertex c The third vertex of this polygon

GlobalDeclarationManager

The declaration manager (available since 3.1.0) offers methods to interact with the declarations like Materials, Skins, ModelDefs defined throughout the mod. It can iterate through existing declarations, find them, manipulate them and even save them back to disk. See also the Test Python Script (scripts/test.py) in DarkRadiant's installation location.

  • Declaration findDeclaration(Declaration.Type type, string name) Finds a named declaration. If the declaration is not found, a NULL object is returned, see Declaration.isNull.
  • Declaration findOrCreateDeclaration(Declaration.Type type, string name) Finds an existing named declaration or creates an empty one if no declaration with that name exists yet. Will always return a non-null object.
  • Declaration foreachDeclaration(Declaration.Type type, DeclarationVisitor visitor) Calls the visit method of the given visitor class, see the example below.
  • bool renameDeclaration(Declaration.Type type, string oldName, string newName) Renames the declaration from oldName to newName. The new name must not be in use by any other declaration, and it must be different from oldName, otherwise renaming will fail. Returns true if the old declaration existed and could successfully be renamed, false on any failure.
  • removeDeclaration(Declaration.Type type, string name) Removes the given declaration from the internal dictionaries. This doesn't remove the declaration from the source files, so this operation will not survive a reloadDeclarations command. Used to remove temporary decls in edit scenarios.
  • reloadDeclarations() Reload all declarations. All declaration references your script may hold will stay intact, only their contents will be refreshed.
  • saveDeclaration(Declaration decl) Saves the given declaration to a physical declaration file. Depending on the original location of the declaration the outcome will be different (see notes below).

Notes on saveDeclaration

It is required for the declaration to have valid file information set on its syntax block, otherwise the declaration manager will not know where to save it to.

  • Case #1: Newly created declarations (created through findOrCreateDeclaration): The decl will be appended to the given file. The file will be created if required.
  • Case #2: Existing declarations (with their original file being a physical file): The decl in the file will be replaced with its new syntax block. All the content before and after the declaration will be left untouched.
  • Case #3: Existing declarations (with their original file being stored within a PK4): The decl file will be copied and saved to its corresponding physical location, effectively creating a file that will override the one in the PK4. The decl will be merged into the file just like in case #2

Declaration.Type

An enumeration of the available decl types supported by DarkRadiant:

  • Declaration.Type.Material
  • Declaration.Type.Table
  • Declaration.Type.EntityDef
  • Declaration.Type.SoundShader
  • Declaration.Type.ModelDef
  • Declaration.Type.Particle
  • Declaration.Type.Skin

Declaration

Represents a generic declaration as defined in the .mtr, .skin and .def files throughout the active mod or mission project.

  • bool isNull() Returns true if this is a NULL object, e.g. if a non-existent declaration has been requested through DeclarationManager.findDeclaration
  • string getDeclName() Returns the name of this declaration, e.g. "textures/common/caulk"
  • Type getDeclType() Returns the declaration type, e.g. Declaration.Type.Skin
  • DeclarationBlockSyntax getBlockSyntax() Returns the syntax block containing the raw source text
  • setBlockSyntax(DeclarationBlockSyntax syntax) Assigns a new syntax block to this declaration
  • string getDeclFilePath() Returns the mod-relative path of the file this declaration has been defined in (e.g. "materials/test.mtr")
  • setDeclFilePath(string folder, string filename) Sets the mod-relative folder and filename of this declaration (useful right before saving a newly created declaration), Example: setDeclFilePath("materials/", "test.mtr")

DeclarationBlockSyntax

The syntax block contains the raw text contents as found in the file the declaration was defined in. The contents property holds the source text excluding the name and the outermost surrounding curly braces, so only the inner part is stored here. It can be modified and saved back into a declaration using setBlockSyntax.

  • typeName Returns typename as defined in the source file (can also be empty if none was specified)
  • name Returns the name of this block
  • contents Returns the raw contents of this block, excluding the name and the outermost surrounding curly braces
  • modName Returns the name of the mod/FM/project this block has been declared in.

DeclarationVisitor

A DeclarationVisitor can be used to iterate over all existing declarations of a given type. It just needs a single method definition named visit:

  • visit(Declaration decl) Is called for each known Declaration.

This code example can be used as template when writing scripts for declarations; it shows how to print the name and filename of each skin declaration:

import darkradiant as dr

# Test implementing a DeclarationManager interface
class TestDeclarationVisitor(dr.DeclarationVisitor) :
   def visit(self, decl):
       print(str(decl.getDeclType()) + ": " + decl.getDeclName() + " defined in " + decl.getDeclFilePath())

visitor= TestDeclarationVisitor()
GlobalDeclarationManager.foreachDeclaration(Declaration.Type.Skin, visitor)

Entity Classes

GlobalEntityClassManager

The global entity class manager provides methods to retrieve existing entity classes. It also holds all the model definitions, which carry information about meshes and animations.

  • EntityClass findClass(string classname) Finds an entity class by name. If the class with the given name doesn't exist, a NULL object is returned.
  • forEachEntityClass(EntityClassVisitor visitor) Iterates over all existing entity classes using the given visitor object.
  • ModelDef findModel(string modelDefName) Returns the model def with the given name. If it doesn't exist, the returned ModelDef is empty, including its name.
  • forEachModelDef(ModelDefVisitor visitor) Iterates over all existing model definitions using the given visitor object.

(Note: forEachEntityClass has been introduced in DarkRadiant 1.7.0, it was previously named forEach)

EntityClassVisitor

An EntityClassVisitor can be used to iterate over all existing entityDefs. It just needs a single function definition named visit:

  • visit(EntityClass eclass) Is called for each known EntityClass.

This code example can be used as template when writing scripts for entityclasses; it shows how to print the "editor_usage" spawnarg of each entityDef:

import darkradiant as dr

# Test implementing a eclass visitor interface
class TestVisitor(dr.EntityClassVisitor) :
	def visit(self, eclass):
		print eclass.getAttribute('editor_usage').getValue()

eclassVisitor = TestVisitor()
GlobalEntityClassManager.forEachEntityClass(eclassVisitor)

ModelDefVisitor

A ModelDefVisitor can be used to iterate over all existing model definitions. It just needs a single function definition named visit:

  • visit(ModelDef modelDef) Is called for each known model declaration.

This code example can be used as template when writing scripts for model definitions; it shows how to print the "mesh" property of each modelDef:

# Test implementing a model def visitor interface
class TestModelDefVisitor(ModelDefVisitor) :
	def visit(self, modelDef):
		print(modelDef.mesh)

modelDefVisitor = TestModelDefVisitor()
GlobalEntityClassManager.forEachModelDef(modelDefVisitor)

EntityClass

An EntityClass represents what modders know as entityDef. An entityDef represents a collection of spawnargs, pre-defining a certain entity type. Its interface is pretty simple:

  • isNull Returns true if this entityclass is a NULL object, i.e. is empty. This is usually the case if an nonexisting eclass was requested from the GlobalEntityClassManager.
  • bool isOfType(string className) Returns true if this eclass is of type or inherits from the given entity class name. className is treated case-sensitively. (new in 1.8.1)
  • EntityClassAttribute getAttribute(string key) Returns the named attribute (spawnarg) of this entityclass. The returned attribute can be empty if the key is not defined.
  • string getDefFileName() Returns the mod-relative path to the .def file this entity class is defined in (since 2.8.1).

EntityClassAttribute

An EntityClassAttribute represents a spawnarg on a given entityDef. It contains not only the key and the value, but also additional information about its type and (possibly) a description.

  • getName() Returns the name of this attribute (i.e. the key), for example: "spawnclass".
  • getValue() Returns the value of this attribute.
  • getType() Returns the type string of this attribute - this can be "string", "bool", "sound", "float", etc.
  • getDescription() Returns the description, as provided by an "editor_*" spawnarg.
  • inherited Returns TRUE if this attribute has been inherited from a parent entityDef.

(Note: up to DarkRadiant 1.6.1 the accessors to the entityclass attribute values were named "name", "value", "type" and "description", this has been changed to member methods in 1.7.0+.)

ModelDef

A ModelDef represents a model {} block as defined in the .def files of the game. A ModelDef primarily contains information about meshes and animations.

  • name The name of this modelDef.
  • mesh The value of the "mesh" property, usually pointing to an .md5mesh file in TDM.
  • skin The skin property. This is empty if no skin is used by this model.
  • parent The parent def this modelDef is inheriting from.
  • anims The list of anims. This basically is a key => value map, which can be iterated over like shown in the following code snippet.
# Try to find the modeldef of the builder forger
modelDef = GlobalEntityClassManager.findModel('builderforger')
print('ModelDef mesh for builderforger = ' + modelDef.mesh)

# Iterate over all the animations for this modelDef
for anim in modelDef.anims:
	print(anim.key())
	print(' = ')
	print(anim.data())
	print()

GlobalEntityCreator

The entity creator can be used (as the name implies) to create entities in the scene.

It offers two flavours (so-called overloads) of the method "createEntity":

  • SceneNode createEntity(string entityClassName) Create an entity of the given class, specified by name, e.g. "atdm:playertools_lantern"
  • SceneNode createEntity(EntityClass eclass) Create an entity of the given class, as acquired by the GlobalEntityClassManager

After creation, be sure to insert the entity into some parent node, which is always the root node for idTech4 maps.

GlobalCommandSystem

The global command system can be used to execute DarkRadiant commands, as entered manually in the console.

  • execute(string command) Executes the given string command.
  • addStatement(string statementName, string str) Adds the given <str> as new statement with the given name.
  • removeCommand Removes the command with the given name from the command system.

Example:

# Test the commandsystem (this stretches the texture of the selection by 10%)
GlobalCommandSystem.execute('texscale "0 0.1"')

GlobalFileSystem

This global object allows the client to browse the so-called Virtual File System, which lists both the contents of the mod folders ("base", "darkmod", etc.) as well as the contents of the PK4 files in them.

  • forEachFile(string baseDir, string extension, FileVisitor visitor, int depth) Traverses the virtual filesystem, taking "baseDir" as starting point (e.g. "models/"), using "extension" to filter the visiited files and the given "visitor" to visit each file. The depth parameter can be used to restrict the traversal to a maximum folder depth.
  • string findFile(string relativeFilename) Returns the absolute filename for the given relative filename.
  • string findRoot(string absFilename) Returns the filesystem root for the given absolute filename, basically converting it to a relative filename.
  • string readTextFile(string relativeFilename) Returns the full text contents of the given filename.
  • int getFileCount(string filename) Returns the number of files in the VFS matching the given filename.

FileVisitor

A FileVisitor is needed to traverse the GlobalFileSystem using its forEachFile() method. The visitor just needs to provide a single "visit" method, which is called for each matching file.

  • visit(string filename) Is called by forEachFile() for each matching filename.

GlobalGameManager

The GlobalGameManager object knows about all the available games. DarkRadiant supports a number of different "games", with each being defined in its own .game file in the install/ folder.

  • string getUserEnginePath() Returns the user's local engine path, on POSIX systems this might point to the folder in the home directory, e.g. ~/.doom3/ if it exists. If no engine directory is found in the home directory, the regular engine path is returned, e.g. /usr/local/doom3 or c:\games\doom3 (since 2.2.0)
  • string getModPath() Returns the current mod path, e.g. C:\Games\Doom3\darkmod, or ~/.doom3/darkmod. Returns the mod base path if the mod path itself is empty.
  • string getModBasePath() Returns the current mod base path, e.g. C:\Games\Doom3\gathers, or ~/.doom3/gathers. can be an empty string if fs_game_base is not set.
  • Game currentGame() Returns the active game object.
  • StringVector getVFSSearchPaths Returns a list of strings with the current search path, i.e. the search priorities. Topmost folder are searched first. The list can be iterated using Python's "for .. in .." construct.

Game

  • string getKeyValue(string key) Returns a key value as defined in the .game file for this game object. E.g. "basegame" will return "base" for the Doom 3 game.

GlobalRegistry

The registry allows storing persistent data for the application. Use this to save information for use in later script calls (e.g. to store the last filename). The DarkRadiant registry is XML-based, so the keys are actually XPaths. Be specific and use distinct xpath specifications, for instance user/scripts/aseExport/recentFilename

  • string get(path) Returns the string value for the given path. Returns empty if nothing found.
  • set(path, value) Set the string value for the given path, overwriting any existing value.

GlobalGrid

The GlobalGrid object can be used to set the grid size of the current viewports.

  • int getGridPower() Returns the currently active grid size in powers of two. The value is in the range [-3 .. 8], with -3 mapping to 0.125 and 8 mapping to 256.
  • setGridSize(int gridsize) Set the current grid size to the given power of two. The value must be in the range [-3 .. 8], with -3 referring to 0.125 and 8 referring to 256.
  • float getGridSize()Returns the currently active grid size in absolute units (e.g. 0.125 .. 256)
  • gridDown() Decreases the grid size (stops at 0.125)
  • gridUp() Increases the grid size (stops at 256)

GlobalMap

The GlobalMap object represents the currently loaded map. Its interface is quite thin at the moment:

  • SceneNode getWorldSpawn() Returns the worldspawn of the currently loaded map. This can be a NULL node if no map is active or no worldspawn has been created yet.
  • SceneNode getRoot() Returns the root node of the currently loaded map. This can be a NULL node if no map is active. (since 2.13.0)
  • bool isModified() Returns true (1) if the current map has been modified. (since 2.13.0)
  • string getMapName() Returns the name of the currently loaded map. This is "unnammed.map" for an unsaved map.
  • MapEditMode getEditMode() Returns the current edit mode. This is either MapEditMode.Normal or MapEditMode.Merge (since 2.13.0)
  • setEditMode(MapEditMode mode) Sets the current edit mode. (since 2.13.0)
  • StringList getPointFileList() Gets the list of available point files for the current map. (since 2.13.0)
  • showPointFile(string path) Loads and displays the given point file. (since 2.13.0)
  • isPointTraceVisible() Returns true (1) if there's a point file visualisation active. (since 2.13.0)

Math Objects

The most important math objects as used by the internal C++ code are exposed to scripting. This includes the most widely used three-component vector "Vector3" as well as the axis aligned bounding box object AABB, among others.

Vector2

A Vector2 is a two-component floating point vector.

  • x Returns a reference to the first component x of this vector.
  • y Returns a reference to the second component y of this vector.
  • float getLength() Returns the length of this vector.
  • float getLengthSquared() Returns the squared length (x^2 + y^2)
  • float dot(Vector2 other) Returns the result of the inner product of this Vector2 with a second Vector2.
  • Vector2 crossProduct(Vector2 other) Returns the resulting vector of the cross product of this Vector2 with one another.

Vector3

A Vector3 is a three-component floating point vector.

  • x Returns a reference to the first component x of this vector.
  • y Returns a reference to the second component y of this vector.
  • z Returns a reference to the third component z of this vector.
  • float getLength() Returns the length of this vector.
  • float getLengthSquared() Returns the squared length (x^2 + y^2 + z^2)
  • float dot(Vector3 other) Returns the result of the inner product of this Vector3 with a second Vector3.
  • Vector3 crossProduct(Vector3 other) Returns the resulting vector of the cross product of this Vector3 with one another.
  • Vector3 getNormalised() Returns a normalised copy of this vector, leaves this vector untouched.
  • normalise() Normalises this vector. After this call, this vector is a unit vector.
  • Vector3 getInversed() Returns an inversed copy of this vector, with the components <1/x 1/y 1/z>.
  • float angle(Vector3 other) Returns the angle between this vector and the "other" Vector3.
  • bool isParallel(Vector3 other) Returns true (1) if this vector is parallel to the "other" vector.

Vector4 / Quaternion

A Vector4 is a four-component floating-point Vector, also used to represent Quaternions. Both Quaternion and Vector4 are valid object types and implement the same interface.

  • x Returns a reference to the first component x of this vector.
  • y Returns a reference to the second component y of this vector.
  • z Returns a reference to the third component z of this vector.
  • w Returns a reference to the fourth component w of this vector.
  • float dot(Vector4 other) Returns the result of the inner product of this Vector4 with a second Vector4.
  • Vector3 getProjected() Projects this Vector4 into three dimensional space, by dividing the first three components by w and returning the resulting Vector3.

Vector Arithmetics

All Vector objects support the most important operators, each compatible with a Vector of the same type.

  • +
  • -
  • +=
  • -=
  • < (lesser than, only supported by Vector2 and Vector3)

AABB

AABB is an abbreviation of "Axis-Aligned Bounding Box". An AABB can be seen as rectangular box, providing an outer bound of the object it contains. Each two planes of an AABB are parallel to one of the orthogonal xy, yz and xz planes.

  • AABB() Constructs an empty bounding box, which is invalid until its origin and extents are set to something valid.
  • AABB(Vector3 origin, Vector3 extents) Constructs a valid bounding box, using the given origin and extents.
  • Vector3 origin This property can be used to access the center Vector3 of this bounding box.
  • extents This property provides access to the symmetrical extents (the Vector3 pointing from the center to one corner)
  • bool isValid() Returns true (1) if this AABB is valid.
  • float getRadius() Returns the radius of this bounding box, i.e. the length of the "extents" vector.
  • includePoint(Vector3 other) Modifies this bounding box to include the given point, extending it when necessary.
  • includeAABB(AABB other) Modifies this bounding box to include the given AABB, extending it when necessary.

GlobalRadiant

The "Radiant" module plays a slightly different role for scripting than it does for the "internal" C++ code. Here, it provides some "convenience" methods.

  • EntityNode findEntityByClassname(string name) Returns the first matching entity with the given classname in the current scenegraph. Returns a NULL node if nothing is found.
  • EntityNode findEntityName(string name) Returns the entity with the given name in the current scenegraph. Returns a NULL node if nothing is found (since 3.6.0).

Example:

worldspawn = Radiant.findEntityByClassname("worldspawn")
worldspawn.setKeyValue('test', 'success')
print('Worldspawn edited')

Or:

worldspawn = Radiant.findEntityByName("world")
worldspawn.setKeyValue('test', 'success')
print('Worldspawn edited')

GlobalSelectionSystem

The GlobalSelectionSystem object is the one managing the current selection. It provides methods to globally change selection states and to iterate over the existing selection.

  • SelectionInfo getSelectionInfo() Returns the reference to the internal counters of the selectionsystem, which can be used to check how many objects of which type are currently selected.
  • foreachSelected(SelectionVisitor visitor) Visits the current selection using the given Visitor object (not counting components).
  • foreachSelectedComponent(SelectionVisitor visitor) Visits the current component selection using the given Visitor object.
  • foreachSelectedFace(SelectedFaceVisitor visitor) Visits all selected faces using the given FaceVisitor object (since 2.13.0).
  • setSelectedAll(bool selected) Sets the selection status of all objects in the scenegraph (not counting components like Vertices and Edges).
  • setSelectedAllComponents(bool selected) Sets the selection status of all components in the scenegraph (Vertices, Edges, Faces).
  • SceneNode ultimateSelected() Returns a reference to the last selected object. Will throw an exception if called with an empty selection, so check first using getSelectionInfo().
  • SceneNode penultimateSelected() Returns a reference to the penultimate selected object. Will throw an exception if called with less than two objects selected, so check first using getSelectionInfo().

Visiting Faces

The following snippet calls the visitFace method for every selected face in the scene:

# Visit every selected face
import darkradiant as dr

class FaceVisitor(dr.SelectedFaceVisitor) :
	def visitFace(self, face):
		print(face.getShader())

visitor = FaceVisitor()
GlobalSelectionSystem.foreachSelectedFace(visitor)

SelectionInfo

This is the object returned by GlobalSelectionSystem.getSelectionInfo(). It provides just a few counters which can be used to inspect the currently selected object.

  • int totalCount The total number of selected objects, including components.
  • int patchCount The number of selected patches.
  • int brushCount The number of selected brushes.
  • int entityCount The number of selected entities.
  • int componentCount The number of selected components (Faces, Edges, Vertices).

GlobalSelectionSetManager

The GlobalSelectionSetManager object is the one maintaining the selection sets in the scene. It provides methods to create/delete selection sets and to iterate over the existing set. (Since 1.4.0.)

  • foreachSelectionSet(SelectionSetVisitor visitor) Traverses the available selection sets using the given visitor object. See install/scripts/test.py for an example.
  • SelectionSet createSelectionSet(string name) Creates a new selection set or overwrites the existing one with the given name.
  • deleteSelectionSet(string name) Deletes the named selection set.
  • deleteAllSelectionSets() Deletes ALL selection sets (irreversibly).
  • SelectionSet findSelectionSet(string name) Finds the selection set with the given name. Use the empty() method of the SelectionSet to check if the lookup succeeded.

SelectionSet

This is the object returned by GlobalSelectionSetManager .createSelectionSet() and GlobalSelectionSetManager .findSelectionSet(). (Since 1.4.0.)

  • string getName() Returns the name of this selection set.
  • bool empty() Returns TRUE if this selection set is empty.
  • clear() Empties this selection set.
  • select() Selects all members/nodes of this selection set.
  • deselect() De-selects all members/nodes of this selection set.
  • assignFromCurrentScene() Clears this set and loads the currently selected nodes in the scene as new members into this set.

GlobalSelectionGroupManager

The GlobalSelectionGroupManager (not to be confused with the above Selection Set Manager) object provides routines for organising and manipulating groups. (since 2.4.0).

  • SelectionGroup createSelectionGroup() Creates a new selection group and returns it.
  • SelectionGroup getSelectionGroup(int id) Returns the selection group with the given ID.
  • SelectionGroup findOrCreateSelectionGroup(int id) Returns the selection group with the given ID. The group will be created if it doesn't exist yet.
  • setGroupSelected(int id, int selected) Selects or deselects all elements of the group with the given ID. Pass 1 to the selected argument to select items, 0 otherwise.
  • deleteAllSelectionGroups() Deletes ALL selection groups from the map. The actual elements are not removed, just the grouping information is removed.
  • deleteSelectionGroup(int id) Removes the selection group with the given ID. The actual elements are not removed, just the grouping information is removed.

SelectionGroup

This is the object returned by GlobalSelectionGroupManager.createSelectionGroup, GlobalSelectionGroupManager.findOrCreateSelectionGroup and GlobalSelectionGroupManager.getSelectionGroup. (Since 2.4.0.)

  • int getId() Returns the ID of this selection group.
  • string getName() Returns the name of this selection group.
  • setName(string name) Sets the name of this selection group.
  • addNode(SceneNode node) Adds a scene node to this group.
  • removeNode(SceneNode node) Removes a scene node from this group.
  • int size() Returns the number of elements in this group.
  • clear() Empties this selection set.
  • setSelected(int selected) Selects/deselects all members/nodes of this group (pass 1 to select, 0 to deselect).
  • foreachNode(SelectionGroupVisitor visitor) For every node in this group, call the visit method of the given visitor (see below).

SelectionGroupVisitor

Create an object deriving from this SelectionGroupVisitor and use it to visit every member of a selection group.

  • visit(SceneNode node) Required method which is called for every group member when using SelectionGroup.foreachNode()

Example

import darkradiant as dr

# List nodes in this group
class SelectionGroupWalker(dr.SelectionGroupVisitor) :
	def visit(self, node):
		print('Group Member: ' + node.getNodeType())

groupWalker = SelectionGroupWalker()
group.foreachNode(groupWalker)

GlobalLayerManager

The GlobalLayerManager instance provides methods for organising and manipulating layers. (since 2.10.0).

  • int createLayer(string name) Creates a new layer with the given name, returns the ID.
  • deleteLayer(int id) Deletes the layer with the given ID.
  • foreachLayer(LayerVisitor visitor) Calls the given visitor object with the id and name of each layer.
  • int getLayerID(string name) Looks up the ID for the given named layer, returns -1 if the layer doesn't exist.
  • string getLayerName(int id) Looks up the name for the given layer ID, returns an empty string if the layer doesn't exist.
  • bool layerExists(int id) Returns true if the layer with the given ID exists, false otherwise.
  • bool renameLayer(int id, string newName) Renames the layer with the given ID, returns true on success.
  • int getFirstVisibleLayer() Returns the ID of the first visible layer.
  • int getActiveLayer() Returns the ID of the active layer.
  • setActiveLayer(int id) Makes the layer with the given ID the active layer.
  • bool layerIsVisible(int id) Returns true if the layer with the given ID is visible, false otherwise.
  • bool layerIsVisible(string name) Returns true if the layer with the given name is visible, false otherwise.
  • setLayerVisibility(string name, bool visible) Makes the layer with the given name visible or invisible, depending on the value of the "visible" flag.
  • setLayerVisibility(int id, bool visible) Makes the layer with the given ID visible or invisible, depending on the value of the "visible" flag.
  • addSelectionToLayer(int id) Adds the current map selection to the layer with the given ID.
  • addSelectionToLayer(string name) Adds the current map selection to the layer with the given name.
  • moveSelectionToLayer(int id) Moves the current map selection to the layer with the given ID.
  • moveSelectionToLayer(string name) Moves the current map selection to the layer with the given name.
  • removeSelectionFromLayer(int id) Removes the current map selection from the layer with the given ID.
  • removeSelectionFromLayer(string name) Removes the current map selection from the layer with the given name.
  • setSelected(int id, bool selected) Selects or deselects all members of the layer with the given ID.

LayerVisitor

Create an object deriving from this LayerVisitor and use it to visit every layer in the loaded map.

  • visit(int layerId, string layerName) Required method which is called for every layer when using GlobalLayerManager.foreachLayer()

Example

import darkradiant as dr

class LayerPrinter(dr.LayerVisitor):
    def visit(self, layerID, layerName):
        print(layerID, layerName)
layerPrinter = LayerPrinter()
GlobalLayerManager.foreachLayer(layerPrinter)

GlobalMaterialManager

This object holds all the shaders as parsed from the material (.mtr) files in the materials/ folders. Use this to retrieve a given material object and get information about them.

  • foreachMaterial(MaterialVisitor visitor) Visit each known material with the given visitor object.
  • Material getMaterial(string name) Returns the material object for the given name. Returns a NULL object if nothing is found (isNull() will return true).
  • bool materialExists(string name) Returns true if the named material is existing, false otherwise (since 2.12)
  • bool materialCanBeModified(string name) Returns true if the named material can be modified (is not defined in a PK4 files), false otherwise (since 2.12)
  • Material createEmptyMaterial(string name) Creates a new material using the given name. In case the name is already in use, a generated one will be assigned to the created material. (since 2.12)
  • Material copyMaterial(string nameOfOriginal, string nameOfCopy) Creates a copy of the given material and returns the reference to it. (since 2.12)
  • bool renameMaterial(string oldName, string newName) Renames the material named oldName to newName, and returns true if the operation was successful. If the new name is already in use, this returns false too. (since 2.12)
  • void removeMaterial(string name) Removes the named material. (since 2.12)
  • void saveMaterial(string name) Saves the named material to the file location as specified in its file info. If the path is not writable or the material is not suitable for saving, this will throw an exception. (since 2.12)
  • deprecated since 2.12: foreachShader(MaterialVisitor visitor) Visit each known material with the given visitor object.
  • deprecated since 2.12: Shader getMaterialForName(string name) Returns the material object for the given name. Returns a NULL object if nothing is found (isNull() will return true).

MaterialVisitor

A MaterialVisitor is needed for the GlobalMaterialManager.foreachMaterial() method to iterate over known materials. (Old name until 2.11 was: ShaderVisitor)

  • visit(Material s) Is invoked by the foreachMaterial() routine for each material, passing the object along.

This example script will print all materials and the files they're defined in:

import darkradiant as dr

# This is the material visitor object we will use to traverse the materials
class TestMaterialVisitor(dr.MaterialVisitor) :
	def visit(self, material):
		if not material.isNull():
			print('Found material: ' + material.getName() + ' defined in ' + material.getShaderFileName())

materialvisitor = TestMaterialVisitor()
GlobalMaterialManager.foreachMaterial(materialvisitor)

Material

The material object wraps around a known declaration, holding information about the shader stages and other things. (Old name until 2.11 was: Shader)

  • bool isNull() Returns true (1) if this a NULL material.
  • string getName() Returns the full name of this shader, e.g. "textures/darkmod/stone/brick/blocks_mixedsize01"
  • string getShaderFileName() Returns the filename this shader is defined in (e.g. "materials/tdm_stone_brick.mtr")
  • string getDescription() Returns the description string as parsed from the material.
  • bool isModified() Returns true (1) if this material has been modified (programmatically). (since 2.12)
  • string getDefinition() Returns the parsed (or generated) material definition source (the part between the two outermost curly braces).
  • bool isVisible() Returns true if this shader is visible, i.e. not currently filtered.
  • bool isAmbientLight() Returns true (1) if this is an ambient light material.
  • bool isBlendLight() Returns true (1) if this is a blend light material.
  • bool isFogLight() Returns true (1) if this is a fog light material.
  • bool isCubicLight() Returns true (1) if this is a cubic light material. (since 2.12)
  • string getEditorImageExpressionString() Returns the qer_editorImage part (since 2.12)
  • float getSortRequest() Returns the value of the "sort" keyword in this material (since 2.12)
  • float getPolygonOffset() Return a polygon offset if one is defined. The default is 0. (since 2.12)
  • Material.ClampType getClampType() Get the desired texture repeat behaviour (since 2.12)
  • Material.CullType getCullType() Get the cull type (none, back, front) (since 2.12)
  • int getMaterialFlags() Get the combined bit flags that are set on this material (see Material.Flag below) (since 2.12)
  • int getSurfaceFlags() Get the combined bit surface flags that are set on this material (see Material.SurfaceFlag below) (since 2.12)
  • Material.SurfaceType getSurfaceType() Get the surface type (wood, flesh, etc.) of this material (see Material.SurfaceType below) (since 2.12)
  • Material.DeformType getDeformType() Get the deform type (flare, sprite, ...) of this material (see Material.DeformType below) (since 2.12)
  • string getDeformExpressionString(int index) Returns the shader expression used to define the deform parameters (valid indices in [0..2]) (since 2.12)
  • string getDeformDeclName() Used for DeformType.PARTICLE/PARTICLE2; defines the name of the particle def (since 2.12)
  • int getSpectrum() Returns the spectrum of this shader, 0 is the default value (even without keyword in the material) (since 2.12)
  • Material.DecalInfo getDecalInfo() Returns the decal info structure of this material (since 2.12)
  • Material.Coverage getCoverage() The evaluated coverage of this material (see Material.Coverage below) (since 2.12)
  • string getLightFalloffExpressionString() Returns the map expression used to define the light falloff image (since 2.12)
  • MaterialStage.MapType getLightFalloffCubeMapType() Returns the map type of the light falloff image (cubeMap, map) (since 2.12)
  • string getGuiSurfArgument() The argument to the "guisurf" keyword, if not entity[2]3]. In case entity[2]3] is set, the corresponding surface flags are enabled (since 2.12)
  • string getRenderBumpArguments() Returns the argument string after the renderbump keyword, or an empty string if no statement is present (since 2.12)
  • string getRenderBumpFlatArguments() Returns the argument string after the renderbumpflat keyword, or an empty string if no statement is present (since 2.12)
  • (List of ScriptMaterialStage) getAllStages() Returns the list of all stages in this material (since 2.12)
  • int getNumStages() Return the number of stages in this material (since 2.12)
  • MaterialStage getStage(int index) Returns the stage with the given index (since 2.12)

The following methods can only be called on materials that can be modified, otherwise an exception will be thrown. Check GlobalMaterialManager.materialCanBeModified() first.

  • revertModifications() Undo all changes to this material since it was last saved(since 2.12)
  • EditableMaterialStage getEditableStage(int index) Returns the editable stage with the given index (since 2.12)
  • setShaderFileName(string fullPath) Set the mtr file name to define where this material should be saved to (since 2.12)
  • setDescription(string description) Set the material description (since 2.12)
  • setEditorImageExpressionFromString(string editorImagePath) Sets the qer_editorImage path of this material. (since 2.12)
  • setSortRequest(float/SortRequest value) Sets the sort request value of this material. See the predefined SortRequest values below (since 2.12)
  • resetSortRequest() Resets the sort request value of this material to its default. (since 2.12)
  • setPolygonOffset(float offset) Set the polygon offset of this material (since 2.12)
  • clearPolygonOffset() Removes the polygon offset from this material (since 2.12)
  • setClampType(Material.ClampType type) Set the desired texture repeat behaviour (see Material.ClampType below) (since 2.12)
  • setCullType(Material.CullType type) Set the cull type (see Material.CullType below) (since 2.12)
  • setMaterialFlag(Material.Flag flag) Set the given material flag (see Material.Flag below) (since 2.12)
  • clearMaterialFlag(Material.Flag flag) Clear the given material flag (see Material.Flag below) (since 2.12)
  • setSurfaceFlag(Material.SurfaceFlag flag) Set the given surface flag (see Material.SurfaceFlag below) (since 2.12)
  • clearSurfaceFlag(Material.SurfaceFlag flag) Clear the given surface flag (see Material.SurfaceFlag below) (since 2.12)
  • setSurfaceType(Material.SurfaceType type) Set the surface type (wood, flesh, etc.) of this material (see Material.SurfaceType below) (since 2.12)
  • setSpectrum(int spectrum) Sets the spectrum of this material (since 2.12)
  • setIsAmbientLight(int newValue) Pass true (1) to enable the ambient light flag on this material (since 2.12)
  • setIsBlendLight(int newValue) Pass true (1) to enable the blend light flag on this material (since 2.12)
  • setIsFogLight(int newValue) Pass true (1) to enable the fog light flag on this material (since 2.12)
  • setIsCubicLight(int newValue) Pass true (1) to enable the cubic light flag on this material (since 2.12)
  • setLightFalloffExpressionFromString(string expression) Set the light falloff map expression (since 2.12)
  • setLightFalloffCubeMapType(MaterialStage.MapType type) Set the map type of the light falloff image (since 2.12)
  • int addStage(MaterialStage.Type type) Create a new stage with the given type, returns the index of the new stage (since 2.12)
  • removeStage(int index) Removes the stage with the new index (since 2.12)
  • int duplicateStage(int index) Duplicates the stage with the given index, returns the index of the new stage (since 2.12)
  • swapStagePosition(int first, int second) Swaps the position of the two given stages. (since 2.12)
  • Material.FrobStageType getFrobStageType() Returns the frob stage type used by this material. (since 3.8.0) - see FrobStageType
  • setFrobStageType(Material.FrobStageType type) Sets the frob stage type used by this material. (since 3.8.0)
  • string getFrobStageMapExpressionString() Returns the frob stage map expression used for frob stage type TEXTURE. (since 3.8.0)
  • setFrobStageMapExpressionFromString(string expression) Sets the frob stage map expression used for frob stage type TEXTURE. (since 3.8.0)
  • Vector3 getFrobStageRgbParameter(int index) Returns one of the two frob stage RGB parameters (index can be 0 or 1), as used by this material. (since 3.8.0)
  • setFrobStageParameter(double value) Assigns the same value to all three RGB components of the frob stage parameter with the given index (which can be 0 or 1). (since 3.8.0)
  • setFrobStageRgbParameter(Vector3 rgb) Sets the RGB components of the frob stage parameter with the given index (which can be 0 or 1). (since 3.8.0)

Material.SurfaceType

  • Material.SurfaceType.DEFAULT
  • Material.SurfaceType.METAL
  • Material.SurfaceType.STONE
  • Material.SurfaceType.FLESH
  • Material.SurfaceType.WOOD
  • Material.SurfaceType.CARDBOARD
  • Material.SurfaceType.LIQUID
  • Material.SurfaceType.GLASS
  • Material.SurfaceType.PLASTIC
  • Material.SurfaceType.RICOCHET
  • Material.SurfaceType.AASOBSTACLE
  • Material.SurfaceType.SURFTYPE10
  • Material.SurfaceType.SURFTYPE11
  • Material.SurfaceType.SURFTYPE12
  • Material.SurfaceType.SURFTYPE13
  • Material.SurfaceType.SURFTYPE14
  • Material.SurfaceType.SURFTYPE15

Material.Flag

These are bit flags that can be set/cleared/combined on a material.

  • Material.Flag.NOSHADOWS
  • Material.Flag.NOSELFSHADOW
  • Material.Flag.FORCESHADOWS
  • Material.Flag.NOOVERLAYS
  • Material.Flag.FORCEOVERLAYS
  • Material.Flag.TRANSLUCENT
  • Material.Flag.FORCEOPAQUE
  • Material.Flag.NOFOG
  • Material.Flag.NOPORTALFOG
  • Material.Flag.UNSMOOTHEDTANGENTS
  • Material.Flag.MIRROR
  • Material.Flag.POLYGONOFFSET
  • Material.Flag.ISLIGHTGEMSURF

Material.SurfaceFlag

Various flags that can be set/cleared/combined on a material

  • Material.SurfaceFlag.SOLID
  • Material.SurfaceFlag.OPAQUE
  • Material.SurfaceFlag.WATER
  • Material.SurfaceFlag.PLAYERCLIP
  • Material.SurfaceFlag.MONSTERCLIP
  • Material.SurfaceFlag.MOVEABLECLIP
  • Material.SurfaceFlag.IKCLIP
  • Material.SurfaceFlag.BLOOD
  • Material.SurfaceFlag.TRIGGER
  • Material.SurfaceFlag.AASSOLID
  • Material.SurfaceFlag.AASOBSTACLE
  • Material.SurfaceFlag.FLASHLIGHT_TRIGGER
  • Material.SurfaceFlag.NONSOLID
  • Material.SurfaceFlag.NULLNORMAL
  • Material.SurfaceFlag.AREAPORTAL
  • Material.SurfaceFlag.NOCARVE
  • Material.SurfaceFlag.DISCRETE
  • Material.SurfaceFlag.NOFRAGMENT
  • Material.SurfaceFlag.SLICK
  • Material.SurfaceFlag.COLLISION
  • Material.SurfaceFlag.NOIMPACT
  • Material.SurfaceFlag.NODAMAGE
  • Material.SurfaceFlag.LADDER
  • Material.SurfaceFlag.NOSTEPS
  • Material.SurfaceFlag.GUISURF
  • Material.SurfaceFlag.ENTITYGUI
  • Material.SurfaceFlag.ENTITYGUI2
  • Material.SurfaceFlag.ENTITYGUI3

Material.SortRequest

Pre-defined sort request constants as corresponding to the TDM engine code:

  • Material.SortRequest.SUBVIEW
  • Material.SortRequest.GUI
  • Material.SortRequest.BAD
  • Material.SortRequest.OPAQUE
  • Material.SortRequest.PORTAL_SKY
  • Material.SortRequest.DECAL
  • Material.SortRequest.FAR
  • Material.SortRequest.MEDIUM
  • Material.SortRequest.CLOSE
  • Material.SortRequest.ALMOST_NEAREST
  • Material.SortRequest.NEAREST
  • Material.SortRequest.AFTER_FOG
  • Material.SortRequest.POST_PROCESS

Material.ClampType

  • Material.ClampType.REPEAT default = no clamping
  • Material.ClampType.NOREPEAT "clamp"
  • Material.ClampType.ZEROCLAMP zeroclamp"
  • Material.ClampType.ALPHAZEROCLAMP "alphazeroclamp"

Material.CullType

  • Material.CullType.BACK (default)
  • Material.CullType.FRONT (backsided)
  • Material.CullType.NONE (twosided)

Material.DeformType

  • Material.DeformType.NONE
  • Material.DeformType.SPRITE
  • Material.DeformType.TUBE
  • Material.DeformType.FLARE
  • Material.DeformType.EXPAND
  • Material.DeformType.MOVE
  • Material.DeformType.TURBULENT
  • Material.DeformType.EYEBALL
  • Material.DeformType.PARTICLE
  • Material.DeformType.PARTICLE2

Material.DecalInfo

  • int stayMilliSeconds
  • int fadeMilliSeconds
  • Vector4 startColour
  • Vector4 endColour

Material.Coverage

  • Material.Coverage.UNDETERMINED
  • Material.Coverage.OPAQUE
  • Material.Coverage.PERFORATED
  • Material.Coverage.TRANSLUCENT

Material.FrobStageType

Frob stage types supported by TDM 2.11+, see also the descriptive comments on the corresponding tracker entry

  • Material.FrobStageType.DEFAULT
  • Material.FrobStageType.DIFFUSE
  • Material.FrobStageType.TEXTURE
  • Material.FrobStageType.NONE

MaterialStage

Note: There are two material stage interfaces, this one covers the read-only methods. If you intend to modify a stage, be sure to use the EditableMaterialStage type, which can be acquired through Material.getEditableStage

  • MaterialStage.Type getType() Returns the blend type of this stage (diffuse, specular, blend) (since 2.12)
  • MaterialStage.MapType getMapType() Get the map type used by this stage (see MaterialStage.MapType below) (since 2.12)
  • string getMapExpressionString() The map expression used to generate/define the texture of this stage (since 2.12)
  • int getStageFlags() Returns the combined stage flags value (see MaterialStage.Flag below) (since 2.12)
  • pair getBlendFuncStrings() Get the blend strings as defined in the material def, e.g. "add" or "gl_one, gl_zero". Returns a tuple of size 2. (since 2.12)
  • Material.ClampType getClampType() Each stage can have its own clamp type, overriding the per-material one (since 2.12)
  • MaterialStage.TexGenType getTexGenType() Returns the texgen type: normal, reflect, skybox, etc., use getTexGenParam(i) to retrieve the wobblesky parameters [0..2] (see MaterialStage.TexGenType below) (since 2.12)
  • string getTexGenExpressionString(int index) TexGen type wobblesky has 3 parameters, get the expressions used to calculate them here. Index in [0..2] (since 2.12)
  • string getColourExpressionString(MaterialStage.ColourComponent selector) Returns the expression to calculate the R/G/B/A vertex colour values. The selectors RGB and RGBA will only return a non-empty string if all the expressions are actually the same.(since 2.12)
  • MaterialStage.VertexColourMode getVertexColourMode() Returns the vertex colour mode, if specified (see MaterialStage.VertexColourMode below) (since 2.12)
  • List(MaterialStage.Transformation) getTransformations() The list of transformations defined in this stage, in the order they appear in the declaration (since 2.12)
  • Vector2 getRenderMapSize() Returns the dimensions specifying the map size for stages using the "mirrorRenderMap", "remoteRenderMap" keywords. (since 2.12)
  • string getAlphaTestExpressionString() Get the alpha test expression of this stage (since 2.12)
  • string getConditionExpressionString() Get the condition expression of this stage (since 2.12)
  • string getVertexProgram() Returns the name of this stage's vertex program (since 2.12)
  • string getFragmentProgram() Returns the name of this stage's fragment program (since 2.12)
  • int getNumVertexParms() The number of defined vertex parameters (since 2.12)
  • int getNumFragmentMaps() Returns the number of fragment maps in this stage (since 2.12)
  • MaterialStage.VertexParm getVertexParm(int index) Returns the indexed vertex parm used in this stage (since 2.12)
  • MaterialStage.FragmentMap getFragmentMap(int index) Returns the indexed fragment map used in this stage (since 2.12)
  • float getPrivatePolygonOffset() Returns the private polygon offset of this stage(since 2.12)

EditableMaterialStage

Note: There are two material stage interfaces, this one covers the writeable one. An EditableMaterialStage offers all the functions of a read-only MaterialStage plus all the methods to change the stage properties. If you don't intend to modify a stage, consider using the read-only type returned by Material.getStage instead.

  • setStageFlag(MaterialStage.Flag flag) Sets the given stage flag (see MaterialStage.Flag below) (since 2.12)
  • clearStageFlag(MaterialStage.Flag flag) Clears the given stage flag (see MaterialStage.Flag below) (since 2.12)
  • setMapType(MaterialStage.MapType type) Sets the map type of this stage (cubemap, map, mirrorrendermap, etc.) (see MaterialStage.MapType below) (since 2.12)
  • setMapExpressionFromString(string expression) Sets the map expression (an image path, or a more complex map expression) (since 2.12)
  • setBlendFuncStrings(StringPair blendFuncStrings) Sets the blend func strings of this stage, passed as pair of strings, e.g. ["gl_one", "gl_zero"]. (since 2.12)
  • setAlphaTestExpressionFromString(string expression) Sets the alpha test expression of this stage (since 2.12)
  • int addTransformation(MaterialStage.TransformType type, string expression1, string expression2) Appends a new transformation to this stage with the given parameters, returning the index of the newly created slot. (since 2.12)
  • int updateTransformation(int index, MaterialStage.TransformType type, string expression1, string expression2) Updates an existing transformation of this stage to the given parameters. (since 2.12)
  • int removeTransformation(int index) Removes an existing transformation from this stage. (since 2.12)
  • setColourExpressionFromString(MaterialStage.ColourComponent selector, string expression) Sets the R/G/B/A/RGB/RGBA colour expression to use in this stage (since 2.12)
  • setConditionExpressionFromString(string expression) Sets the condition expression which enables/disables this stage depending on its value (since 2.12)
  • setTexGenType(MaterialStage.TexGenType type) Sets the texgen type of this stage (see MaterialStage.TexGenType below) (since 2.12)
  • setTexGenExpressionFromString(int index, string expression) Sets one of the three texgen expressions used in the wobble sky texgen type (index in [0..2]) (since 2.12)
  • setVertexColourMode(MaterialStage.VertexColourMode mode) Sets the vertex colour mode of this stage (see MaterialStage.VertexColourMode below) (since 2.12)
  • setClampType(Material.ClampType type) Sets the clamp type of this stage, overriding the one defined in the material. (since 2.12)
  • setPrivatePolygonOffset(float offset) Sets the private polygon offset of this stage. (since 2.12)
  • setRenderMapSize(Vector2 dimensions) Sets the dimensions of the render map used by the render map expressions. (since 2.12)
  • setSoundMapWaveForm(bool waveForm) Sets the waveform property for stages using the soundmap expression. (since 2.12)
  • setVideoMapProperties(string filePath, bool looping) Sets the path and loop properties for stages using the videomap expression. (since 2.12)

Stage Structures and Enumerations

MaterialStage.Type

  • MaterialStage.Type.DIFFUSE
  • MaterialStage.Type.BUMP
  • MaterialStage.Type.SPECULAR
  • MaterialStage.Type.BLEND

MaterialStage.MapType

  • MaterialStage.MapType.MAP
  • MaterialStage.MapType.CUBEMAP
  • MaterialStage.MapType.CAMERACUBEMAP
  • MaterialStage.MapType.VIDEOMAP
  • MaterialStage.MapType.SOUNDMAP
  • MaterialStage.MapType.MIRRORRENDERMAP
  • MaterialStage.MapType.REMOTERENDERMAP

MaterialStage.Flag

  • MaterialStage.Flag.IGNORE_ALPHATEST
  • MaterialStage.Flag.FILTER_NEAREST
  • MaterialStage.Flag.FILTER_LINEAR
  • MaterialStage.Flag.HIGHQUALITY
  • MaterialStage.Flag.FORCE_HIGHQUALITY
  • MaterialStage.Flag.NO_PICMIP
  • MaterialStage.Flag.MASK_RED
  • MaterialStage.Flag.MASK_GREEN
  • MaterialStage.Flag.MASK_BLUE
  • MaterialStage.Flag.MASK_ALPHA
  • MaterialStage.Flag.MASK_DEPTH
  • MaterialStage.Flag.IGNORE_DEPTH

MaterialStage.TexGenType

  • MaterialStage.TexGenType.NORMAL
  • MaterialStage.TexGenType.REFLECT
  • MaterialStage.TexGenType.SCREEN
  • MaterialStage.TexGenType.SKYBOX
  • MaterialStage.TexGenType.WOBBLESKY

MaterialStage.ColourComponent

  • MaterialStage.ColourComponent.RED
  • MaterialStage.ColourComponent.GREEN
  • MaterialStage.ColourComponent.BLUE
  • MaterialStage.ColourComponent.ALPHA
  • MaterialStage.ColourComponent.RGB
  • MaterialStage.ColourComponent.RGBA

MaterialStage.VertexColourMode

  • MaterialStage.VertexColourMode.NONE
  • MaterialStage.VertexColourMode.MULTIPLY
  • MaterialStage.VertexColourMode.INVERSE_MULTIPLY

MaterialStage.TransformType

  • MaterialStage.TransformType.TRANSLATE
  • MaterialStage.TransformType.SCALE
  • MaterialStage.TransformType.ROTATE
  • MaterialStage.TransformType.CENTERSCALE
  • MaterialStage.TransformType.SHEAR

MaterialStage.Transformation

  • MaterialStage.TransformType type The type of this transformation
  • string expression1 The first expression string
  • string expression2 The second expression string (always empty for TransformType.Rotate)

MaterialStage.VertexParm

  • int index The index of this vertex parameter
  • List(string) expression The list of expressions defining this parameter's values (max. 4)

MaterialStage.FragmentMap

  • int index The index of this fragment map
  • List(string) options The list of options passed to this map
  • string mapExpression The map expression used in this fragment map

GlobalDialogManager

The dialog manager allows you to create popup messages and dialog windows and offers functions to customise them. The interface is like this, see the paragraphs below for some examples:

  • Dialog createDialog(string title) Creates and returns a new Dialog object with the given window title.
  • Dialog createMessageBox(string title, string text, MessageType type) Creates and returns a new popup message object (a popup message is just a specialised dialog, hence the same return type). The MessageType is an "enum" value (see below) and determines which buttons and which icon is displayed in the popup.

Dialog

Once you've created a new Dialog object, it offers the following functions:

  • setTitle(string title): Sets the window title of the dialog, if this hasn't been passed to the createDialog() method already. This way the title can be changed after creation.
  • Dialog.Result run() Displays the dialogs and waits until the user hits any button.
  • Handle addLabel(string labelText) Adds a label with the given text.
  • Handle addComboBox(string label, StringVector options) Adds a combo (dropdown) box with the given options (see below for an example about how to do that).
  • Handle addEntryBox(string label) Adds a text entry box.
  • Handle addPathEntry(string label, bool foldersOnly) Adds a file/folder browse field. When foldersOnly is true (1) the file browser only accepts paths as input.
  • Handle addSpinButton(string label, float min, float max, float step, int digits) Adds a spin button with the given limits [min..max] and the given step size. Floating point values are allowed. (Note: the "digits" parameter was added with DR 1.5.0+).
  • Handle addCheckbox(string label) Adds a simple checkbox (can be ticked on or off).
  • string getElementValue(Handle handle) Retrieves the current value of the element behind the given Handle. Returns an empty string if the Handle is invalid or not known to the dialog.
  • setElementValue(Handle handle, string value). Sets the value of the element specified by the given Handle. The given string is de-serialised into the dialog widgets (e.g. to set the value of a combo box in the dialog to a specific option, just pass the string value of that option). You can also set the "value" of labels in the dialog.

You'll notice that the add* methods return a Handle. This is an unsigned integer carrying the ID of the created element, so that it can be referenced later. Be sure to save that handle into a Python variable if you need to retrieve the value of the added element later down the road.

When the dialog is first created it consists of a title and an OK and CANCEL button only. You'll want to call the add*() methods on the dialog objects to add some elements to it. The elements are inserted in the exact order of the calls, top to bottom, so if you call dialog.addLabel() followed by dialog.addEntryBox() the label will be added first and will be located above the entry box. See below for an example for each of the add*() methods listed above.

MessageType

  • Dialog.CONFIRM: The message carries a "Notification" icon (e.g. a light bulb) and features a single OK button.
  • Dialog.ASK: The message is decorated with a "question" image and offers the buttons YES and NO.
  • Dialog.WARNING: The message has a warning sign on it and has a simple OK button.
  • Dialog.ERROR: The message has an error image (a "stop" sign) on it and has a simple OK button.
  • Dialog.YESNOCANCEL: The message carries three buttons: Yes, No and Cancel. Like the one used for DarkRadiant's overwrite map confirmation dialog.

Result

When a dialog is finished running, the result is returned by the run() method. It can be one of several:

  • Dialog.CANCELLED: The dialog has been cancelled, either by a click on the "Cancel" button or by a click on the window's X element (usually in the upper right corner of the window).
  • Dialog.OK: The user clicked the OK button.
  • Dialog.NO: The user clicked the NO button.
  • Dialog.YES: The user clicked the YES button.

Examples

Popup messages are simple windows with just a string message. A popup message can be one of several types, like Questions, Confirmations, see below. It's best to learn from this example script:

import darkradiant as dr

dialog = GlobalDialogManager.createMessageBox("Confirmation Box", "Confirm this", dr.Dialog.CONFIRM)
dialog.run()

That's as simple as one can get: the code above just creates a new popup message of "CONFIRM" type with "Confirmation Box" as title and "Confirm this" as body text (yes, HTML-like markup is allowed). After creation, the dialog is displayed to the user by calling the run() method. (The result returned by run() is ignored here, as it's not of interest for a confirm popup.

Dialogs are more complex. When calling createDialog() you'll receive an empty dialog window first, only equipped with OK and CANCEL buttons. By calling the add*() methods on the dialog objects, it's possible to add some elements to it, in the given call order:

import darkradiant as dr

# Test creating a new dialog
dialog = GlobalDialogManager.createDialog("Test")

# Add a label
dialog.addLabel("Testlabel")

# Add an entry box and remember the handle
entryHandle = dialog.addEntryBox("Entry")

# Add a spin button
dialog.addSpinButton("Spinner", 0, 10, 0.5)

# Add a combo box, the options must be passed in the form of a StringVector
options = StringVector()
options.append("Test1")
options.append("Test2")
dialog.addComboBox("Test", options)

# Add a simple checkbox
dialog.addCheckbox("TestCheckbox")

if dialog.run() == dr.Dialog.OK:
     print("User clicked OK.")

GlobalSoundManager

The sound manager provides an interface to the sound shader declarations, plus simple playback/stop routines.

  • SoundShader getSoundShader(string shaderName) Looks up the sound shader by name.
  • bool playSound(string fileName) Tries to playback the sound file given by its VFS path. Returns 1 if the sound file could be located, 0 otherwise.
  • stopSound() Stops the currently played sound.

SoundShader

This is the object returned by GlobalSoundManager.getSoundShader(). It resembles a single sound shader declaration in the .sndshd files.

  • bool isNull() Whether this sound shader is the null object (i.e. if the getSoundShader() routine did not find the named shader, a null object will be returned)
  • string getName() The name of this sound shader
  • SoundRadii getRadii() The Radii object containing min/max values.
  • StringVector getSoundFileList() Returns the list of sound files used in this shader (by their VFS path).
  • string getShaderFilePath() Returns the mod-relative path to the .sndshd file this shader has been defined in (since 2.8.1).
  • string getDefinition() Returns the source text of the sound shader declaration (only the inner part within the curly braces) (since 2.8.1).

SoundRadii

This is the object returned by SoundShader.getRadii().

  • float getMin(bool inMetres) Gets the minimum radius of this sound shader. The flag indicates whether the value should be returned in units or meters.
  • setMin(float min, bool inMetres) Set the minimum radius of this sound shader. The flag indicates whether the value is provided in units or meters.
  • float getMax(bool inMetres) Gets the maximum radius of this sound shader. The flag indicates whether the value should be returned in units or meters.
  • setMax(float max, bool inMetres) Set the maximum radius of this sound shader. The flag indicates whether the value is provided in units or meters.

Example Code

soundshader = GlobalSoundManager.getSoundShader('tdm_ai_lady_alertdown_to_idle')

if not soundshader.isNull():
	print('Name of this sound shader: ' + soundshader.getName())

	radii = soundshader.getRadii()

	print('Minimum radius in meters: ' + str(radii.getMin(1)))
	print('Maximum radius in meters: ' + str(radii.getMax(1)))

	fileList = soundshader.getSoundFileList()
	for i in range(0, len(fileList)):
		print(' Sound file used by this shader: ' + fileList[i])

	if (len(fileList) > 0):
		GlobalSoundManager.playSound(fileList[0])

GlobalCameraManager

The camera manager provides an interface to the active camera view of DR. Use it to query or set the active camera's position and angles, among a few other settings.

  • CameraView getActiveView() Returns the active camera (since 2.8.1)

CameraView

This is the object returned by GlobalCameraManager.getActiveView(). It resembles the camera view used to render the 3D view. This whole interface can be found in DR 2.8.1 or higher.

  • Vector3 getCameraOrigin() Returns the current 3D position of the camera.
  • setCameraOrigin(Vector3 newOrigin) Sets the new camera position.
  • Vector3 getCameraAngles() Returns the camera's orientation as Euler angles (pitch, yaw, roll) in degrees.
  • setCameraAngles(Vector3 newAngles) Sets the new camera orientation (pitch, yaw, roll) in degrees.
  • setOriginAndAngles(Vector3 newOrigin, Vector3 newAngles) Sets the new camera position and orientation (pitch, yaw, roll) in degrees.
  • Vector3 getRightVector() Returns the direction pointing towards the right of the camera's view direction
  • Vector3 getUpVector() Returns the direction pointing upwards of the camera's view direction
  • float getFarClipPlaneDistance() Returns the distance of the camera's cubic clip plane
  • setFarClipPlaneDistance(float newDistance) Sets the distance of the camera's cubic clip plane
  • refresh() Requests a repaint of the camera view (since 2.13.0)

Example Code

import darkradiant as dr

camview = GlobalCameraManager.getActiveView()
print(camview.getCameraOrigin())
camview.setCameraOrigin(dr.Vector3(50,0,50))

GlobalFxManager

The FX manager (available since 3.3.0) exposes methods to interact with FX declarations.

  • FxDeclaration findFx(string name) Finds a named FX declaration. If the declaration is not found, a NULL object is returned, see FxDeclaration.isNull.

Example code:

fx = GlobalFxManager.findFx("fx/sparks")

if not fx.isNull:
    print(fx.getDeclName())

FxDeclaration

Represents an FX declaration as defined in the .fx file. It inherits all methods from a generic Declaration object (see DeclarationManager interface).

  • bool isNull() Returns true if this is a NULL object, e.g. if a non-existent declaration has been requested through GlobalFxManager.findFx
  • string getBindTo() Returns the name of this declaration, e.g. "fx/sparks"
  • int getNumActions() Returns the number of actions defined in this effect.
  • FxAction getAction(int index) Returns the i-th action (index is starting with 0)

FxAction

The FxAction object offers methods to check the various values set on a single action block.

  • FxAction.Type getActionType() Returns the type of this action, see FxAction.Type below.
  • string getName() Returns the name of this action (which might be an empty string)
  • float getDelayInSeconds() Returns the action delay in seconds
  • float getDurationInSeconds() Action duration in seconds, before it is killed or restarted
  • bool getIgnoreMaster() True: Don't shake the entity this effect is attached to
  • float getShakeTimeInSeconds() Shake parameter
  • float getShakeAmplitude() Shake parameter
  • float getShakeDistance() Shake parameter
  • bool getShakeFalloff() Shake parameter
  • float getShakeImpulse() Shake parameter
  • bool getNoShadows() if this is 1, the light in this effect doesn't cast shadows
  • string getFireSiblingAction() Causes the sibling action to happen when this action does
  • float getRandomDelay() Let the delay be random between min and max (in seconds). If both are 0.0 no random delay is active and the regular delay is used instead
  • float getRotate() According to the docs this is not used
  • bool getTrackOrigin() Move around with the entity (vs stationary after spawning)
  • bool getRestart() If this is 1, the action starts again after the 'duration' has run out
  • float getFadeInTimeInSeconds() Fade in the RGB of the light or model over
  • float getFadeOutTimeInSeconds() Fade out the light/model. Ignored if fadeIn is set, you can use 2 separate actions (tied together with uselight) if you want a light to fade in and out.
  • float getDecalSize() Size of the decal (corresponds to "size" keyword)
  • Vector3 getOffset() Offset from the origin of the entity (or bind point) this action is located at
  • Vector3 getAxis() Axis of the model, mutually exclusive with angle
  • Vector3 getAngle() Alternate way of setting the axis of the model
  • string getUseLight() Returns the name of the action containing the light which should be used
  • string getUseModel() Modify the model in a named sibling action. Can be used to fade out a particle in a sibling.
  • string getAttachLight() Attach to external light (a light not defined in the effect) for fading.
  • string getAttachEntity() Attach to an external entity
  • string getLaunchProjectileDef() Launches a projectile of the given entityDef
  • string getLightMaterialName() If not empty, this action spawns a light with this material
  • Vector3 getLightRgbColour() For FxAction.Type.Light actions, this defines the RGB colour components
  • float getLightRadius() For FxAction.Type.Light actions, this defines the radius of the spawned light
  • string getModelName() Return the name of the model or particle
  • string getDecalMaterialName() For FxAction.Type.Decal actions, this defines the decal material name
  • bool getParticleTrackVelocity() Unused according to docs
  • string getSoundShaderName() For FxAction.Type.:Sound actions: start a sound (on any channel)
  • string getShockwaveDefName() For FxAction.Type.Shockwave actions: the name of the shockwave entityDef

FxAction.Type

An enumeration of the available FX action types known to DarkRadiant:

  • FxAction.Type.Undefined
  • FxAction.Type.Light
  • FxAction.Type.Particle
  • FxAction.Type.Decal
  • FxAction.Type.Model
  • FxAction.Type.Sound
  • FxAction.Type.Shake
  • FxAction.Type.AttachLight
  • FxAction.Type.AttachEntity
  • FxAction.Type.Launch
  • FxAction.Type.Shockwave