Skip to content

11. Tools and Utilities

Ketei edited this page May 22, 2026 · 3 revisions

Objects

RangeInt / RangeFloat

I. Introduction and Core Principles

The RangeInt and RangeFloat are two distinct, standalone classes that function as data containers. They are designed to hold a numerical value while simultaneously managing its minimum and maximum boundary constraints.

To get a new instance call either RangeInt.new() or RangeFloat.new()

1.1 Purpose and Design

  • Role: Their primary purpose is to define the Stats used in the StatBlock (for Characters and Species). They provide a clean structure for holding a stat's current value and its defined limits.
  • Benefit: By bundling the value and its rules, they simplify stat management, validation, and the implementation of effects that modify stat boundaries (e.g., "Max Health Up").
  • Separation: RangeInt is used for whole numbers, and RangeFloat is used for numbers with decimal precision.

II. Class Properties (API)

Both classes share the exact same five properties. These variables are public and are intended to be accessed and modified directly.

Variable Type Purpose Notes
value int / float The current, active value of the range.
min_value int / float The defined minimum boundary of the value.
max_value int / float The defined maximum boundary of the value.
allow_lesser bool If true, the value is allowed to fall below the min_value. If false, value is clamped to min_value.
allow_greater bool If true, the value is allowed to exceed the max_value. If false, value is clamped to max_value.

Note

The min_value is allowed to push the max_value higher. (e.g., if Max is 100, setting Min to 110 will force Max to also become 110). But the max_value cannot push the min_value lower.

RandomWeightedPool

I. Introduction and Core Principles

The RandomWeightedPool is a standalone object (class) designed to manage a collection of items and facilitate weighted random selection.

To get a new instance use RandomWeightedPool.new()

1.1 Purpose and Design

  • Role: This class is used when you need to randomly select an item from a list, but you want some items to be chosen more frequently than others.
  • Mechanism: It allows you to add any Variant (data, object, resource path, etc.) to a "pool" and assign it a numerical weight. When you ask the pool to pick an item, it calculates the total weight of all items and selects one based on its relative probability.
  • Example:
    • Potion (Weight: 10.0)
    • Sword (Weight: 1.0)
    • Gem (Weight: 0.5) In this pool, the "Potion" is significantly more likely to be picked than the "Gem".

II. Usage in GDScript (API Hooks)

The API provides simple functions for adding items, clearing the pool, and picking a result.

Function Signature Purpose Return Type Notes
add_weighted(item: Variant, weight: float) Adds an item (any data type) to the pool and assigns it a weight. - The weight is a float, allowing for fractional probabilities.
pick_weighted() Primary Function. Calculates the probabilities and returns one randomly selected item from the pool. Variant Returns null if the pool is empty.
remove_item(item: Variant) Removes the specified item from the pool. Bool Returns true if the item was found and removed.
pool_size() Returns the total number of items currently in the pool. Integer
pool_items() Returns an array containing the full pool structure. Array[Dictionary] Each dictionary in the array contains {"item": Variant, "weight": float}.
clear_pool() Empties the entire pool, removing all items and weights. -

BitFlags

I. Introduction and Core Principles

The BitFlags class is a serializable Resource object designed to combine the human-readable convenience of StringName keys with the memory efficiency of bitwise storage.

1.1 Purpose and Design

  • Role: To efficiently manage a large set of boolean states (up to 64 flags).
  • Mechanism: It maps a user-defined StringName (e.g., &"IsPoisoned") to a specific bit index (an integer from 0 to 63). Instead of storing 64 separate boolean variables, the object stores a single 64-bit integer and performs bitwise operations on it.
  • Benefit: This is significantly more memory-efficient than a large dictionary or a class with many boolean properties.
  • Serialization: Because it is a Resource, a BitFlags object can be saved directly into other resources (like a CharacterSheet) or as part of a save file, preserving its state.

Note

By default BitFlags only allows the assignment of 63 bits. To change the size change the constant MAX_BITMASK with a value between 1 and 64 on the BitFlags[1] script.


II. Usage in GDScript (API Hooks)

The API provides functions for registering StringName keys and then setting or checking the boolean state associated with that key's index.

2.1 Flag Registration and Management

These functions manage the mapping between the StringName key and its assigned bit index.

Function Signature Purpose Return Type Notes
create_flag(flag_id: StringName) Registers a new StringName key and assigns it to the next available, unused bit index. Bool Returns true if the flag was created successfully. Fails if the flag ID already exists or if the object is full.
release_flag(flag_id: StringName) Removes the StringName key from the registry and frees up its bit index for future use. -
has_flag(flag_id: StringName) Returns true if the StringName key is registered with this object. Bool
get_flags() Returns a list of all currently registered StringName keys. Array[StringName]
is_full() Returns true if all available bit indices have been assigned. Bool

