Util_Engine

This page documents the Godot utility wrappers for persistent databases, fuzzy search, MIR/STFT and waveform generation, and Beat This detection. Native build, backend, and error contracts are collected at the end.

Godot Utility Classes

Class

Responsibility

PDJE_KeyValueDB

RocksDB-backed text and byte key/value storage.

PDJE_RelationalDB

SQLite execution, queries, and transactions.

PDJE_RelationalRow

Query row with columns and values properties.

PDJE_RelationalExecResult

Affected-row and optional last-insert-row-id result.

PDJE_VectorDB

Annoy-backed nearest-neighbor vector index.

PDJE_VectorItem

Vector item with id, embedding, and text/byte payloads.

PDJE_VectorHit

Search result with id, distance, and payloads.

FuzzyDB

In-memory fuzzy text store and candidate query helper.

PDJE_MIR

STFT, waveform, RGB waveform, and music-analysis facade.

PDJE_StftResult

One STFT frame’s real and imag arrays.

PDJE_AI

Factory for Beat This detectors.

PDJE_BeatThisDetector

Beat/downbeat detector initialized from an ONNX model.

PDJE_BeatThisResult

beats and downbeats timestamps in seconds.

Database Lifecycle

The three persistent DB wrappers share the same lifecycle:

  1. Optionally call Create(…), or let Open(…, create_if_missing=true) create storage.

  2. Check that Open(…) returned true.

  3. Read and mutate through the wrapper-specific methods.

  4. Call Close() before releasing or replacing the node.

  5. Call Destroy(…) only for explicit destructive removal.

Use user:// for writable game data. A res:// path is normally read-only in an exported project.

Key-Value Database

var kv := PDJE_KeyValueDB.new()
if not kv.Open("user://pdje-cache/kv", true):
    push_error("Key-value DB open failed")
    return

if not kv.PutText("artist", "RLIOP913"):
    push_error("Text write failed")
if kv.Contains("artist"):
    print(kv.GetText("artist"))

var blob := PackedByteArray([1, 2, 3])
kv.PutBytes("preview", blob)
print(kv.GetBytes("preview"))
print(kv.ListKeys("art"))

kv.Erase("artist")
kv.Close()

PDJE_KeyValueDB also exposes Create(path, truncate_if_exists), Destroy(path), IsOpen(), and GetPath(). Empty string/byte results can mean missing data or failure, so use Contains() when absence matters.

Relational Database

var sql := PDJE_RelationalDB.new()
if not sql.Open("user://pdje-cache/library.sqlite3", true):
    return

var created: PDJE_RelationalExecResult = sql.Execute(
    "CREATE TABLE IF NOT EXISTS notes(id INTEGER, lane TEXT)")
if created == null:
    push_error("Schema creation failed")
    sql.Close()
    return

if not sql.BeginTransaction():
    sql.Close()
    return

var inserted := sql.Execute(
    "INSERT INTO notes(id, lane) VALUES(?1, ?2)",
    [1, "left"])
if inserted == null:
    sql.Rollback()
    sql.Close()
    return

if not sql.Commit():
    sql.Rollback()

for row: PDJE_RelationalRow in sql.Query(
        "SELECT id, lane FROM notes WHERE id = ?1",
        [1]):
    print(row.columns)
    print(row.values)

sql.Close()

Execute() returns PDJE_RelationalExecResult or null on failure. Its properties are affected_rows, has_last_insert_rowid, and last_insert_rowid. Query() returns an array of PDJE_RelationalRow; each row keeps column names and values in matching order.

Vector Database

The index dimension is fixed by Open()/Create(). Every item and query embedding must have exactly that dimension.

Open(root_path, dimension, trees, prefault, create_if_missing, truncate_if_exists, read_only) fixes the index dimension. The example below uses 10 trees, disables prefault, and creates the index when it is missing; the remaining options keep their defaults.

var vectors := PDJE_VectorDB.new()
if not vectors.Open(
        "user://pdje-cache/vectors",
        3,
        10,
        false,
        true):
    return

var item := PDJE_VectorItem.new()
item.id = "track-a"
item.embedding = PackedFloat32Array([0.9, 0.1, 0.0])
item.text_payload = "high-energy intro"
item.bytes_payload = PackedByteArray()

if not vectors.UpsertItem(item):
    push_error("Vector insert failed")

for hit: PDJE_VectorHit in vectors.Search(
        PackedFloat32Array([1.0, 0.0, 0.0]),
        3,
        -1):
    print(hit.id, " distance=", hit.distance, " payload=", hit.text_payload)

print(vectors.Contains("track-a"))
print(vectors.GetItem("track-a"))
print(vectors.ListKeys())
vectors.EraseItem("track-a")
vectors.Close()

PDJE_VectorDB also reports GetRootPath() and GetDimension(). Reopen an existing index with the same dimension and tree count. prefault asks the backend to preload index pages; create_if_missing, truncate_if_exists, and read_only control storage lifecycle and access mode.

MIR, STFT, And Waveforms

PDJE_MIR exposes analysis values in Godot-native arrays. Methods that search music require an initialized PDJE_Wrapper. A PDJE_KeyValueDB can cache waveform or analysis output where accepted.

STFT From PCM

var mir := PDJE_MIR.new()
var pcm := PackedFloat32Array()
pcm.resize(44100)

