Metadata-Version: 2.1
Name: optitrack
Version: 0.0.9
Summary: Native Python wrapper for the optitrack tracking system
Requires-Python: >=3.8,<3.13
Description-Content-Type: text/markdown

# optitrack

Unified native Python wrapper for OptiTrack Motive 2.3 and 3.1 on 64-bit
Windows. One installation exposes the existing `optitrack.optr` API and loads
the backend matching the locally installed Motive runtime.

The OptiTrack SDK and runtime are proprietary vendor components and are not
redistributed by this repository or by the wheel. Install Motive before using
the package.

## Runtime selection

Automatic selection tries Motive 3.1 first, then Motive 2.3:

```python
import optitrack

print(optitrack.backend_version())
tracker = optitrack.optr()
tracker.Initialize(r"C:\path\Calibration.cal", r"C:\path\UserProfile.motive")
```

Set `OPTITRACK_MOTIVE_VERSION=2` or `OPTITRACK_MOTIVE_VERSION=3` to force a
backend. If the DLLs are outside the standard Motive installation, set
`OPTITRACK_MOTIVE_RUNTIME` to the runtime directory (or a semicolon-separated
list of directories). The loader also checks the `bin` and `lib` children of
each configured directory and installations named `Motive*` below
`C:\Program Files\OptiTrack`.

When the complete Motive runtime contains `plugins\platforms\qwindows.dll`,
the loader registers its Qt plugin directories for the current Python process.
Global `QT_PLUGIN_PATH` or `QT_QPA_PLATFORM_PLUGIN_PATH` variables are not
required and should not be used to point at a different Qt installation.

For example, to test Motive 2.3 explicitly:

```powershell
$env:OPTITRACK_MOTIVE_VERSION = '2'
$env:OPTITRACK_MOTIVE_RUNTIME = 'C:\Program Files\OptiTrack\Motive'
python -c "import optitrack; print(optitrack.backend_version())"
```

Use the directory from the complete Motive installation. Copying only
`NPTrackingToolsx64.dll` or `MotiveAPI.dll` is insufficient because those
libraries depend on other Motive components (including Qt, TBB and FFmpeg
DLLs). The package reports whether the main API DLL was found but one of its
dependencies could not be loaded.

## Threading and API compatibility

Native tracker calls release Python's GIL so a tracking worker does not block
other Python threads while Motive is updating. Motive API calls are serialized
and the legacy pose attributes are synchronized. Existing applications keep
using the same `optitrack.optr` methods, return values and attributes; no Python
call-site changes are required.

Initialization waits up to twenty seconds for the first frame instead of either
failing immediately or waiting indefinitely. As before, `0` indicates success
and `1` indicates failure. The Motive 3.1 backend also writes the failing API
operation, numeric result and vendor result description to standard error.
Set `OPTITRACK_INITIALIZE_TIMEOUT_SECONDS` to an integer from 1 to 600 to
change the Motive 3.1 wait, for example:

```powershell
$env:OPTITRACK_INITIALIZE_TIMEOUT_SECONDS = '30'
```

If the wait expires, the diagnostic includes the number of cameras reported by
the Motive API. Initialization also reports when the API says capture devices
are unavailable, which commonly means Motive is still open or the cameras are
not connected to the same computer.

## Multiple coils

The original two-argument `Initialize(calibration, profile)`, `Run()`, and
all legacy pose attributes remain available. To validate the expected number
of coils once, pass a third positional argument:

```python
tracker = optitrack.optr()
if tracker.Initialize(calibration_path, profile_path, 3) != 0:
    raise RuntimeError("OptiTrack initialization failed")

print(list(tracker.coilNames))

tracker.Run()
frame = tracker.GetFrame()  # Snapshot of that Run; does not acquire another frame.
if frame.status == 0:
    for coil in frame.coils:
        print(coil.name, coil.id, coil.tracked, coil.x, coil.y, coil.z)
```