2.2 State Management (Setting and Checking Flags)

These functions perform the actual bitwise operations to check or change the boolean state.

Function Signature Purpose Notes
set_flag(flag_id, value) Sets the state of the single flag identified by flag_id to true (1) or false (0).
set_flags(flags, value) Sets the state for an entire array of flags simultaneously.
is_flag(flag, value) Checks if the single flag identified by flag_id is currently set to the specified value.
are_flags(flags, value) Checks if all flags in the array are set to the specified value.
clear_flags() Clears the flag registry and the set bits.

LRU Cache

I. Introduction and Core Principles

The Cache class (and its child class ResourceCache) provides a Least Recently Used (LRU) caching system. It is a utility class that developers can instantiate and use for efficient memory management of frequently accessed data or resources.

To get a new instance use Cache.new() or ResourceCache.new() depending on which one you need.

1.1 Purpose (LRU Explained)

A Least Recently Used (LRU) cache maintains a fixed number of items (max_size). Its primary purpose is to keep frequently accessed items (like data or resources) in memory for immediate retrieval.

  • How it works: When you access an item (get_cache), it is moved to the "front" of the cache (marked as the most recently used).
  • Benefit: This is highly efficient for data that is used often but is too large to keep in memory permanently. It leverages Godot's internal caching: as long as the Cache holds a reference to a resource, Godot will not unload it.

1.2 How Items Are Removed (Automatic Background Purge)

Items are not removed explicitly by the user (unless clear() is called). They are purged automatically in the background based on a single rule:

When the cache reaches its max_size (e.g., 50 items) and a new item (the 51st) is added via cache_data(), the item that has gone the longest without being accessed (the Least Recently Used item) is silently dropped from the cache to maintain the size limit.


II. Usage in GDScript: Cache API

This is the base class, which can hold any Variant type.

Property Type Purpose Notes
max_size Integer The maximum number of items the cache can hold. Changing the size will also resize the cache, dropping resources that fall outside of the boundary
Method Signature Purpose Return Type Notes
cache_data(key, data) Adds data to the cache, marking it as the newest item. If the key already exists, it updates the data and marks it as newest. -
get_cache(key) Returns the cached item. Also marks the item as the newest used. Variant Returns null if the key isn't cached
is_in_cache(key: String) Returns true if an item with the specified key is in the cache. Bool
size() Returns the current number of items in the cache. Integer
clear() Empties the entire cache, releasing references. -

III. Usage in GDScript: ResourceCache API (Child Class)

This is a specialized child class that only works with Resource objects. It is designed to handle path-based loading and caching simultaneously.

Method Signature Purpose Return Type Notes
get_resource(path) Primary Function. Returns a resource from the cache. If the resource is not in the cache, it loads the resource from the path, adds it to the cache, and then returns it. Variant If the resource couldn't be loaded returns null and it won't be added to the cache
cache_resource(resource) Manually adds a resource to the cache and marks it as the newest used. If the resource is already in the cache, it is simply marked as newest. - The resource must be a loaded file (have a resource_path) for it to be cached

Static tools

UUID

I. Introduction and Core Principles

The UUID class is a standalone utility script designed to handle the generation and representation of Universally Unique Identifiers (UUIDs).