var frames: Array[PDJE_StftResult] = mir.STFT_PCM_DATA(
    pcm,
    1,
    PDJE_MIR.HANNING,
    10,
    0.5,
    true,
    true,
    true,
    true,
    true,
    true)

for frame in frames:
    print(frame.real.size(), " ", frame.imag.size())

Arguments after channel_count select the window, FFT-size exponent, overlap, and post-processing flags (toPower, to_bin, normalization, mel scale, dB, and RGB preparation). PCM must be interleaved and aligned to channel_count.

PDJE_MIR window values are BLACKMAN, BLACKMAN_HARRIS, BLACKMAN_NUTTALL, HANNING, NUTTALL, FLATTOP, GAUSSIAN, HAMMING, and NONE.

Music STFT

STFT_MUSIC(core, cache_db, title, composer, bpm, …) searches music through an initialized PDJE_Wrapper and returns a PackedColorArray. Pass an open PDJE_KeyValueDB when results should be reused. The caller owns that database node and must call Close() after all analysis users finish.

The wrapper reads and writes byte blobs under keys beginning with MIR|stft_music|; the remaining key includes the selected music identity, window, window-size exponent, and overlap. A valid cached PackedColorArray is returned directly; otherwise the wrapper computes it and writes through to the same DB. If the handle is null or closed, analysis still runs without caching. Use STFT_PCM_DATA() when operating on caller-supplied PCM rather than searched music.

Waveform Images

SoundToWaveform() returns encoded waveform image byte arrays. SoundToRGBWaveform() adds STFT-derived RGB information.

var cache := PDJE_KeyValueDB.new()
if not cache.Open("user://pdje-cache/waveforms", true):
    return

var images: Array = mir.SoundToWaveform(
    $PDJE_Wrapper,
    cache,
    "music-title",
    "composer",
    128.0,
    256,
    4096,
    256,
    0,
    -1)

for webp_bytes: PackedByteArray in images:
    print(webp_bytes.size())

pcm_per_pixel controls horizontal aggregation. width and height control each image. start_index and end_index select a PCM range; -1 uses the available end.

Beat This Detection

The native PDJE_UTIL::ai namespace includes a generic ONNX Runtime facade, but the current Godot wrapper exposes only Beat This. Godot code cannot create arbitrary ONNX sessions or tensors through this extension.

Create A Detector

The model path must be non-empty, point to an existing regular .onnx file, and be included in the exported Godot project.

var ai := PDJE_AI.new()
var detector: PDJE_BeatThisDetector = ai.CreateBeatThisDetector(
    "res://models/beat_this.onnx")

if detector == null or not detector.IsInitialized():
    push_error("Beat This model initialization failed")
    return

print(detector.GetModelPath())

Detect From PCM

var interleaved_pcm := PackedFloat32Array()
interleaved_pcm.resize(44100)

var result: PDJE_BeatThisResult = detector.DetectPCM(
    interleaved_pcm,
    1,
    44100)
if result == null:
    push_error("Beat detection failed")
    return

print(result.beats)
print(result.downbeats)

DetectPCM(pcm, channel_count, sample_rate) validates non-empty PCM, positive channel/sample-rate values, and frame alignment. It downmixes interleaved input to mono before inference. Returned beat and downbeat positions are seconds.

Detect From PDJE Music

var result: PDJE_BeatThisResult = detector.DetectMusic(
    $PDJE_Wrapper,
    "music-title",
    "composer",
    -1.0)

if result != null:
    for downbeat_seconds in result.downbeats:
        print(downbeat_seconds)

DetectMusic() requires an initialized PDJE_Wrapper, searches its music metadata, decodes PCM, and uses the decoder sample rate. A negative BPM skips the BPM filter. Failures return null and emit a Godot diagnostic.

Contributor Utility Contracts

Native consumers use several CMake units:

  • PDJE_UTIL for the umbrella utility and AI surface

  • PDJE_UTIL_DB for SQLite, RocksDB, and Annoy backends

  • PDJE_UTIL_IMAGE_WEBP for generic WebP encoding/writing

  • PDJE_UTIL_IMAGE_WAVEFORM for waveform and STFT-backed image generation

Current error and return boundaries

The former shared StatusCode, Status, Result<T>, and Result<void> files were removed. Current native code uses direct values and exceptions according to each API:

  • PDJE_UTIL::function::clamp(ClampArgs) returns double and throws std::invalid_argument when minimum exceeds maximum.

  • slugify(SlugifyArgs) returns std::string and throws std::invalid_argument for an alphanumeric separator.

  • DB lifecycle and operations return direct values or throw backend/runtime exceptions; wrappers translate failures into null, empty, or false Godot results plus diagnostics.

  • Native ONNX and Beat This constructors/inference may throw; the Godot wrapper validates inputs and converts failures to null results.

Do not write new examples using .ok(), .status(), or .value() unless a specific current type actually defines that contract.

STFT and image boundaries

The maintained native STFT entry is include/util/function/stft/STFT_Parallel.hpp. PDJE_PARALLEL::STFT::calculate() accepts PCM plus STFTRequest and returns a StftResult pair. The runtime detects an available backend and retains serial fallback behavior; enum presence alone does not prove a backend is selectable.

Generic WebP and waveform helpers live under include/util/function/image/. They validate dimensions, stride, PCM/channel layout, and output options before encoding. These native helpers are projected through PDJE_MIR only where the wrapper explicitly binds them.

Primary source anchors

Use API Reference for exact native symbol lookup after applying the wrapper and error-boundary rules above.