Discovery runs once after loading the profile. Names are matched
case-insensitively against `Coil`, followed by an optional space, underscore,
hyphen or digit (`Coil`, `Coil 001`, `Coil_Left`, `coil-right`, `Coil2`).
No list of names is required. Validation counts all matching configured assets,
including untracked ones. A mismatch reports the expected count, actual count
and discovered names, shuts down the API, and returns `1`. Omit the third
argument or pass `-1` to discover without validating; `0` expects no coils.

The coil vector follows the SDK enumeration order at initialization and keeps
that order until the next initialization. This is the order reported by the
SDK after loading the profile, not a guarantee about text order inside the file.
Each slot stores its name, identity, pose and tracking flag together.
An occluded or missing coil keeps its slot and last valid pose, with
`tracked == 0`. Positions are in SDK world coordinates (meters); quaternions
are exposed as `qx, qy, qz, qw`. Apply the existing application coordinate
permutation and unit conversion when needed.

Motive 3 uses the asset's unique UID (`high:low`) to locate its pose even when
SDK indices change. The SDK-free Motive 2 backend uses the exact asset name
(`name:...`) as identity and rejects duplicate coil names during initialization.
Keep asset definitions and names unchanged during a connection; initialize
again after modifying the profile. Call `Close()` before initializing again.

`tracker.coils`, `tracker.coilNames`, `tracker.coilIDs` and
`tracker.coilCount` expose copies of the latest state. Like Polaris `objIDs`,
`coilIDs` contains visibility flags (`0/1`); each `coil.id` contains its identity.
For aligned arrays under concurrent updates, read one `GetFrame()` snapshot
and derive names, poses and flags from its `coils` vector:

```python
coils = list(tracker.GetFrame().coils)
names = [coil.name for coil in coils]
positions = [(coil.x, coil.y, coil.z) for coil in coils]
visible = [coil.tracked for coil in coils]
```

`ReadFrame()` acquires a new frame and also updates legacy attributes.
Use either `ReadFrame()` or `Run()` followed by `GetFrame()` for each acquisition.
Frame `status` is `0` on success, `-1` when updating fails, and `-2` when
the connection is closed/not initialized. `sequence` counts successful reads
in this connection; it is not the Motive frame number.

The legacy coil attributes always refer to the asset named exactly `Coil`,
or to the first discovered coil if that name does not exist. This selection
is fixed during initialization and never switches to another visible coil
when the selected coil is occluded. Legacy `coilID` remains a `0/1` flag.

## Building

OptiTrack wheels are built locally; this package is excluded from GitHub
Actions. To support both Motive 2.3 and 3.1, build with
`OPTITRACK_BUILD_BACKENDS=2;3` and the Motive 3.1 SDK available. See the
local Python 3.8 through 3.12 build instructions in `BUILDING.md`.

Choose the backends with `OPTITRACK_BUILD_BACKENDS`. A Motive 2.3-only wheel
does not require any vendor SDK during the build because its API is resolved
dynamically from the installed runtime:

```powershell
$env:OPTITRACK_BUILD_BACKENDS = '2'
uv run --isolated --python 3.8 python build-system/build_wheel.py optitrack `
    --output-dir wheelhouse/motive2
```

The default unified wheel builds both backends and therefore requires the
Motive 3.1 SDK. CMake first searches installed `Motive*` directories below
`C:\Program Files\OptiTrack`. When the SDK is elsewhere, set its root
explicitly:

```powershell
$env:OPTITRACK_BUILD_BACKENDS = '2;3'
$env:OPTITRACK_MOTIVE_3_ROOT = 'C:\SDKs\Motive-3.1'
uv run --python 3.12 python build-system/build_wheel.py optitrack
```

The Motive 3 root must contain `MotiveAPI.h`, its `Core/` headers and
`MotiveAPI.lib`. The wrapper builds against these files but does not copy them
into the wheel.

`OPTITRACK_BUILD_BACKENDS=3` builds only the Motive 3.1 backend and also
requires the 3.1 SDK. Use separate output directories for different backend
selections because their wheel filenames otherwise have the same package,
version, Python and platform tags.