1.1 Purpose and Design

  • Role: This class provides a reliable method for generating Version 4 (v4) UUIDs, which are randomly generated identifiers. This is essential for creating unique IDs for any data that requires a guaranteed unique reference.
  • Access: The class contains both static functions (for quick generation) and instance methods (for handling a specific UUID object's data).

II. Usage in GDScript (API Hooks)

2.1 Static Generation Functions

These functions are used to quickly generate a new UUID string without needing to instantiate a UUID object.

Function Signature Purpose Return Type Notes
generate_new() Generates a new, standard, random UUID v4 string. String This is the most common function you will use.
generate_with_rng(rng: RandomNumberGenerator) Generates a new UUID v4 string using a provided RandomNumberGenerator instance. String This offers more control over the source of randomness (e.g., using a seeded RNG for deterministic generation).

2.2 Instance Methods (Data Representation)

These methods are used on an instance of a UUID object (e.g., var my_uuid = UUID.new()) to convert its internal data.

Function Signature Purpose Return Type Notes
as_string() Converts the internal raw byte array of the UUID object into the standard UUID v4 string format. String
as_array() Returns the raw 16 bytes of the UUID as a duplicate PackedByteArray. PackedByteArray Useful for network transmission or byte-level storage.
as_dict(big_endian = true) Converts the UUID's raw bytes into a dictionary representation, breaking it down into its standard fields (low, mid, hi, clock, node). Dictionary Supports both big-endian and little-endian byte ordering.
is_equal(other_uuid_object) Compares this UUID object to another UUID object to check if they represent the same identifier. Bool

StringUtils

I. Introduction

The StringUtils class is a static utility script designed to enhance Godot's native string manipulation capabilities. It provides tools for advanced formatting, parsing, type conversion, and similarity analysis.

  • Access: Functions are static and called directly (e.g., StringUtils.beautify_int(1000)).

II. Usage in GDScript (Static API)

2.1 Formatting and Casing

These functions allow for rapid text standardization and UI formatting.

Function Signature Purpose Example
capitalize(string_to_cap: String) Converts the first letter to uppercase and forces the rest of the string to lowercase. "hELLO wORLD""Hello world"
title_case(string_to_title: String) Converts the first letter of every word (separated by space) to uppercase, while lowercasing the rest. "the GREAT sword""The Great Sword"
beautify_int(value: int) Converts an integer into a string with comma separators. 123456789"123,456,789"

2.2 Parsing and Conversion

Functions designed to process raw strings into usable data or structures.

Function Signature Purpose Notes
string_to_variant(string: String) Attempts to auto-parse a string into a float, int, or bool. If the string does not match a number or boolean pattern, it returns the original String itself.
split_and_strip(string: String, delimeter: String, ...) Splits the string by the delimiter and automatically performs strip_edges() on every resulting element. Arguments: allow_empty (bool) and max_split (int) allow for fine-tuning the output array.

2.3 Analysis and Comparison

Functions for checking string content and similarity.

Function Signature Purpose Notes
is_between(string: String, prefix: String, suffix: String) Checks if the string starts with the prefix AND ends with the suffix. Useful for parsing wrapped tags (e.g., checking if "[b]Text[/b]" is between [b] and [/b]).
levenshtein_distance(string_1: String, string_2: String) Quantifies the textual difference (edit distance) between two strings as a normalized value. Return Value:
• Closer to 0.0: Strings are very similar.
• Closer to 1.0: Strings are very different.

RangeUtils

I. Introduction

The RangeUtils class is a static utility script offering helper functions for numerical range checks and integer-based movement interpolation.

  • Access: Functions are static and called directly.

II. Usage in GDScript (Static API)

Function Signature Purpose Notes
move_towardi(from: float, to: float, by: float) An integer-typed version of the standard move_toward function. Moves from toward to by the by amount, but returns the result as an int. Useful for grid-based movement or pixel-perfect interpolation logic where integer results are required.
is_between(value: float, a: float, b: float) Checks if value exists inclusively between the range defined by a and b. Auto-Sorting: a and b do not need to be passed in specific order. The function handles cases where a > b or b > a automatically.

ArrayUtils

I. Introduction

The ArrayUtils class is a utility script providing a comprehensive suite of helper functions for advanced array manipulation, sorting, set operations, and 2D array management.

  • Access: Functions are static and called directly (e.g., ArrayUtils.pop_random(my_array)).

II. Usage in GDScript (Static API)

2.1 Manipulation and Modification

These functions modify the content or order of an existing array.

Function Signature Purpose Notes
pop_random(from) Removes and returns a random item from the array.
switch_indexes(from_idx, to_idx, in_array) Swaps the elements at the specified from_idx and to_idx indexes.
move_item(array, from_idx, to_idx) Moves an item from one index to another, shifting other elements as necessary.
swap_remove(in_array, index) Efficient Removal: Replaces the item at index with the last item in the array, then removes the last item. Order Not Preserved: Much faster than standard removal, but changes the array order.
replace_all(in_array, find, replace_with) Replaces all instances of find with replace_with inside in_array.

2.2 Sorting and Ordered Insertion

Functions for maintaining sorted arrays and custom sorting logic.

Function Signature Purpose Return Type Notes
binary_search(in_array, search_for) Finds target index using Binary Search. Integer Expects ascending sort.
bsearch_array_desc(array, target) Finds target index using Binary Search. Integer Expects descending sort.
insert_sorted_asc(array, item) Inserts item into array while preserving ascending order. - Expects array to be pre-sorted.
insert_sorted_desc(array, item) Inserts item into array while preserving descending order. - Expects array to be pre-sorted.

Custom Sort Comparators: These functions are designed to be passed as arguments to Godot's native Array.sort_custom().

  • sort_custom_desc(a, b): Sorts generic items in descending order.
  • sort_custom_alphabetically_asc(a, b): Sorts strings alphabetically (A-Z), case-insensitive.
  • sort_custom_alphabetically_desc(a, b): Sorts strings alphabetically (Z-A), case-insensitive.

Usage Example: my_array.sort_custom(ArrayUtils.sort_custom_alphabetically_asc)

2.3 Set Operations (Uniques and Differences)

Functions for treating arrays like mathematical sets.

Function Signature Purpose Example
append_uniques(append_to, from) Appends items from from to append_to only if they don't already exist there.
insert_uniques_asc(to, items) Inserts items into to while preserving ascending order, skipping duplicates. Expects to to be sorted.
substract_array(from, substract) Removes all items found in substract from the from array.
symetric_difference(array_a, array_b) Returns a new array containing items unique to each array. diff([a,b], [b,c])[a, c]

2.4 Creation and Structure (Typed & 2D)

Functions for constructing and resizing complex array types.

Function Signature Purpose Notes
create_array_typed(type, from = [], class_string = &"", script = null) Constructor for a strictly typed array with default parameters.
create_array_2d(size_x, size_y, type: int = -1) Creates a pre-sized 2D array (Array of Arrays). Optional type ensures inner arrays are typed.
resize_array_2d(array, new_width, new_height) Resizes an existing 2D array structure.

2.5 Checks and Utilities

Function Signature Purpose Return Type
containsn(array, what) Checks if array contains the string what (Case-Insensitive). Bool
clamp_index(to_array, index) Clamps the given integer so it is a valid index for to_array (0 to size - 1). Integer

BitUtils

I. Introduction and Core Principles

The BitUtils class is a utility script whose sole purpose is to provide a collection of high-performance, low-level helper functions for performing common bitwise operations on integers.

  • Role: Simplifies complex bit manipulation tasks, such as checking or setting multiple flags stored within a single integer.
  • Access: As a static class, its functions are called directly (e.g., BitUtils.get_bits(...)).

II. Usage in GDScript (Static API)

The API provides functions for reading, writing, and checking bits using both indices and masks.

2.1 Bit Manipulation (Using Masks)

A mask is an integer used to define which bits you want to operate on.

Function Signature Purpose Return Type Example
get_bits(from: int, mask: int) Returns only the bits from the from value that are also set in the mask. Integer BitUtils.get_bits(10, 3) (binary 0101, mask 1100) returns 2 (binary 0100).
set_bits(on, mask, enabled) Turns all bits defined by the mask to 1 (if enabled: true) or 0 (if enabled: false) on the on value. Integer
are_bits(on, mask, enabled) Checks if all bits defined by the mask are set to the specified state (enabled) within the on value. Bool

2.2 Bit Manipulation (Using Index)

These functions target a single bit by its numerical index (e.g., 0, 1, 2, ...).

Function Signature Purpose Return Type
`set_bit_index(on: int, bit_index: int, value: bool) Sets the single bit at bit_index (e.g., index 2) within the on value to 1 (true) or 0 (false). Integer
`is_bit_index(on: int, bit_index: int, enabled: bool) Checks if the single bit at bit_index within the on value is currently set to the specified state (enabled). Bool

DictUtils

DictUtils is a static helper class providing utility methods for safely interacting with Godot Dictionary objects. It is specifically designed to handle complex, deeply nested dictionaries—a common structure for RPG data like inventories, character stats, and metadata.

Benefits: Navigating nested dictionaries natively in GDScript often requires repetitive type-checking and has() validations to prevent runtime crashes. DictUtils abstracts this boilerplate away, allowing you to safely retrieve, set, and validate deep paths in a single line of code without risking null reference or index errors.

Method Reference

Method Purpose Return Type Notes
has_any(dict: Dictionary, keys: Array) Checks if the dictionary contains at least one of the provided keys. bool Stops iterating and returns true as soon as the first match is found.
has_nested_path(dict: Dictionary, keys: Array) Verifies if a specific sequence of nested keys exists in the dictionary. bool Safely evaluates each step. Returns false immediately if any key in the path is missing or if an intermediate value is not a dictionary.
get_nested_value(from: Dictionary, keys: Array, default = null) Retrieves a value from a deeply nested dictionary path. Variant Returns the default parameter (which is null by default) if the path doesn't exist or is invalid, completely preventing index errors.
set_nested_value(on: Dictionary, keys: Array, value, create_dictionaries: bool = true) Sets a value at a specific nested path inside the dictionary. bool Returns true if the value was successfully set, or false if the path is invalid (e.g., trying to nest inside a pre-existing integer). If create_dictionaries is true, it automatically builds the required nested dictionaries along the path.

Footnotes

  1. The default path of the BitFlags is: res://addons/nexus_forge/classes/resources/bit_flags.gd.

Clone this wiki locally