- Notifications
You must be signed in to change notification settings - Fork139
Open Source Lighthouse Tracking System
License
collabora/libsurvive
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Libsurvive is a set of tools and libraries that enable 6 dof tracking onlighthouse and vive based systems that is completely open source and can runon any device. It currently supports both SteamVR 1.0 and SteamVR 2.0 generation of devices and should support any trackedobject commercially available.
Since the focus is on tracking; it does not independently run the HMD. For an open souce stack that does that seemonado
Most of the development is discussed on Discord.Join the chat and discussion in our discord!. There is also amatrix bridge available to join the discussion.
An example application is libsurvive running the controllers and HMD in Godot:
git clone https://github.com/cntools/libsurvive.git --recursivecd libsurvivesudo cp ./useful_files/81-vive.rules /etc/udev/rules.d/sudo udevadm control --reload-rules && sudo udevadm triggersudo apt update && sudo apt install build-essential zlib1g-dev libx11-dev libusb-1.0-0-dev freeglut3-dev liblapacke-dev libopenblas-dev libatlas-base-dev cmakemake
Plug in a headset / tracker / controller / etc and run:
./bin/survive-cli
This should calibrate and display your setup.
For visualization, you can either download a binary ofwebsocketd or enable the experimental apt source and usesudo apt install websocketd
. After which you can run:
./bin/survive-websocketd & xdg-open ./tools/viz/index.html
If you havecmake
installed on your path you can simply run themake.ps1
script by right clicking it and seletingRun with PowerShell
.
A more manual approach is to open CMakeLists file in something likeCMake GUI to buildfrom source using one of the visual studio generators. This will also let you set various build options. The build uses NuGetto get thenecessary development dependencies. After you generate the project, open thesolution in visual studio and run build all.
Websocketd should work the same with with the visualization tool; assuming you put it somewhere in the system path. In the build binary folder (./build-win/Release
if you built frommake.ps1
) there should be asurvive-websocketd.ps1
which can be ran as a PowerShell file.
Probably the easiest way to get started with libsurvive on windows is to check out therelease binaries.
The tracking and device enumeration work fairly well at this point; but there isn't an extremely large testing base andthe tools aren't as polished as the comparable ones bundled in SteamVR. Work is ongoing to quantify how accurate thetracking is and to improve the user experience.
A very loose collection of things that are on the short term agenda:
- Dynamic correction of calibration. This would detect and silently recalibrate lighthouses that might have moved. Theend goal is to have a system where the user is never aware of any calibration requirements.
- An android binary / port
- Hard numbers on the accuracy and precision of libsurvive as a tracking system. If anyone wants to contribute time testingon a CNC please get in ourdiscord
- Better handling of data starvation -- if the USB or radio connection stutters too long, the tracking will occasionallyglitch out for a brief period.
- Use something like usbmon for windows
If you followed the quick start guide, you'll notice that the first thing you must do (for linux) is install udev rules:
sudo cp ./useful_files/81-vive.rules to /etc/udev/rules.d/sudo udevadm control --reload-rules && udevadm trigger
This allows one to use those devices without having root. No such steps are necessary in windows.
After that, when you runsurvive-cli
orsurvive-websocketd
it should recognize any plugged in vive devices and startcalibrating and tracking those devices.
Important: Close SteamVR for best results. Depending on the system, libsurvivewill either cause SteamVR to lose connection to the device or will compete for bandwidth with it
Calibration is the process which establishes where the lighthouses are set up in relation to the tracked objects. Thefirst time you run libsurvive, it can take up to ten seconds to communicate with the lighthouses and figure out wherethey are.
Calibration will continuously integrate objects data so long as they are momentarily stationary. Due to this, you might notice lighthouses shift slighty while it gets a good lock. Subsequent runs should shift much less.
Once you do this one time, it is saved inconfig.json
inXDG_CONFIG_HOME/libsurvive
. If you delete this file, it will simplyrecalibrate; but it is faster to use the--force-calibrate
flag. Some drivers change the name of this file -- notably recordings will instead use<event_file>.json
.
If you have a large space, and you can not centrally locate a single device to 'see' all lighthouses, you can calibratea few lighthouses and move the tracked object into the field of view of the uncalibrated lighthouse while keeping it inview of at least one of the calibrated ones. Set it down so it doesn't move; and the remaining lighthouse(s) should nowcalibrate.
Important: Resetting calibration automatically when a lighthouse is moved is being planned on but is not currentlyavailable. If one of the calibrated lighthouses are moved, you either have to redo calibration by deleting the config.jsonfile or passing--force-calibrate
into any of the libsurvive tools.
The main visualization tool is a THREE.js page which is fed data through (websocketd)[http://websocketd.com/]. To usethis tool, runsurvive-websocketd [options]
and open a web browser to./tools/viz/index.html
from the root of thecloned repo.
survive-cli
- This is the main command line interface to the library; really just a very thin wrapper around the library.survive-websocketd
- A script which runssurvive-cli
throughwebsocketd
with all the appropriate flags set.sensors-readout
- Display raw sensor information in a ncurses display
This section is mainly concerned aboutconsuming data from the library; for information on how toprovide data, seethedrivers section.
The main way to extend and use libsurvive is to use the various callbacks exposed by the library to get information fromthe system. Use of libsurvive in this way is recommended if you need access to all data going in -- IMU data, individuallight data, and/or final pose data. However care needs to be taken to not bog down the system. In general these callbacksare invoked from the thread collecting the data; so if you have unnecessary delays in processing data will be droppedwhich will cause poor tracking performance.
The full list of hooks ishere.The function types arehere.
You install your custom hook via:
<hook-name>_process_func survive_install_<hook-name>_fn(SurviveContext *ctx, <hook-name>_process_func fbp);
This returns the previously set function for that particular hook; which you can choose to call in your own callback. Thisis somewhat more cumbersome than just having the callbacks returntrue
orfalse
; but allows the flexibility to callthe previously defined function before or after your code, or not at all.
These hooks are used internally within libsurvive; if you provide a hook and do not either call the previously defined ordefault function, some data will not make it to the posers.
SurviveContext
andSurviveObject
both have auser_ptr
variable which is zero initialized and not used internally,and is meant to be set by library consumers for their own purposes. This allows you to install the hook, and not resortto using globals.
These interfaces are relatively stable, but aren't guaranteed to not change.
Have a look at the other libsurvive tools a the top level of the repository for example usage of the lower level API:
- survive-cli.c
- sensors-readout.c
- simple_pose_test.c
The high levelSimple
API is recommended for applications which just need position and velocity data as fast as theycan process that data. It has a few main advantages:
- User code runs in it's own thread; so you can't starve libsurvive of data
- Much more insulated against lower level API changes; so you can upgrade libsurvive versions more easily
The main loop logic tends to look like this inC
:
while (survive_simple_wait_for_update(actx)&&keepRunning) {for (constSurviveSimpleObject*it=survive_simple_get_next_updated(actx);it!=0;it=survive_simple_get_next_updated(actx)) {SurvivePosepose;uint32_ttimecode=survive_simple_object_get_latest_pose(it,&pose);printf("%s %s (%u): %f %f %f %f %f %f %f\n",survive_simple_object_name(it),survive_simple_serial_number(it),timecode,pose.Pos[0],pose.Pos[1],pose.Pos[2],pose.Rot[0],pose.Rot[1],pose.Rot[2],pose.Rot[3]); }}
Example code for the application interface can be found inapi_example.c.
The full header for the simpler API is availablehere.
Python bindings are available for python3 on windows and linux throughhttps://pypi.org/project/pysurvive/. You caninstall them with
pip install pysurvive
To build the python bindings, runpython setup.py install
in the repo root. This should install thepysurvive
package.
An example which streams poses out as they come in:
import pysurviveimport sysactx = pysurvive.SimpleContext(sys.argv)for obj in actx.Objects(): print(obj.Name())while actx.Running(): updated = actx.NextUpdated() if updated: print(updated.Name(), updated.Pose())
There are more examples in./bindings/python
.
The C# bindings wrap both the low level access API and the higher level simpler to use API. It is recommended to use thehigher level API since the low level one relies heavily on callbacks and marshalling makes working with it prone toerrors that are not always easy to solve.
Standard binaries are available athttps://www.nuget.org/packages/libsurvive.net/. You can install them for a givenC# project through the visual studio nuget manager tool.
Build the solutionhere with either visual studio or byrunning something like
dotnet build -c Release
from a terminal to generate the binarylibsurvive.net.dll
. This works in linux as well as windows; but thefilename still ends indll
. When you run against this binary,libsurvive.so
needs to either be in the same directory(with desired plugins), or on the system path.
The high level api is exposed through thelibsurvive.SurviveAPI
object. It's use is pretty easy; it can just poll forupdates to object positions or button events as in theDemo project:
usinglibsurvive;usingSystem;namespaceDemo{classProgram{staticvoidMain(){string[]args=System.Environment.GetCommandLineArgs();varapi=newSurviveAPI(args);while(api.WaitForUpdate()){SurviveAPIOObjectobj;while((obj=api.GetNextUpdated())!=null){Console.WriteLine(obj.Name+": "+obj.LatestPose);}}api.Close();}}}
It's also meant to be easy to integrate into code bases based on frame updates; such as in theUnity example:
// Update is called once per framevoidUpdate(){varupdated=survive?.GetNextUpdated();if(updated==null)return;varupdatedObject=getObject(updated.Name);Vector3newPosition=Vector3.zero;QuaternionnewRotation=Quaternion.identity;SurvivePosepose=updated.LatestPose;newPosition.x=(float)pose.Pos[0];newPosition.y=(float)pose.Pos[1];newPosition.z=(float)pose.Pos[2];newRotation.w=(float)pose.Rot[0];newRotation.x=(float)pose.Rot[1];newRotation.y=(float)pose.Rot[2];newRotation.z=(float)pose.Rot[3];updatedObject.transform.localPosition=newPosition;updatedObject.transform.localRotation=newRotation;}
There are a lot of things that can go wrong to give bad tracking or calibration results, and given the wide variety ofdevices, configurations and use cases, it's extremely helpful when trying to resolve bugs if there is a data recordingof the bug. This also can get added to our CI system to have automatic testing against that use case.
There are two mechanisms available for recording data:--record
and--usbmon-record
.
--record
is available in every installation, and less setup to use so for pure tracking issues this is usually theapproach to take. However, if the issue is in parsing and understanding the low level data packes from the tracked device,the--usbmon-record
option might be more helpful.
When running any of the libsurvive tools, pass in--record <filename>.rec.gz
. This will create a data log of everythingthe system sees as it runs in that file. This records a large amount of data, so if it is allowed to run for a long timethat file might get very large.
To playback that file, run:
./survive-cli --playback <filename>.rec.gz
Occasionally, when dealing with new hardware or certain types of bugs that cause an issue in the USB layer, it is necessary to have a raw capture of the USB data seen / sent. The USBMON driver lets you do this.
Currently this driver is only available on linux and you must have libpcap installed --sudo apt install libpcap-dev
. You also need theusbmon
kernel module installed; but many linux flavors come with that built in.
To start usbmon and prepare it for use for all users, run:
sudo modprobe usbmonsudo setfacl -m u:$USER:r /dev/usbmon* # In sensitive environments, you can run survive-cli with sudo instead.
To capture usb data, run:
./survive-cli --usbmon-record <filename>.pcap.gz --htcvive <additional options>`
You can run that playback with:
./survive-cli --usbmon-playback <filename>.pcap.gz [--playback-factor x] <additional options>`
If you are sending this file for analysis, note that you need the accompanying*.usbdevs
file with it to be useful. If you follow the*.pcap.gz
convention, run something like
zip logs.zip *.pcap* config.json
and post thelogs.zip
to an issue or to discord.
This driver specifically only captures devices on a white list of VR equipment; but if you don't want to publish raw USBdata to the internet, ask in discord for who to send it to in a private message.
Libsurvive is very configurable, and contains a lot of command line options depending on the drivers and options givenat build time.
It's recommended that you install the bash completion for libsurvive if you are working with the command line options:
sudo cp survive_autocomplete.sh /etc/bash_completion.d/
.
The most useful command line option for debugging is--v
-- this sets the reporting level. This verbosity level roughly follows this guideline:
--v 10
- Statistics and information displayed either at the start or end of the application.--v 100
- Information displayed at many common points while tracking--v 150
- Information displayed for almost every pose output--v 250
- Information displayed for almost all light data event in the system--v 1000
- Everything.
Running at higher verbosity (>100) will make the visualization tool sluggish.
--force-calibrate
: This reruns calibration but reuses OOTX; which makes it much faster to run.
--playback-factor
: When playing back a recording, this will speed up the playback (0 is run everything as fast as possible) or slow it down (2 takes twice as much time)
--lighthouse-gen
: Force the system to use a particular generation of lighthouse. Right now, sometimes the system misidentified lighthouse 1 (The purely square base stations) for lighthouse 2 (The rounded face base stations) or vice versa. As we find these cases, we are fixing them but this lets a misbehaving system be useful in the meantime.
These are the different drivers for providing information into libsurvive. All of them are encapsulated in thesrc
directorywith adriver_
prefix. Each driver can be specified with a--<driver-name>
flag. You can disable a default driver (eg,htcvive
) with--no-<driver-name>
.
htcvive
- This is the main driver which provides data via USB connection to vive hardware.simulator
- This simulates a device floating around while providing realistic light / IMU data into libsurvive. Usefulfor testing different features.playback
- The playback driver is what enables record/playback functionality. It replays a file into the various data points.usbmon
- USBmon can be ran concurrent with steamvr to allow both systems to use the tracked object data.openvr
- This driver exposes external poses and velocities and can be ran withusbmon
to compare the two systems.
Integrating a driver is meant to be relatively straight forward and the above mentioned ones are good references for howto do it.
The general approach is to compile to a shared object / DLL with the name ofdriver_<name>.so
in the plugins folder.The internals of libsurvive enumerate these plugins and run libsurvive registered function from the form:
intDriverRegExample(SurviveContext*ctx) {if(...error...) {returnSURVIVE_DRIVER_ERROR; }returnSURVIVE_DRIVER_NORMAL;}REGISTER_LINKTIME(DriverRegExample)
It isn't necessary for a driver to register anything else; but to be integrated into libsurvive the driver must eitherexpose a poll / close function or a thread / close function.
The simpliest approach is a poll driver:
void survive_add_driver(SurviveContext *ctx, void *user_ptr, DeviceDriverCb poll, DeviceDriverCb close)
The poll function is called continuously while the system is running; and the close function is called atshutdown.
More versatile is a threaded driver:
bool *survive_add_threaded_driver(SurviveContext *ctx, void *driver_data, const char *name, void *(routine)(void *), DeviceDriverCb close);
This starts a thread with the given function and name.
In the threaded driver case, when accessing any members ofSurviveContext
orSurviveObject
, youmust lock and release around that access with the following functions:
void survive_get_ctx_lock(SurviveContext *ctx);void survive_release_ctx_lock(SurviveContext *ctx);
Improper locking or unlocking can result in race conditions or dead locks.
Within either the threaded function or the polling function, it is then up to the driver to call the appropriatehook functions with whatever data they are exposing. Generally the driver will also callsurvive_create_device
and only concern itself with that device. More than one driver can be running at a time; but they all assume the samelighthouse configuration.
A good example of this in action isdriver_simulator.c
which calls various light data and IMU callbackswith a customSurviveObject
type.driver_openvr.cc
demonstrates how to incorporate external position data into thelibrary.
Other projects using libsurvive
- TheMonado OpenXR runtime uses libsurvive as one of its HMD and controller drivers.
- OpenXR applications that run on Monado include theOpenXR plugin for Godot 3.x
- There is a very unofficial (and not upstreamable)OpenHMD/libsurvive fork that adds a libsurvive driver.
- This OpenHMD/libsurvive fork can be plugged intoSteamVR-OpenHMD or used natively with theOpenHMD plugin for Godot 3.x.
Thanks to Mr. Faul for our logo!Special thanks to @nairol for an extreme amount of detail in reverse engineering the existing HTC Vive system on hishttps://github.com/nairol/LighthouseRedox project.
About
Open Source Lighthouse Tracking System