Compare commits

...
119 Commits
Author SHA1 Message Date
Hyblocker 8100d776b8 Merge pull request #14 from PiMaker/pi-adds-require-trigger-press-mode
adds require trigger press mode
2024-07-14 17:33:06 +02:00
Hyblocker 137d8916af Merge pull request #13 from PiMaker/pi-does-dynamic-calibration-speed-in-continuous
dynamic calibration speed in continuous, merge arcticfox's relative pose lock
2024-07-14 17:32:56 +02:00
Hyblocker ceeab0e6e2 Merge pull request #12 from PiMaker/pi-falls-back-to-exclude-serial-for-hmd
fall back to serial-excluded matching for HMD finding
2024-07-14 17:32:45 +02:00
Hyblocker 797f65ad0d Merge pull request #11 from PiMaker/pi-pause-on-tracking-lost
detect when headset does not send valid tracking data and pause
2024-07-14 17:32:32 +02:00
pi 3460437924 fall back to serial-excluded matching for HMD finding
this allows keeping settings working between different tracking
methods (e.g. switching from Virtual Desktop to Oculus Link will
not break detecting the same HMD)

for some reason serial number changes between link methods...
2024-07-06 18:51:14 +02:00
pi 67f7c820f5 move trigger detection earlier 2024-07-06 16:56:05 +02:00
pi 3ac6dfc208 add "require trigger press to apply calibration" mode 2024-07-06 16:55:28 +02:00
pi 8b86898417 allow calibration speed setting to be used for continuous 2024-07-06 16:52:52 +02:00
pi d9fb08560b dynamically calculate dropping frames in continuous 2024-07-06 16:51:03 +02:00
pi 0ac3ab3ad8 Merge remote-tracking branch 'arcticfox/Branch_v1.4-bd_-r2' into pi-merges-relative-pose-lock 2024-07-06 16:50:05 +02:00
pi b0fe076845 detect when headset does not send valid tracking data and pause
this happens when a Quest enters out-of-bounds passthrough mode or
standby for example, in which case it's almost always cleaner to keep
the current calibration alive instead of calibrating towards a zero
location
2024-07-06 16:47:27 +02:00
Hyblocker 5fba766d4d Merge pull request #10 from Tropingenie/Branch_v1.4-bd_-r2
Update README.md
2024-06-18 01:36:29 +02:00
Tropingenie 9da1c41927 Update README.md
Updates "latest release" hyperlink. Now correctly opens latest release, and points to hyblocker repo instead of pushrax.
2024-06-16 20:26:16 -07:00
Hyblocker 31fb1d15f9 Add preliminary support for playspace scale 2024-05-22 20:17:32 +02:00
Hyblocker 16625138e1 Return more verbose error on startup fail 2024-05-22 20:16:30 +02:00
Evgeny Zuev d0159852e1 Add relative pose lock, use slow preset again 2024-05-21 20:36:15 +03:00
Hyblocker d22b2d1c69 Make settings UI more coherent 2024-02-18 19:04:23 +01:00
Hyblocker 308641ebf2 Add tracker offsets 2024-02-18 19:01:21 +01:00
Hyblocker 19ed75c378 Add tracker offset UI to settings 2024-02-18 05:23:09 +01:00
Hyblocker 4dd9ccfc79 Group settings into groups 2024-02-18 05:22:53 +01:00
Hyblocker f578999f0e Rename alignment speeds to settings 2024-02-18 05:20:57 +01:00
Hyblocker 7a4dc9007d Save cc tracker offset to config 2024-02-18 05:20:21 +01:00
Hyblocker 02f4aa22dc Add fields for cc tracker offset 2024-02-18 05:20:03 +01:00
Hyblocker 89d231472a Fix crash with keyboard input 2024-02-18 05:19:40 +01:00
Hyblocker 1515312e76 Add Extension to ImGui for box style containers 2024-02-18 05:19:22 +01:00
Hyblocker 7349f510ef Add instructions for continuous calibration 2024-02-17 17:44:12 +01:00
Hyblocker 71b82d0641 Cleanup installer dir 2024-02-17 17:36:57 +01:00
Hyblocker 68476caafc Bump version 2024-02-17 17:35:33 +01:00
Hyblocker 011158cd2c Add special handling for Pimax Crystal
Pimax please don't touch other drivers and please don't lie about what you are 😭
2024-02-17 17:34:17 +01:00
Hyblocker a8c48136c0 Make IPC errors work on non latin machines 2024-02-17 17:33:32 +01:00
Hyblocker dc9ada1a60 Remove missing file from project 2024-02-17 17:32:50 +01:00
Hyblocker 3acdbe5654 Bump version 2023-12-06 12:06:13 +01:00
Hyblocker de0d3425fa Merge pull request #1 from TCL987/limit-minimized-frame-rate
Limit the frame rate when minimized
2023-12-06 11:51:48 +01:00
ArcticFox8515 3b8ea60c8a Revert back to fast continuous calibration 2023-10-23 17:53:08 +03:00
ArcticFox8515 56531e0432 Optimize resource usage when running in background
Draw GUI only when window or overlay is visible.
Set minimal update time to 1/90 seconds,
so application won't "busy loop".
2023-10-22 18:00:47 +03:00
TCL987 1c18cd5445 Limit the frame rate when minimized
This avoids high CPU usage when minimized.
2023-10-10 23:42:13 -07:00
ArcticFox8515 e371b1d13f Use only yaw rotation for calibration
Pitch and roll offsets usually should be 0
because "up" vector in all VR tracking systems
is the same.
2023-09-23 19:29:18 +03:00
ArcticFox8515 cc4ffa774d Use slow preset; save relative transform
1. Use SLOW preset for continuous calibration. This should
   increase its accuracy with expense of increased CPU usage
   before fully calibrated.

2. Save/load relative transform, so new calibration doesn't have
  to start from scratch.
2023-08-20 19:10:25 +03:00
ArcticFox8515 9a0204466a Continuous calibration improvements
Use best effort calibration while nothing better is available,
this makes calibration converge within seconds.

Use relative pose for quick re-calibration until it provides
sensible quality result. This saves a lot of CPU load after
pose is calibrated.
2023-05-30 20:47:02 +03:00
bd_ 71e9683dc4 r2 2022-09-25 18:08:19 -07:00
bd_ f21de937f0 Enable calibration loading for continuous calibration mode
Fixes: https://github.com/bdunderscore/OpenVR-SpaceCalibrator/issues/2
2022-09-25 18:08:19 -07:00
bd_ aecc9612e2 Import minhook as a submodule
libMinHook needs to be built using the same VC++ version as OVRAS.
To help keep things consistent without having to check in binaries,
include libMinHook as a submodule so we can build it as part of the
solution.
2022-09-25 18:08:19 -07:00
bd_ 0e8ab54400 Save alignment config 2022-09-24 18:50:57 -07:00
bd_ c5c63da491 Adjustments to calibration config UI 2022-09-24 18:48:19 -07:00
bd_ f779d68dff Adjusting default static calibration configuration 2022-09-24 18:13:28 -07:00
bd_ 20a1054111 [v1.1] Add manual mark logs button 2022-08-23 18:09:23 -07:00
bd_ 3e3d7750f1 Bump version 2022-08-21 18:56:16 -07:00
bd_ 37a951a4cc Fixing logging bugs, adding switch for logging 2022-08-21 18:56:08 -07:00
bd_ 492743e4d0 Update protocol version 2022-08-21 18:46:19 -07:00
bd_ d9af36f290 Add calibration log 2022-08-21 18:46:10 -07:00
bd_ 98760540e6 UI improvements 2022-08-21 18:01:10 -07:00
bd_ be51eeeda1 Gradual correction 2022-08-20 19:53:36 -07:00
bd_ 1e8191bcf1 Static calibration mode works 2022-08-16 17:23:58 -07:00
bd_ 889cdf9828 Infrastructure for more internal metrics 2022-08-14 16:50:11 -07:00
bd_ 650d86dcc3 More extensible debug UI 2022-08-14 14:57:52 -07:00
bd_ 996373e07d Separate out continuous calibration UI 2022-08-14 14:09:32 -07:00
bd_ 50ecc1af1c Calibration debug UI 2022-08-14 13:46:34 -07:00
bd_ 50991f17a8 Update version string 2022-08-13 15:03:28 -07:00
bd_ 52c166e643 Adjusting coplanar check 2022-07-30 16:56:42 -07:00
bd_ 9b9e2119d4 Don't mark the target tracker as having an invalid pose
VRChat seems to use the last valid pose on a tracker that isn't tracking, which means you can bind to the autocalibration tracker. Put it far, far away instead of marking the pose invalid.
2022-07-18 17:27:25 -07:00
bd_ af409fbed3 Show cancel button when in continuous standby state 2022-07-14 19:44:49 -07:00
bd_ 51372d9f0b improve axis variance check 2022-07-14 19:28:25 -07:00
bd_ a732606507 Cancel translation induced by rotation correction 2022-07-14 19:12:51 -07:00
bd_ ea13a5b9f7 Fixing bugs in ImGui integration 2022-07-14 19:12:35 -07:00
bd_ a3dabf06bf Restore imgui patch
Originally in https://github.com/bdunderscore/OpenVR-SpaceCalibrator/commit/85c6b3cea44ff07e7e2204be3c2bc0dfe94e8adc , hopefully fixes overlay
2022-07-14 18:08:21 -07:00
bd_ faa0462d72 make quashing the target device optional 2022-07-14 18:07:28 -07:00
bd_ e052c85dd5 disable device setting when continuous calibration is active 2022-07-13 20:04:52 -07:00
bd_ 1ca0537e83 update imgui 2022-07-13 19:50:45 -07:00
bd_ 040b98a513 smoother continuous calibration 2022-07-13 19:27:11 -07:00
bd_ c4379bb84d update gitignore 2022-07-13 08:08:18 -07:00
bd_ 843b01486a initial continuous calibration system 2022-07-13 08:07:49 -07:00
bd_ 8969600007 Fix debug builds 2022-07-11 18:29:07 -07:00
bd_ bebeb0c1cd CalibrationCalc changes 2022-07-11 18:26:57 -07:00
bd_ 3d546f2fd2 Refactor out calibration calculations 2022-07-10 18:35:12 -07:00
bd_ 3f170b9ff1 wip - shmem pose buffer 2022-07-10 16:49:21 -07:00
bd_ 6969cb8c5a Experimental calibration quality check 2022-07-04 17:17:59 -07:00
bd_ 6f1c83dd9f Reuse samples for both rot and trans calibration 2022-07-04 15:35:55 -07:00
bd_ fcb6f13c5f VC++ version update 2022-07-04 15:35:10 -07:00
bd_ 81c55df127 Update to latest VC++ 2022-07-04 14:55:38 -07:00
Justin Li 1cc0583a5e Fix overlay on AMD 2022-03-31 01:59:15 -04:00
Justin Li 15a16eb14c Export symbols to enable high performance rendering, fixes #55 2021-11-08 00:39:06 -05:00
Justin Li 4dba5fd7fe Rebuild minhook for v141, update versions 2021-11-08 00:36:33 -05:00
Justin Li 984b93ffff Merge pull request #65 from brian-armstrong/scale_config
Driver Scale Parameter
2021-11-07 23:38:51 -05:00
Justin Li 55242e7d56 Update build system to v141 2021-11-07 23:37:33 -05:00
Brian Armstrong c6eb49d580 scale vecPosition
This looks like the right thing to scale
2021-11-02 00:48:27 -07:00
Brian Armstrong e599ac136d make the steps smaller
The correct value is probably between 0.99 and 1.01. Let's use really
small steps here.
2021-11-02 00:46:33 -07:00
Brian Armstrong bd50a8c207 Driver Scale Parameter
Also stash to serialized config and allow editing from editor
2021-10-31 16:17:16 -07:00
Justin Li f3b4f9475e readme: add wiki link 2021-07-31 01:34:18 -04:00
Justin Li d060b98581 Merge pull request #39 from monstermac77/monstermac77-reddit-community
Added Reddit community link
2020-11-23 14:14:50 -05:00
monstermac77 da869868a1 Added Reddit community link
Added a link for the newly created Reddit community, with the goal of having a place for users of Open VR Space Calibrator to work together and troubleshoot in a more public (indexed by search engines) and less linear forum than Discord. Hopefully this will increase the discoverability of mixed VR, help existing users of mixed VR troubleshoot issues by being able to Google them, as well as reduce some of the repetitive questions on the Discord.
2020-11-23 01:27:22 -05:00
Justin Li 8e6796a9b5 Log device info when starting calibration 2020-10-25 15:05:02 -04:00
Justin Li 6389d745ae Update issue templates 2020-10-12 17:15:03 -04:00
Justin Li 326b54ba74 Update issue templates 2020-10-12 17:13:51 -04:00
Justin Li 98b23ad5bb Update README.md 2020-09-10 22:20:41 -04:00
Justin Li 7788c2af38 Update README.md 2020-09-08 20:15:28 -04:00
Justin Li 5334084508 Update README.md 2020-09-08 20:12:20 -04:00
Justin Li 9752a3be05 Update README for v1.1 2020-09-08 20:04:09 -04:00
Justin Li 8323d64b2d Support IVRServerDriverHost_006 2020-09-02 11:54:55 -04:00
Justin Li b04615dcb6 Store config in the registry 2020-04-08 00:25:01 -04:00
Justin Li 9d1fa11f98 Calibration speed setting, improve UI 2020-04-07 22:48:36 -04:00
Justin Li ab5e80a8ef v0.9 2020-04-06 00:25:54 -04:00
Justin Li ffb301b38c Disable profile when HMD is not the calibration reference, Clear button saves profile 2020-04-06 00:25:18 -04:00
Justin Li 9744585cf0 Merge pull request #17 from direct-configuration 2020-04-05 23:06:43 -04:00
Justin Li 7cf363e315 Reduce duplication and remove dead code 2020-04-05 23:04:45 -04:00
Dj lukis.LT 9c4a906ec0 Also apply calibration to TrackingReference devices
Been running Rift CV1 with Steamvr 2.0 basestations for a while and did not run into any problems so far even when purely on Index. The lighthouse driver station poses update on their (re)initialisation or some speciffic(dynamic recalibration?) cases and not immediately.
2020-04-05 21:07:07 -04:00
Dj lukis.LT d6030195f9 Set ActivateMultipleDrivers flag via API, Increment version
Left old config file method as a renamed launch command
2020-04-05 21:07:07 -04:00
Dj lukis.LT c607fa30c4 Update to OpenVR v1.10.30 2020-04-05 21:06:51 -04:00
Justin Li eebf2877f3 Update README for 0.8 2019-03-03 22:27:23 -05:00
Justin Li 7f60358eac Release v0.8 2019-03-03 15:42:55 -05:00
Justin Li 85c6b3cea4 Add chaperone bounds tool, fix rendering when launched minimized 2019-03-03 15:37:23 -05:00
Justin Li dda68d48b4 Automatically set activateMultipleDrivers to true 2019-03-03 12:28:41 -05:00
Justin Li 5c36f6e909 Add VR overlay, use non-admin writable path for config 2019-03-03 01:03:45 -05:00
Justin Li f112ca6768 Set driver name to lower precedence than InputEmulator 2019-01-04 15:48:39 -05:00
Justin Li a93dac0e28 Add installer 2018-08-08 19:49:29 -04:00
Justin Li 35690d8521 Remove unused dependencies 2018-07-19 22:56:45 -04:00
Justin Li 1bed4afb97 Implement driver hook for pose manipulation 2018-07-19 22:48:54 -04:00
Justin Li 6126280c40 Implement new user interface 2018-07-14 21:04:58 -04:00
Justin Li f8abea143e Add picojson 2018-07-14 20:56:51 -04:00
Justin Li ac16d42d01 Add GLFW, gl3w, and ImGui 2018-07-14 14:01:21 -04:00
105 changed files with 97196 additions and 3830 deletions

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
---
name: Bug report
about: Something is broken
title: ''
labels: bug
assignees: ''
---
<!--
If you are having trouble setting this up with SteamVR and would like help, the fastest way is to ask in the Discord group. https://discord.com/invite/m7g2Wyj
If you are having issues after updating SteamVR, please check for a new release at https://github.com/pushrax/OpenVR-SpaceCalibrator/releases before posting an issue.
-->
+10
View File
@@ -0,0 +1,10 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
+3
View File
@@ -5,5 +5,8 @@ ipch
*.aps
*.user
/OpenVR-SpaceCalibrator/x64/
/OpenVR-SpaceCalibratorDriver/x64/
/x64/
/lib/boost*
/install/OpenVR-SpaceCalibrator.exe
lib/Release/
+3
View File
@@ -0,0 +1,3 @@
[submodule "lib/minhook"]
path = lib/minhook
url = https://github.com/bdunderscore/minhook.git
+568 -1
View File
@@ -1,6 +1,8 @@
== OpenVR-SpaceCalibrator ==
MIT License
Copyright (c) 2018 Justin Li
Copyright (c) 2020-2022 Justin Li and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -19,3 +21,568 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This software also includes components licensed as follows:
== MinHook ==
MinHook - The Minimalistic API Hooking Library for x64/x86
Copyright (C) 2009-2017 Tsuda Kageyu.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
Portions of this software are Copyright (c) 2008-2009, Vyacheslav Patkov.
================================================================================
Hacker Disassembler Engine 32 C
Copyright (c) 2008-2009, Vyacheslav Patkov.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
Hacker Disassembler Engine 64 C
Copyright (c) 2008-2009, Vyacheslav Patkov.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
== ImGui ==
The MIT License (MIT)
Copyright (c) 2014-2022 Omar Cornut
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
== ImPlot ==
MIT License
Copyright (c) 2020 Evan Pezent
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
== glfw ==
Copyright (c) 2002-2006 Marcus Geelnard
Copyright (c) 2006-2016 Camilla Berglund <elmindreda@glfw.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would
be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not
be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
== gl3w ==
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
== Eigen ==
Portions copyrighted by many parties; see source code for names.
(The upstream distribution does not provide any single listing)
This application uses only the MPL-2.0 licensed components of Eigen.
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+32 -6
View File
@@ -1,10 +1,17 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
# Visual Studio Version 17
VisualStudioVersion = 17.3.32819.101
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OpenVR-SpaceCalibrator", "OpenVR-SpaceCalibrator\OpenVR-SpaceCalibrator.vcxproj", "{63BAE169-D595-4464-8E7E-50D6FD379348}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OpenVR-SpaceCalibratorDriver", "OpenVR-SpaceCalibratorDriver\OpenVR-SpaceCalibratorDriver.vcxproj", "{A61324AD-CE32-46D1-A95E-7E28A6D8CCA7}"
ProjectSection(ProjectDependencies) = postProject
{F142A341-5EE0-442D-A15F-98AE9B48DBAE} = {F142A341-5EE0-442D-A15F-98AE9B48DBAE}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libMinHook", "lib\minhook\build\VC16\libMinHook.vcxproj", "{F142A341-5EE0-442D-A15F-98AE9B48DBAE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@@ -15,14 +22,33 @@ Global
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{63BAE169-D595-4464-8E7E-50D6FD379348}.Debug|x64.ActiveCfg = Debug|x64
{63BAE169-D595-4464-8E7E-50D6FD379348}.Debug|x64.Build.0 = Debug|x64
{63BAE169-D595-4464-8E7E-50D6FD379348}.Debug|x86.ActiveCfg = Debug|Win32
{63BAE169-D595-4464-8E7E-50D6FD379348}.Debug|x86.Build.0 = Debug|Win32
{63BAE169-D595-4464-8E7E-50D6FD379348}.Debug|x86.ActiveCfg = Debug|x64
{63BAE169-D595-4464-8E7E-50D6FD379348}.Debug|x86.Build.0 = Debug|x64
{63BAE169-D595-4464-8E7E-50D6FD379348}.Release|x64.ActiveCfg = Release|x64
{63BAE169-D595-4464-8E7E-50D6FD379348}.Release|x64.Build.0 = Release|x64
{63BAE169-D595-4464-8E7E-50D6FD379348}.Release|x86.ActiveCfg = Release|Win32
{63BAE169-D595-4464-8E7E-50D6FD379348}.Release|x86.Build.0 = Release|Win32
{63BAE169-D595-4464-8E7E-50D6FD379348}.Release|x86.ActiveCfg = Release|x64
{63BAE169-D595-4464-8E7E-50D6FD379348}.Release|x86.Build.0 = Release|x64
{A61324AD-CE32-46D1-A95E-7E28A6D8CCA7}.Debug|x64.ActiveCfg = Debug|x64
{A61324AD-CE32-46D1-A95E-7E28A6D8CCA7}.Debug|x64.Build.0 = Debug|x64
{A61324AD-CE32-46D1-A95E-7E28A6D8CCA7}.Debug|x86.ActiveCfg = Debug|x64
{A61324AD-CE32-46D1-A95E-7E28A6D8CCA7}.Debug|x86.Build.0 = Debug|x64
{A61324AD-CE32-46D1-A95E-7E28A6D8CCA7}.Release|x64.ActiveCfg = Release|x64
{A61324AD-CE32-46D1-A95E-7E28A6D8CCA7}.Release|x64.Build.0 = Release|x64
{A61324AD-CE32-46D1-A95E-7E28A6D8CCA7}.Release|x86.ActiveCfg = Release|x64
{A61324AD-CE32-46D1-A95E-7E28A6D8CCA7}.Release|x86.Build.0 = Release|x64
{F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Debug|x64.ActiveCfg = Debug|x64
{F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Debug|x64.Build.0 = Debug|x64
{F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Debug|x86.ActiveCfg = Debug|Win32
{F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Debug|x86.Build.0 = Debug|Win32
{F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Release|x64.ActiveCfg = Release|x64
{F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Release|x64.Build.0 = Release|x64
{F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Release|x86.ActiveCfg = Release|Win32
{F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BCE727E8-4604-4D4F-B5FF-321A7D7868D6}
EndGlobalSection
EndGlobal
File diff suppressed because it is too large. Load diff
+209 -2
View File
@@ -1,5 +1,212 @@
#pragma once
bool InitVR();
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <Windows.h>
#include <openvr.h>
#include <vector>
#include <deque>
#include "../Protocol.h"
enum class CalibrationState
{
None,
Begin,
Rotation,
Translation,
Editing,
Continuous,
ContinuousStandby,
};
struct StandbyDevice {
std::string trackingSystem;
std::string model, serial;
};
struct CalibrationContext
{
CalibrationState state = CalibrationState::None;
int32_t referenceID = -1, targetID = -1;
static const size_t MAX_CONTROLLERS = 8;
int32_t controllerIDs[MAX_CONTROLLERS];
StandbyDevice targetStandby, referenceStandby;
Eigen::Vector3d calibratedRotation;
Eigen::Vector3d calibratedTranslation;
double calibratedScale;
std::string referenceTrackingSystem;
std::string targetTrackingSystem;
bool enabled = false;
bool validProfile = false;
bool clearOnLog = false;
bool quashTargetInContinuous = false;
bool requireTriggerPressToApply = false;
double timeLastTick = 0, timeLastScan = 0;
double wantedUpdateInterval = 1.0;
float xprev, yprev, zprev;
float continuousCalibrationThreshold;
Eigen::Vector3d continuousCalibrationOffset;
protocol::AlignmentSpeedParams alignmentSpeedParams;
bool enableStaticRecalibration;
bool lockRelativePosition = false;
Eigen::AffineCompact3d refToTargetPose = Eigen::AffineCompact3d::Identity();
bool relativePosCalibrated = false;
enum Speed
{
FAST = 0,
SLOW = 1,
VERY_SLOW = 2
};
Speed calibrationSpeed = FAST;
vr::DriverPose_t devicePoses[vr::k_unMaxTrackedDeviceCount];
CalibrationContext() {
calibratedScale = 1.0;
memset(devicePoses, 0, sizeof(devicePoses));
ResetConfig();
}
void ResetConfig() {
alignmentSpeedParams.thr_rot_tiny = 0.49f * (EIGEN_PI / 180.0f);
alignmentSpeedParams.thr_rot_small = 0.5f * (EIGEN_PI / 180.0f);
alignmentSpeedParams.thr_rot_large = 5.0f * (EIGEN_PI / 180.0f);
alignmentSpeedParams.thr_trans_tiny = 0.98f / 1000.0; // mm
alignmentSpeedParams.thr_trans_small = 1.0f / 1000.0; // mm
alignmentSpeedParams.thr_trans_large = 20.0f / 1000.0; // mm
alignmentSpeedParams.align_speed_tiny = 1.0f;
alignmentSpeedParams.align_speed_small = 1.0f;
alignmentSpeedParams.align_speed_large = 2.0f;
continuousCalibrationThreshold = 1.5f;
continuousCalibrationOffset = Eigen::Vector3d::Zero();
enableStaticRecalibration = true;
}
struct Chaperone
{
bool valid = false;
bool autoApply = true;
std::vector<vr::HmdQuad_t> geometry;
vr::HmdMatrix34_t standingCenter;
vr::HmdVector2_t playSpaceSize;
} chaperone;
void ClearLogOnMessage() {
clearOnLog = true;
}
void Clear()
{
chaperone.geometry.clear();
chaperone.standingCenter = vr::HmdMatrix34_t();
chaperone.playSpaceSize = vr::HmdVector2_t();
chaperone.valid = false;
calibratedRotation = Eigen::Vector3d();
calibratedTranslation = Eigen::Vector3d();
calibratedScale = 1.0;
referenceTrackingSystem = "";
targetTrackingSystem = "";
enabled = false;
validProfile = false;
refToTargetPose = Eigen::AffineCompact3d::Identity();
relativePosCalibrated = true;
}
size_t SampleCount()
{
switch (calibrationSpeed)
{
case FAST:
return 100;
case SLOW:
return 250;
case VERY_SLOW:
return 500;
}
return 100;
}
struct Message
{
enum Type
{
String,
Progress
} type = String;
Message(Type type) : type(type) { }
std::string str;
int progress, target;
};
std::deque<Message> messages;
void Log(const std::string &msg)
{
if (clearOnLog) {
messages.clear();
clearOnLog = false;
}
if (messages.empty() || messages.back().type == Message::Progress)
messages.push_back(Message(Message::String));
OutputDebugStringA(msg.c_str());
messages.back().str += msg;
std::cerr << msg;
while (messages.size() > 15) messages.pop_front();
}
void Progress(int current, int target)
{
if (messages.empty() || messages.back().type == Message::String)
messages.push_back(Message(Message::Progress));
messages.back().progress = current;
messages.back().target = target;
}
bool TargetPoseIsValid() const {
return targetID >= 0 && targetID <= vr::k_unMaxTrackedDeviceCount
&& devicePoses[targetID].poseIsValid;
}
bool ReferencePoseIsValid() const {
return referenceID >= 0 && referenceID <= vr::k_unMaxTrackedDeviceCount
&& devicePoses[referenceID].poseIsValid;
}
};
extern CalibrationContext CalCtx;
void InitCalibrator();
void CalibrationTick(double time);
void StartCalibration();
void CalibrationTick();
void StartContinuousCalibration();
void EndContinuousCalibration();
void LoadChaperoneBounds();
void ApplyChaperoneBounds();
void PushCalibrationApplyTime();
void ShowCalibrationDebug(int r, int c);
void DebugApplyRandomOffset();
+660
View File
@@ -0,0 +1,660 @@
#include "CalibrationCalc.h"
#include "Calibration.h"
#include "CalibrationMetrics.h"
#include "..\Protocol.h"
inline vr::HmdQuaternion_t operator*(const vr::HmdQuaternion_t& lhs, const vr::HmdQuaternion_t& rhs) {
return {
(lhs.w * rhs.w) - (lhs.x * rhs.x) - (lhs.y * rhs.y) - (lhs.z * rhs.z),
(lhs.w * rhs.x) + (lhs.x * rhs.w) + (lhs.y * rhs.z) - (lhs.z * rhs.y),
(lhs.w * rhs.y) + (lhs.y * rhs.w) + (lhs.z * rhs.x) - (lhs.x * rhs.z),
(lhs.w * rhs.z) + (lhs.z * rhs.w) + (lhs.x * rhs.y) - (lhs.y * rhs.x)
};
}
namespace {
inline vr::HmdVector3d_t quaternionRotateVector(const vr::HmdQuaternion_t& quat, const double(&vector)[3]) {
vr::HmdQuaternion_t vectorQuat = { 0.0, vector[0], vector[1] , vector[2] };
vr::HmdQuaternion_t conjugate = { quat.w, -quat.x, -quat.y, -quat.z };
auto rotatedVectorQuat = quat * vectorQuat * conjugate;
return { rotatedVectorQuat.x, rotatedVectorQuat.y, rotatedVectorQuat.z };
}
inline Eigen::Matrix3d quaternionRotateMatrix(const vr::HmdQuaternion_t& quat) {
return Eigen::Quaterniond(quat.w, quat.x, quat.y, quat.z).toRotationMatrix();
}
struct DSample
{
bool valid;
Eigen::Vector3d ref, target;
};
bool StartsWith(const std::string& str, const std::string& prefix)
{
if (str.length() < prefix.length())
return false;
return str.compare(0, prefix.length(), prefix) == 0;
}
bool EndsWith(const std::string& str, const std::string& suffix)
{
if (str.length() < suffix.length())
return false;
return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;
}
Eigen::Vector3d AxisFromRotationMatrix3(Eigen::Matrix3d rot)
{
return Eigen::Vector3d(rot(2, 1) - rot(1, 2), rot(0, 2) - rot(2, 0), rot(1, 0) - rot(0, 1));
}
double AngleFromRotationMatrix3(Eigen::Matrix3d rot)
{
return acos((rot(0, 0) + rot(1, 1) + rot(2, 2) - 1.0) / 2.0);
}
vr::HmdQuaternion_t VRRotationQuat(Eigen::Vector3d eulerdeg)
{
auto euler = eulerdeg * EIGEN_PI / 180.0;
Eigen::Quaterniond rotQuat =
Eigen::AngleAxisd(euler(0), Eigen::Vector3d::UnitZ()) *
Eigen::AngleAxisd(euler(1), Eigen::Vector3d::UnitY()) *
Eigen::AngleAxisd(euler(2), Eigen::Vector3d::UnitX());
vr::HmdQuaternion_t vrRotQuat;
vrRotQuat.x = rotQuat.coeffs()[0];
vrRotQuat.y = rotQuat.coeffs()[1];
vrRotQuat.z = rotQuat.coeffs()[2];
vrRotQuat.w = rotQuat.coeffs()[3];
return vrRotQuat;
}
vr::HmdVector3d_t VRTranslationVec(Eigen::Vector3d transcm)
{
auto trans = transcm * 0.01;
vr::HmdVector3d_t vrTrans;
vrTrans.v[0] = trans[0];
vrTrans.v[1] = trans[1];
vrTrans.v[2] = trans[2];
return vrTrans;
}
DSample DeltaRotationSamples(Sample s1, Sample s2)
{
// Difference in rotation between samples.
auto dref = s1.ref.rot * s2.ref.rot.transpose();
auto dtarget = s1.target.rot * s2.target.rot.transpose();
// When stuck together, the two tracked objects rotate as a pair,
// therefore their axes of rotation must be equal between any given pair of samples.
DSample ds;
ds.ref = AxisFromRotationMatrix3(dref);
ds.target = AxisFromRotationMatrix3(dtarget);
// Reject samples that were too close to each other.
auto refA = AngleFromRotationMatrix3(dref);
auto targetA = AngleFromRotationMatrix3(dtarget);
ds.valid = refA > 0.4 && targetA > 0.4 && ds.ref.norm() > 0.01 && ds.target.norm() > 0.01;
ds.ref.normalize();
ds.target.normalize();
return ds;
}
}
const double CalibrationCalc::AxisVarianceThreshold = 0.001;
void CalibrationCalc::PushSample(const Sample& sample) {
m_samples.push_back(sample);
}
void CalibrationCalc::Clear() {
m_estimatedTransformation.setIdentity();
m_isValid = false;
m_samples.clear();
m_axisVariance = 0.0;
m_refToTargetPose = Eigen::AffineCompact3d::Identity();
m_relativePosCalibrated = false;
}
Eigen::Vector3d CalibrationCalc::CalibrateRotation() const {
std::vector<DSample> deltas;
for (size_t i = 0; i < m_samples.size(); i++)
{
for (size_t j = 0; j < i; j++)
{
auto delta = DeltaRotationSamples(m_samples[i], m_samples[j]);
if (delta.valid)
deltas.push_back(delta);
}
}
//char buf[256];
//snprintf(buf, sizeof buf, "Got %zd samples with %zd delta samples\n", m_samples.size(), deltas.size());
//CalCtx.Log(buf);
// Kabsch algorithm
// Initialize 2D points and centroids
Eigen::MatrixXd refPoints(deltas.size(), 2), targetPoints(deltas.size(), 2);
Eigen::Vector2d refCentroid(0, 0), targetCentroid(0, 0);
// Fill matrices and calculate centroids
for (size_t i = 0; i < deltas.size(); i++) {
refPoints.row(i) << deltas[i].ref[0], deltas[i].ref[2]; // Take only the x and z components
refCentroid += refPoints.row(i);
targetPoints.row(i) << deltas[i].target[0], deltas[i].target[2]; // Take only the x and z components
targetCentroid += targetPoints.row(i);
}
refCentroid /= (double)deltas.size();
targetCentroid /= (double)deltas.size();
// Center the points
for (size_t i = 0; i < deltas.size(); i++) {
refPoints.row(i) -= refCentroid;
targetPoints.row(i) -= targetCentroid;
}
// Calculate cross-covariance matrix
auto crossCV = refPoints.transpose() * targetPoints;
// Singular Value Decomposition (SVD)
Eigen::JacobiSVD<Eigen::MatrixXd> svd(crossCV, Eigen::ComputeThinU | Eigen::ComputeThinV);
// Calculate 2D rotation matrix
Eigen::Matrix2d i = Eigen::Matrix2d::Identity();
Eigen::Matrix2d rot = svd.matrixV() * i * svd.matrixU().transpose();
// Calculate yaw angle in radians
double yaw = std::atan2(rot(1, 0), rot(0, 0));
// Convert to degrees
Eigen::Vector3d euler(0.0, yaw * 180.0 / EIGEN_PI, 0.0);
//snprintf(buf, sizeof buf, "Calibrated rotation: yaw=%.2f pitch=%.2f roll=%.2f\n", euler[1], euler[2], euler[0]);
//CalCtx.Log(buf);
return euler;
}
Eigen::Vector3d CalibrationCalc::CalibrateTranslation(const Eigen::Matrix3d &rotation) const
{
std::vector<std::pair<Eigen::Vector3d, Eigen::Matrix3d>> deltas;
for (size_t i = 0; i < m_samples.size(); i++)
{
Sample s_i = m_samples[i];
s_i.target.rot = rotation * s_i.target.rot;
s_i.target.trans = rotation * s_i.target.trans;
for (size_t j = 0; j < i; j++)
{
Sample s_j = m_samples[j];
s_j.target.rot = rotation * s_j.target.rot;
s_j.target.trans = rotation * s_j.target.trans;
auto QAi = s_i.ref.rot.transpose();
auto QAj = s_j.ref.rot.transpose();
auto dQA = QAj - QAi;
auto CA = QAj * (s_j.ref.trans - s_j.target.trans) - QAi * (s_i.ref.trans - s_i.target.trans);
deltas.push_back(std::make_pair(CA, dQA));
auto QBi = s_i.target.rot.transpose();
auto QBj = s_j.target.rot.transpose();
auto dQB = QBj - QBi;
auto CB = QBj * (s_j.ref.trans - s_j.target.trans) - QBi * (s_i.ref.trans - s_i.target.trans);
deltas.push_back(std::make_pair(CB, dQB));
}
}
Eigen::VectorXd constants(deltas.size() * 3);
Eigen::MatrixXd coefficients(deltas.size() * 3, 3);
for (size_t i = 0; i < deltas.size(); i++)
{
for (int axis = 0; axis < 3; axis++)
{
constants(i * 3 + axis) = deltas[i].first(axis);
coefficients.row(i * 3 + axis) = deltas[i].second.row(axis);
}
}
Eigen::Vector3d trans = coefficients.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(constants);
auto transcm = trans * 100.0;
//char buf[256];
//snprintf(buf, sizeof buf, "Calibrated translation x=%.2f y=%.2f z=%.2f\n", transcm[0], transcm[1], transcm[2]);
//CalCtx.Log(buf);
return trans;
}
void CalibrationCalc::CalibrateScaleOffset(const Eigen::Matrix3d& rotation, Eigen::Vector3d* out_scaleOffset, float* out_scaleFactor) const {
// @TODO: figure out where the target and ref
}
namespace {
Pose ApplyTransform(const Pose& originalPose, const Eigen::AffineCompact3d& transform) {
Pose pose(originalPose);
pose.rot = transform.rotation() * pose.rot;
pose.trans = transform * pose.trans;
return pose;
}
Pose ApplyTransform(const Pose & originalPose, const Eigen::Vector3d & vrTrans, const Eigen::Matrix3d & rotMat) {
Pose pose(originalPose);
pose.rot = rotMat * pose.rot;
pose.trans = vrTrans + (rotMat * pose.trans);
return pose;
}
}
Eigen::AffineCompact3d CalibrationCalc::ComputeCalibration() const {
Eigen::Vector3d rotation = CalibrateRotation();
Eigen::Matrix3d rotationMat = quaternionRotateMatrix(VRRotationQuat(rotation));
Eigen::Vector3d translation = CalibrateTranslation(rotationMat);
Eigen::AffineCompact3d rot(rotationMat);
Eigen::Translation3d trans(translation);
return trans * rot;
}
double CalibrationCalc::RetargetingErrorRMS(
const Eigen::Vector3d& hmdToTargetPos,
const Eigen::AffineCompact3d& calibration
) const {
double errorAccum = 0;
int sampleCount = 0;
for (auto& sample : m_samples) {
if (!sample.valid) continue;
// Apply transformation
const auto updatedPose = ApplyTransform(sample.target, calibration);
const Eigen::Vector3d hmdPoseSpace = sample.ref.rot * hmdToTargetPos + sample.ref.trans;
// Compute error term
double error = (updatedPose.trans - hmdPoseSpace).squaredNorm();
errorAccum += error;
sampleCount++;
}
return sqrt(errorAccum / sampleCount);
}
Eigen::Vector3d CalibrationCalc::ComputeRefToTargetOffset(const Eigen::AffineCompact3d& calibration) const {
Eigen::Vector3d accum = Eigen::Vector3d::Zero();
int sampleCount = 0;
for (auto& sample : m_samples) {
if (!sample.valid) continue;
// Apply transformation
const auto updatedPose = ApplyTransform(sample.target, calibration);
// Now move the transform from world to HMD space
const auto hmdOriginPos = updatedPose.trans - sample.ref.trans;
const auto hmdSpace = sample.ref.rot.inverse() * hmdOriginPos;
accum += hmdSpace;
sampleCount++;
}
accum /= sampleCount;
return accum;
}
Eigen::Vector4d CalibrationCalc::ComputeAxisVariance(
const Eigen::AffineCompact3d& calibration
) const {
// We want to determine if the user rotated in enough axis to find a unique solution.
// It's sufficient to rotate in two axis - this is because once we constrain the mapping
// of those two orthogonal basis vectors, the third is determined by the cross product of
// those two basis vectors. So, the question we then have to answer is - after accounting for
// translational movement of the HMD itself, are we too close to having only moved on a plane?
// To determine this, we perform primary component analysis on the rotation quaternions themselves.
// Since an angle axis quaternion is defined as the sum of Qidentity*cos(angle/2) + Qaxis*sin(angle/2),
// we expect that rotations around a single axis will have two primary components: One corresponding
// to the identity component, and one to the axis component. Thus, we check the variance (eigenvalue) of
// the third primary component to see if we've moved in two axis.
std::ostringstream dbgStream;
std::vector<Eigen::Vector4d> points;
Eigen::Vector4d mean = Eigen::Vector4d::Zero();
for (auto& sample : m_samples) {
if (!sample.valid) continue;
auto q = Eigen::Quaterniond(sample.target.rot);
auto point = Eigen::Vector4d(q.w(), q.x(), q.y(), q.z());
mean += point;
points.push_back(point);
}
mean /= (double) points.size();
// Compute covariance matrix
Eigen::Matrix4d covMatrix = Eigen::Matrix4d::Zero();
for (auto& point : points) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
covMatrix(i, j) += (point(i) - mean(i)) * (point(j) - mean(j));
}
}
}
covMatrix /= (double) points.size();
Eigen::SelfAdjointEigenSolver<Eigen::Matrix4d> solver;
solver.compute(covMatrix);
return solver.eigenvalues();
}
bool CalibrationCalc::ValidateCalibration(const Eigen::AffineCompact3d &calibration, double *error, Eigen::Vector3d *posOffsetV) {
bool ok = true;
const auto posOffset = ComputeRefToTargetOffset(calibration);
if (posOffsetV) *posOffsetV = posOffset;
// char buf[256];
//snprintf(buf, sizeof buf, "HMD to target offset: (%.2f, %.2f, %.2f)\n", posOffset(0), posOffset(1), posOffset(2));
//CalCtx.Log(buf);
double rmsError = RetargetingErrorRMS(posOffset, calibration);
//snprintf(buf, sizeof buf, "Position error (RMS): %.3f\n", rmsError);
//CalCtx.Log(buf);
if (rmsError > 0.1) ok = false;
if (error) *error = rmsError;
return ok;
}
// Given:
// R - the reference pose (in reference world space)
// T - the target pose (in target world space)
// C - the true calibration (target world -> reference world)
// We assume that there is some "static target pose" S s.t.:
// R * S = C * T (we'll call this the static target pose)
// To compute S:
// S = R^-1 * C * T
// To compute C:
// R * S * T^-1 = C
namespace {
class PoseAverager {
private:
Eigen::Matrix<double, 4, Eigen::Dynamic> quatAvg;
Eigen::Vector3d accum = Eigen::Vector3d::Zero();
int i = 0;
public:
PoseAverager(size_t n_samples) {
quatAvg.resize(4, n_samples);
}
template<typename P>
void Push(const P &pose) {
const Eigen::Quaterniond rot(pose.rotation());
quatAvg.col(i++) = Eigen::Vector4d(rot.w(), rot.x(), rot.y(), rot.z());
accum += pose.translation();
}
Eigen::AffineCompact3d Average() {
// https://stackoverflow.com/a/27410865/36723
auto quatT = quatAvg.transpose();
Eigen::Matrix4d quatMul = quatAvg * quatT;
Eigen::SelfAdjointEigenSolver<Eigen::Matrix4d> solver;
solver.compute(quatMul);
Eigen::Vector4d quatAvgV = solver.eigenvectors().col(3).real().normalized();
Eigen::Quaterniond avgQ(quatAvgV(0), quatAvgV(1), quatAvgV(2), quatAvgV(3));
avgQ.normalize();
Eigen::AffineCompact3d pose(avgQ);
pose.pretranslate(accum * (1.0 / i));
return pose;
}
template<typename XS, typename F>
static Eigen::AffineCompact3d AverageFor(const XS& samples, const F& poseProvider) {
int sampleCount = 0;
for (auto& sample : samples) {
if (!sample.valid) continue;
sampleCount++;
}
PoseAverager accum(sampleCount);
for (auto& sample : samples) {
if (!sample.valid) continue;
auto pose = poseProvider(sample);
accum.Push(pose);
}
return accum.Average();
}
};
}
// S = R^-1 * C * T
Eigen::AffineCompact3d CalibrationCalc::EstimateRefToTargetPose(const Eigen::AffineCompact3d &calibration) const {
auto avg = PoseAverager::AverageFor(m_samples, [&](const auto& sample) {
return Eigen::Affine3d(sample.ref.ToAffine().inverse() * calibration * sample.target.ToAffine());
});
#if 0
Eigen::Vector3d eulerAvgQ = avg.rotation().eulerAngles(2, 1, 0) * 180.0 / EIGEN_PI;
Eigen::Vector3d trans = Eigen::Vector3d(avg.translation());
std::ostringstream oss;
oss << "==========================================================================================\n";
oss << "Avg rot: " << eulerAvgQ.x() << ", " << eulerAvgQ.y() << ", " << eulerAvgQ.z() << "\n";
oss << "Avg trans:\n" << trans.x() << ", " << trans.y() << ", " << trans.z() << "\n";
OutputDebugStringA(oss.str().c_str());
#endif
return avg;
}
// S = R^-1 * C * T
// R * S * T^-1 = C
// R * (R^-1 * C * T) * T^-1 = C
/*
* This calibration routine attempts to use the estimated refToTargetPose to derive the
* playspace calibration based on the relative position of reference and target device.
* This computation can be performed even when the devices are not moving.
*/
bool CalibrationCalc::CalibrateByRelPose(Eigen::AffineCompact3d &out) const {
// R * S * T^-1 = C
out = PoseAverager::AverageFor(m_samples, [&](const auto& sample) {
return Eigen::AffineCompact3d(sample.ref.ToAffine() * m_refToTargetPose * sample.target.ToAffine().inverse());
});
return true;
}
bool CalibrationCalc::ComputeOneshot() {
auto calibration = ComputeCalibration();
bool valid = ValidateCalibration(calibration);
if (valid) {
m_estimatedTransformation = calibration; // @NOTE: Normal calibration
m_isValid = true;
return true;
}
else {
CalCtx.Log("Not updating: Low-quality calibration result\n");
return false;
}
}
void CalibrationCalc::ComputeInstantOffset() {
const auto &latestSample = m_samples.back();
// Apply transformation
const auto updatedPose = ApplyTransform(latestSample.target, m_estimatedTransformation);
// Now move the transform from world to HMD space
const auto hmdOriginPos = updatedPose.trans - latestSample.ref.trans;
const auto hmdSpace = latestSample.ref.rot.inverse() * hmdOriginPos;
Metrics::posOffset_lastSample.Push(hmdSpace * 1000);
}
bool CalibrationCalc::ComputeIncremental(bool &lerp, double threshold) {
Metrics::RecordTimestamp();
if (lockRelativePosition) {
Eigen::AffineCompact3d byRelPose;
double relPoseError = INFINITY;
Eigen::Vector3d relPosOffset;
CalibrateByRelPose(byRelPose);
ValidateCalibration(byRelPose, &relPoseError, &relPosOffset);
Metrics::posOffset_byRelPose.Push(relPosOffset * 1000);
Metrics::error_byRelPose.Push(relPoseError * 1000);
m_isValid = true;
m_estimatedTransformation = byRelPose;
return true;
}
double priorCalibrationError = INFINITY;
Eigen::Vector3d priorPosOffset;
if (m_isValid) {
ValidateCalibration(m_estimatedTransformation, &priorCalibrationError, &priorPosOffset);
Metrics::posOffset_currentCal.Push(priorPosOffset * 1000);
Metrics::error_currentCal.Push(priorCalibrationError * 1000);
if (priorCalibrationError < 0.005) {
return false;
}
}
double newError = INFINITY;
bool newCalibrationValid = false;
Eigen::AffineCompact3d byRelPose;
Eigen::AffineCompact3d calibration;
bool usingRelPose = false;
double relPoseError = INFINITY;
if (enableStaticRecalibration && CalibrateByRelPose(byRelPose)) {
Eigen::Vector3d relPosOffset;
ValidateCalibration(byRelPose, &relPoseError, &relPosOffset);
Metrics::posOffset_byRelPose.Push(relPosOffset * 1000);
Metrics::error_byRelPose.Push(relPoseError * 1000);
if (relPoseError < 0.010 || m_relativePosCalibrated && relPoseError < 0.025) {
newCalibrationValid = true;
usingRelPose = true;
newError = relPoseError;
calibration = byRelPose;
if (relPoseError * threshold >= priorCalibrationError) {
return false;
}
}
}
double newVariance = 0;
if (!newCalibrationValid) {
calibration = ComputeCalibration();
newVariance = ComputeAxisVariance(calibration)(1);
Metrics::axisIndependence.Push(newVariance);
if (newVariance < AxisVarianceThreshold && newVariance < m_axisVariance) {
newCalibrationValid = false;
} else {
newCalibrationValid = ValidateCalibration(calibration, &newError, &m_posOffset);
Metrics::posOffset_rawComputed.Push(m_posOffset * 1000);
}
if (m_isValid) {
if (priorCalibrationError < newError * threshold) {
// If we have a more noisy calibration than before, avoid updating.
newCalibrationValid = false;
}
}
Metrics::error_rawComputed.Push(newError * 1000);
ComputeInstantOffset();
}
#if 0
char tmp[256];
snprintf(tmp, sizeof tmp, "Prior calibration error: %.3f (valid: %s) sct %d; new error %.3f; new better? %s\n",
priorCalibrationError, m_isValid ? "yes" : "no", stableCt, newError, !oldCalibrationBetter ? "yes" : "no");
CalCtx.Log(tmp);
#endif
// Now, can we use the relative pose to perform a rapid correction?
if (!newCalibrationValid) {
double existingPoseErrorUsingRelPosition = RetargetingErrorRMS(m_refToTargetPose.translation(), m_estimatedTransformation);
Metrics::error_currentCalRelPose.Push(existingPoseErrorUsingRelPosition * 1000);
if (relPoseError * threshold < existingPoseErrorUsingRelPosition || newCalibrationValid && relPoseError < newError) {
newCalibrationValid = true;
usingRelPose = true;
newError = relPoseError;
calibration = byRelPose;
}
}
if (newCalibrationValid) {
lerp = m_isValid;
m_relativePosCalibrated = m_relativePosCalibrated || newError < 0.005;
if (!m_isValid) {
CalCtx.Log("Applying initial transformation...");
}
else if (m_relativePosCalibrated) {
CalCtx.Log("Applying updated transformation...");
} else {
CalCtx.Log("Applying temporary transformation...");
}
m_isValid = true;
m_estimatedTransformation = calibration; // @NOTE: Continuous calibration
m_axisVariance = newVariance;
if (!usingRelPose) {
m_refToTargetPose = EstimateRefToTargetPose(m_estimatedTransformation);
}
Metrics::calibrationApplied.Push(!usingRelPose);
return true;
}
else {
return false;
}
}
+144
View File
@@ -0,0 +1,144 @@
#pragma once
#include <Eigen/Dense>
#include <openvr.h>
#include <vector>
#include <deque>
#include <iostream>
struct Pose
{
Eigen::Matrix3d rot;
Eigen::Vector3d trans;
Pose() { }
Pose(const Eigen::AffineCompact3d& transform) {
rot = transform.rotation();
trans = transform.translation();
}
Pose(vr::HmdMatrix34_t hmdMatrix)
{
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
rot(i, j) = hmdMatrix.m[i][j];
}
}
trans = Eigen::Vector3d(hmdMatrix.m[0][3], hmdMatrix.m[1][3], hmdMatrix.m[2][3]);
}
Pose(vr::HmdQuaternion_t rot, const double *trans) {
this->rot = Eigen::Matrix3d(Eigen::Quaterniond(rot.w, rot.x, rot.y, rot.z));
this->trans = Eigen::Vector3d(trans[0], trans[1], trans[2]);
}
Pose(double x, double y, double z) : trans(Eigen::Vector3d(x, y, z)) { }
Eigen::Matrix4d ToAffine() const {
Eigen::Matrix4d matrix = Eigen::Matrix4d::Identity();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
matrix(i, j) = rot(i, j);
}
matrix(i, 3) = trans(i);
}
return matrix;
}
};
struct Sample
{
Pose ref, target;
bool valid;
Sample() : valid(false) { }
Sample(Pose ref, Pose target) : valid(true), ref(ref), target(target) { }
};
class CalibrationCalc {
public:
static const double AxisVarianceThreshold;
bool enableStaticRecalibration;
bool lockRelativePosition = false;
const Eigen::AffineCompact3d Transformation() const
{
return m_estimatedTransformation;
}
const Eigen::Vector3d EulerRotation() const {
auto rot = m_estimatedTransformation.rotation();
return rot.eulerAngles(2, 1, 0) * 180.0 / EIGEN_PI;
}
bool isValid() const {
return m_isValid;
}
const Eigen::AffineCompact3d RelativeTransformation() const
{
return m_refToTargetPose;
}
bool isRelativeTransformationCalibrated() const
{
return m_relativePosCalibrated;
}
void setRelativeTransformation(const Eigen::AffineCompact3d transform, bool calibrated)
{
m_refToTargetPose = transform;
m_relativePosCalibrated = calibrated;
}
void PushSample(const Sample& sample);
void Clear();
bool ComputeOneshot();
bool ComputeIncremental(bool &lerp, double threshold);
size_t SampleCount() const {
return m_samples.size();
}
void ShiftSample() {
if (!m_samples.empty()) m_samples.pop_front();
}
CalibrationCalc() : m_isValid(false), m_calcCycle(0), enableStaticRecalibration(true) {}
// Debug fields
Eigen::Vector3d m_posOffset;
double m_axisVariance = 0.0;
long m_calcCycle;
private:
bool m_isValid;
Eigen::AffineCompact3d m_estimatedTransformation;
bool m_relativePosCalibrated = false;
/*
* This affine transform estimates the pose of the target within the reference device's local pose space.
* That is to say, it's given by transforming the target world pose by the inverse reference pose.
*/
Eigen::AffineCompact3d m_refToTargetPose = Eigen::AffineCompact3d::Identity();
std::deque<Sample> m_samples;
Eigen::Vector3d CalibrateRotation() const;
Eigen::Vector3d CalibrateTranslation(const Eigen::Matrix3d &rotation) const;
void CalibrateScaleOffset(const Eigen::Matrix3d &rotation, Eigen::Vector3d* out_scaleOffset, float* out_scaleFactor) const;
Eigen::AffineCompact3d ComputeCalibration() const;
double RetargetingErrorRMS(const Eigen::Vector3d& hmdToTargetPos, const Eigen::AffineCompact3d& calibration) const;
Eigen::Vector3d ComputeRefToTargetOffset(const Eigen::AffineCompact3d& calibration) const;
Eigen::Vector4d ComputeAxisVariance(const Eigen::AffineCompact3d& calibration) const;
bool ValidateCalibration(const Eigen::AffineCompact3d& calibration, double *errorOut = nullptr, Eigen::Vector3d* posOffsetV = nullptr);
void ComputeInstantOffset();
Eigen::AffineCompact3d EstimateRefToTargetPose(const Eigen::AffineCompact3d& calibration) const;
bool CalibrateByRelPose(Eigen::AffineCompact3d &out) const;
};
+379
View File
@@ -0,0 +1,379 @@
#include "stdafx.h"
#include <vector>
#include <implot/implot.h>
#include "CalibrationCalc.h"
#include "CalibrationMetrics.h"
#include "UserInterface.h"
// ImPlotPoint (*ImPlotGetter)(void* user_data, int idx);
namespace {
double refTime;
template<typename F>
ImPlotPoint VPIndexer(void* ptr, int idx) {
auto point = (*reinterpret_cast<const F*>(ptr))(idx);
point.x -= refTime;
return point;
}
template<typename F>
void PlotLineG(const char* name, const F& f, int points) {
const void* vp_f = &f;
if (points > 0) {
ImPlot::PlotLineG(name, VPIndexer<F>, const_cast<void*>(vp_f), points);
}
else {
double x = -INFINITY;
double y = 0;
ImPlot::PlotLine(name, &x, &y, 1);
}
}
template<typename F, typename G>
void PlotShadedG(const char* name, const F& data, const G& reference, int count) {
const void* vp_data = &data;
const void* vp_reference = &reference;
if (count > 0) {
ImPlot::PlotShadedG(name,
VPIndexer<F>, const_cast<void*>(vp_data),
VPIndexer<G>, const_cast<void*>(vp_reference),
count
);
}
else {
double x = -INFINITY;
double y = 0;
ImPlot::PlotShaded(name, &x, &y, &y, 1);
}
}
void PlotLineG(const char* name, const Metrics::TimeSeries<double>& ts) {
PlotLineG(name, [&](int index) {
const auto& p = ts[index];
return ImPlotPoint(p.first, p.second);
},
ts.size()
);
}
void PlotVector(const char* namePrefix, const Metrics::TimeSeries<Eigen::Vector3d>& ts) {
std::string name(namePrefix);
name += "X";
PlotLineG(name.c_str(), [&](int index) {
const auto& p = ts[index];
return ImPlotPoint(p.first, p.second(0));
}, ts.size());
name.pop_back();
name += "Y";
PlotLineG(name.c_str(), [&](int index) {
const auto& p = ts[index];
return ImPlotPoint(p.first, p.second(1));
}, ts.size());
name.pop_back();
name += "Z";
PlotLineG(name.c_str(), [&](int index) {
const auto& p = ts[index];
return ImPlotPoint(p.first, p.second(2));
}, ts.size());
}
double lastMouseX = -INFINITY;
bool wasHovered;
std::vector<double> calAppliedTimeBuffer, calByRelPoseTimeBuffer;
void PrepApplyTicks() {
calAppliedTimeBuffer.clear();
calByRelPoseTimeBuffer.clear();
for (auto t : Metrics::calibrationApplied.data()) {
if (t.second) {
calAppliedTimeBuffer.push_back(t.first - refTime);
}
else {
calByRelPoseTimeBuffer.push_back(t.first - refTime);
}
}
}
void AddApplyTicks() {
if (calAppliedTimeBuffer.empty()) {
double x = -INFINITY;
ImPlot::PlotVLines("##CalibrationAppliedTime", &x, 1);
} else {
ImPlot::PlotVLines("##CalibrationAppliedTime", &calAppliedTimeBuffer[0], (int)calAppliedTimeBuffer.size());
}
if (calByRelPoseTimeBuffer.empty()) {
double x = -INFINITY;
ImPlot::PlotVLines("##CalibrationAppliedTimeByRelPose", &x, 1);
}
else {
ImPlot::PlotVLines("##CalibrationAppliedTimeByRelPose", &calByRelPoseTimeBuffer[0], (int)calByRelPoseTimeBuffer.size());
}
ImPlot::SetNextLineStyle(ImVec4(0.5, 0.5, 1, 1));
ImPlot::PlotVLines("##TagLine", &lastMouseX, 1);
if (ImPlot::IsPlotHovered()) {
auto mousePos = ImPlot::GetPlotMousePos();
lastMouseX = mousePos.x;
wasHovered = true;
}
}
struct GraphInfo {
const char* name;
void (*callback)();
};
void SetupXAxis() {
ImPlot::SetupAxisLimits(ImAxis_X1, -Metrics::TimeSpan, 0, ImGuiCond_Always);
}
void G_PosOffset_RawComputed() {
if (ImPlot::BeginPlot("##posOffsetRawComputed")) {
ImPlot::SetupAxes(NULL, "mm", 0, ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_RangeFit);
SetupXAxis();
ImPlot::SetupAxisLimits(ImAxis_Y1, -200, 200, ImGuiCond_Appearing);
AddApplyTicks();
PlotVector("", Metrics::posOffset_rawComputed);
ImPlot::EndPlot();
}
}
void G_PosOffset_CurrentCal() {
if (ImPlot::BeginPlot("##posOffsetCurrentCal")) {
ImPlot::SetupAxes(NULL, "mm", 0, ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_RangeFit);
SetupXAxis();
ImPlot::SetupAxisLimits(ImAxis_Y1, -200, 200, ImGuiCond_Appearing);
AddApplyTicks();
PlotVector("", Metrics::posOffset_currentCal);
ImPlot::EndPlot();
}
}
void G_PosOffset_LastSample() {
if (ImPlot::BeginPlot("##posOffsetLastSample")) {
ImPlot::SetupAxes(NULL, "mm", 0, ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_RangeFit);
SetupXAxis();
ImPlot::SetupAxisLimits(ImAxis_Y1, -200, 200, ImGuiCond_Appearing);
AddApplyTicks();
PlotVector("", Metrics::posOffset_lastSample);
ImPlot::EndPlot();
}
}
void G_PosOffset_ByRelPose() {
if (ImPlot::BeginPlot("##posOffsetByRelPose")) {
ImPlot::SetupAxes(NULL, "mm", 0, ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_RangeFit);
SetupXAxis();
ImPlot::SetupAxisLimits(ImAxis_Y1, -200, 200, ImGuiCond_Appearing);
AddApplyTicks();
PlotVector("", Metrics::posOffset_byRelPose);
ImPlot::EndPlot();
}
}
void G_PosOffset_PosError() {
if (ImPlot::BeginPlot("##Position error")) {
ImPlot::SetupAxes(NULL, "mm (RMS)");
SetupXAxis();
ImPlot::SetupAxisLimits(ImAxis_Y1, 0, 25, ImGuiCond_Appearing);
AddApplyTicks();
PlotLineG("Candidate", Metrics::error_rawComputed);
PlotLineG("Active", Metrics::error_currentCal);
PlotLineG("By Rel Pose", Metrics::error_byRelPose);
PlotLineG("CC Rel Pose", Metrics::error_currentCalRelPose);
ImPlot::EndPlot();
}
}
void G_ComputationTime() {
if (ImPlot::BeginPlot("##Computation Time", ImVec2(-1, 0), ImPlotFlags_NoLegend)) {
ImPlot::SetupAxes(NULL, "ms", 0, ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_RangeFit);
SetupXAxis();
ImPlot::SetupAxisLimits(ImAxis_Y1, 0, 200, ImGuiCond_Appearing);
AddApplyTicks();
PlotLineG("Time", Metrics::computationTime);
ImPlot::EndPlot();
}
}
void G_AxisVariance() {
static bool firstrun = true;
static ImPlotColormap axisVarianceColormap;
if (firstrun) {
firstrun = false;
auto defaultFirst = ImPlot::GetColormapColor(0);
ImVec4 colors[] = {
ImPlot::GetColormapColor(0),
ImPlot::GetColormapColor(1),
{ 1, 0, 0, 1 },
{ 0, 1, 0, 1 },
{ 0.5, 0.5, 0.5, 1 },
};
axisVarianceColormap = ImPlot::AddColormap("AxisVarianceColormap", colors, sizeof(colors) / sizeof(colors[0]));
}
if (ImPlot::BeginPlot("##Axis variance", ImVec2(-1, 0), ImPlotFlags_NoLegend)) {
ImPlot::SetupAxes(NULL, NULL, 0, 0);
SetupXAxis();
ImPlot::SetupAxisLimits(ImAxis_Y1, 0, 0.003, ImGuiCond_Always);
AddApplyTicks();
ImPlot::PushColormap(axisVarianceColormap);
ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.5f);
ImPlot::SetNextLineStyle(ImVec4(1, 0, 0, 1));
PlotShadedG("##VarianceLow",
[&](int index) {
auto p = Metrics::axisIndependence[index];
p.second = min(p.second, CalibrationCalc::AxisVarianceThreshold);
return ImPlotPoint(p.first, p.second);
},
[&](int index) {
auto p = Metrics::axisIndependence[index];
return ImPlotPoint(p.first, 0);
},
Metrics::axisIndependence.size()
);
ImPlot::SetNextLineStyle(ImVec4(0, 1, 0, 1));
PlotShadedG("##VarianceHigh",
[&](int index) {
auto p = Metrics::axisIndependence[index];
p.second = max(p.second, CalibrationCalc::AxisVarianceThreshold);
return ImPlotPoint(p.first, p.second);
},
[&](int index) {
auto p = Metrics::axisIndependence[index];
return ImPlotPoint(p.first, CalibrationCalc::AxisVarianceThreshold);
},
Metrics::axisIndependence.size()
);
PlotLineG("Datapoint", Metrics::axisIndependence);
ImPlot::PopStyleVar(1);
ImPlot::PopColormap(1);
ImPlot::EndPlot();
}
}
const struct GraphInfo graphs[] = {
{ "Position Error", G_PosOffset_PosError },
{ "Axis Variance", G_AxisVariance },
{ "Offset: Raw Computed", G_PosOffset_RawComputed },
{ "Offset: Current Calibration", G_PosOffset_CurrentCal },
{ "Offset: Last Sample", G_PosOffset_LastSample },
{ "Offset: By Rel Pose", G_PosOffset_ByRelPose },
{ "Processing time", G_ComputationTime }
};
const int N_GRAPHS = sizeof(graphs) / sizeof(graphs[0]);
}
void PushCalibrationApplyTime() {
Metrics::calibrationApplied.Push(true);
}
void ShowCalibrationDebug(int rows, int cols) {
static std::vector<int> curIndexes;
//ImGui::ShowDemoWindow();
//ImPlot::ShowDemoWindow();
double initMouseX = lastMouseX;
wasHovered = false;
for (int i = (int)curIndexes.size(); i < rows * cols; i++) {
curIndexes.push_back(i % N_GRAPHS);
}
auto avail = ImGui::GetContentRegionAvail();
auto bgCol = ImGui::GetStyleColorVec4(ImGuiCol_FrameBg);
ImGui::PushStyleColor(ImGuiCol_TableRowBg, bgCol);
ImGui::PushStyleColor(ImGuiCol_TableRowBgAlt, bgCol);
ImPlot::PushStyleColor(ImPlotCol_FrameBg, ImVec4(0,0,0,0));
ImGui::SetNextWindowBgAlpha(1);
if (!ImGui::BeginChild("##CalibrationDebug", avail, false,
ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoTitleBar)) {
ImGui::EndChild();
return;
}
if (!ImGui::BeginTable("##CalibrationDebug", cols, ImGuiTableFlags_RowBg)) {
return;
}
double t = refTime = Metrics::timestamp();
PrepApplyTicks();
for (int r = 0; r < rows; r++) {
ImGui::TableNextRow();
for (int c = 0; c < cols; c++) {
int i = r * cols + c;
ImGui::TableSetColumnIndex(c);
ImGui::PushID(i);
ImGui::SetNextItemWidth(ImGui::GetColumnWidth());
if (ImGui::BeginCombo("", graphs[curIndexes[i]].name, 0)) {
for (int j = 0; j < N_GRAPHS; j++) {
bool isSelected = j == curIndexes[i];
if (ImGui::Selectable(graphs[j].name, isSelected)) {
curIndexes[i] = j;
}
if (isSelected) ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
graphs[curIndexes[i]].callback();
ImGui::PopID();
}
}
ImGui::EndTable();
ImGui::EndChild();
ImPlot::PopStyleColor(1);
ImGui::PopStyleColor(2);
if (!wasHovered) {
lastMouseX = -INFINITY;
}
}
@@ -0,0 +1,215 @@
#include "stdafx.h"
#include "CalibrationMetrics.h"
#include <shlobj_core.h>
#include <fstream>
#include <vector>
namespace Metrics {
double TimeSpan = 30, CurrentTime;
TimeSeries<Eigen::Vector3d> posOffset_rawComputed; // , rotOffset_rawComputed;
TimeSeries<Eigen::Vector3d> posOffset_currentCal; // , rotOffset_currentCal;
TimeSeries<Eigen::Vector3d> posOffset_lastSample; // , rotOffset_lastSample;
TimeSeries<Eigen::Vector3d> posOffset_byRelPose;
TimeSeries<double> error_rawComputed, error_currentCal, error_byRelPose, error_currentCalRelPose;
TimeSeries<double> axisIndependence;
TimeSeries<double> computationTime;
// true - full calibration, false - static calibration
TimeSeries<bool> calibrationApplied;
double timestamp() {
static long long ts_start = ~0LL;
LARGE_INTEGER ts, freq;
QueryPerformanceCounter(&ts);
QueryPerformanceFrequency(&freq);
if (ts_start == ~0LL) ts_start = ts.QuadPart;
ts.QuadPart -= ts_start;
return ts.QuadPart / (double)freq.QuadPart;
}
void RecordTimestamp() {
CurrentTime = timestamp();
}
bool enableLogs = false;
static std::ofstream logFile;
static bool logFileIsOpen = false;
static bool failedToOpenLogFile = false;
struct CsvField {
const char* name;
void (*writer)(std::ofstream& s);
};
#define TS_FIELD(n) \
{ #n, [](auto &s) { s << n.last(); } }
#define TS_VECTOR_FIELD(n) \
{ #n ".x", [](auto &s) { s << n.last()(0); } }, \
{ #n ".y", [](auto &s) { s << n.last()(1); } }, \
{ #n ".z", [](auto &s) { s << n.last()(2); } }
static const CsvField fields[] = {
{
"Timestamp",
[](auto& s) { s << CurrentTime; }
},
TS_VECTOR_FIELD(posOffset_rawComputed),
TS_VECTOR_FIELD(posOffset_currentCal),
TS_VECTOR_FIELD(posOffset_lastSample),
TS_VECTOR_FIELD(posOffset_byRelPose),
TS_FIELD(error_rawComputed),
TS_FIELD(error_currentCal),
TS_FIELD(error_byRelPose),
TS_FIELD(error_currentCalRelPose),
TS_FIELD(axisIndependence),
TS_FIELD(computationTime),
{
"calibrationApplied",
[](auto& s) {
if (calibrationApplied.lastTs() == CurrentTime) {
if (calibrationApplied.last()) {
s << "FULL";
}
else {
s << "STATIC";
}
}
}
}
};
static void ClearOldLogs(const std::wstring& path) {
std::wstring search_path = path + L"\\spacecal_log.*.txt";
WIN32_FIND_DATA find_data;
SYSTEMTIME st_now;
FILETIME ft_now;
GetSystemTime(&st_now);
SystemTimeToFileTime(&st_now, &ft_now);
ULARGE_INTEGER ft_tmp;
ft_tmp.HighPart = ft_now.dwHighDateTime;
ft_tmp.LowPart = ft_now.dwLowDateTime;
// one day ago
uint64_t limit = ft_tmp.QuadPart - (uint64_t)(24LL * 3600LL * 10LL * 1000LL * 1000LL);
HANDLE find_handle = FindFirstFile(search_path.c_str(), &find_data);
if (find_handle != INVALID_HANDLE_VALUE) {
do {
ft_tmp.HighPart = find_data.ftLastWriteTime.dwHighDateTime;
ft_tmp.LowPart = find_data.ftLastWriteTime.dwLowDateTime;
if (ft_tmp.QuadPart < limit) {
std::wstring file_path = path + L"\\" + find_data.cFileName;
DeleteFile(file_path.c_str());
}
} while (FindNextFile(find_handle, &find_data));
FindClose(find_handle);
}
}
static bool OpenLogFile() {
PWSTR RootPath = NULL;
if (S_OK != SHGetKnownFolderPath(FOLDERID_LocalAppDataLow, 0, NULL, &RootPath)) {
CoTaskMemFree(RootPath);
return false;
}
std::wstring path(RootPath);
CoTaskMemFree(RootPath);
path += LR"(\OpenVR-SpaceCalibrator)";
if (CreateDirectoryW(path.c_str(), 0) == 0 && GetLastError() != ERROR_ALREADY_EXISTS) {
return false;
}
path += LR"(\Logs)";
if (CreateDirectoryW(path.c_str(), 0) == 0 && GetLastError() != ERROR_ALREADY_EXISTS) {
return false;
}
ClearOldLogs(path);
SYSTEMTIME now;
GetSystemTime(&now);
size_t dateBufLen = GetDateFormatW(LOCALE_USER_DEFAULT, 0, &now, L"yyyy-MM-dd", NULL, 0);
std::vector<WCHAR> dateBuf(dateBufLen);
if (!GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &now, L"yyyy-MM-dd", &dateBuf[0], dateBufLen, NULL)) return false;
size_t timeBufLen = GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &now, L"HH-mm-ss", NULL, 0);
std::vector<WCHAR> timeBuf(timeBufLen);
if (!GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &now, L"HH-mm-ss", &timeBuf[0], timeBufLen)) return false;
path += LR"(\spacecal_log.)";
path += &dateBuf[0];
path += L"T";
path += &timeBuf[0];
path += L".txt";
logFile.open(path);
if (logFile.fail()) {
return false;
}
for (int i = 0; i < sizeof fields / sizeof fields[0]; i++) {
if (i > 0) logFile << ",";
logFile << fields[i].name;
}
logFile << "\n";
logFileIsOpen = true;
return true;
}
static bool CheckLogOpen() {
if (!enableLogs) {
if (logFileIsOpen) {
logFile.close();
}
logFileIsOpen = false;
failedToOpenLogFile = false;
return false;
}
if (failedToOpenLogFile) return false;
if (!logFileIsOpen && !OpenLogFile()) {
failedToOpenLogFile = true;
return false;
}
return true;
}
void WriteLogAnnotation(const char *s) {
if (!CheckLogOpen()) return;
logFile << "# [" << timestamp() << "] " << s << "\n";
logFile.flush();
}
void WriteLogEntry() {
if (!CheckLogOpen()) return;
if (logFileIsOpen) {
for (int i = 0; i < sizeof fields / sizeof fields[0]; i++) {
if (i > 0) logFile << ",";
fields[i].writer(logFile);
}
logFile << "\n";
}
logFile.flush();
}
}
@@ -0,0 +1,58 @@
#pragma once
#include <deque>
#include <utility>
#include <Eigen/Dense>
namespace Metrics {
extern double TimeSpan, CurrentTime;
double timestamp();
void RecordTimestamp();
template<typename T>
class TimeSeries {
std::deque<std::pair<double, T>> Data;
public:
const std::deque<std::pair<double, T>> &data() const { return Data; }
void Push(const T& data) {
Data.push_back(std::make_pair(CurrentTime, data));
double cutoff = CurrentTime - TimeSpan;
while (!Data.empty() && (Data.front().first < cutoff || Data.size() > INT_MAX)) {
Data.pop_front();
}
}
int size() const { return (int)Data.size(); }
const std::pair<double, T>& operator[](int index) const { return Data[index]; }
const T& last() const {
static const T fallback;
return Data.size() > 0 ? Data.back().second : fallback;
}
const double lastTs() const {
return Data.size() > 0 ? Data.back().first : 0;
}
};
extern TimeSeries<Eigen::Vector3d> posOffset_rawComputed; // , rotOffset_rawComputed;
extern TimeSeries<Eigen::Vector3d> posOffset_currentCal; // , rotOffset_currentCal;
extern TimeSeries<Eigen::Vector3d> posOffset_lastSample; // , rotOffset_lastSample;
extern TimeSeries<Eigen::Vector3d> posOffset_byRelPose;
extern TimeSeries<double> error_rawComputed, error_currentCal, error_byRelPose, error_currentCalRelPose;
extern TimeSeries<double> axisIndependence;
extern TimeSeries<double> computationTime;
extern TimeSeries<bool> calibrationApplied;
extern bool enableLogs;
void WriteLogAnnotation(const char* s);
void WriteLogEntry();
}
+364
View File
@@ -0,0 +1,364 @@
#include "stdafx.h"
#include "Configuration.h"
#include <picojson.h>
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <limits>
static picojson::array FloatArray(const float *buf, int numFloats)
{
picojson::array arr;
for (int i = 0; i < numFloats; i++)
arr.push_back(picojson::value(double(buf[i])));
return arr;
}
static void LoadFloatArray(const picojson::value &obj, float *buf, int numFloats)
{
if (!obj.is<picojson::array>())
throw std::runtime_error("expected array, got " + obj.to_str());
auto &arr = obj.get<picojson::array>();
if (arr.size() != numFloats)
throw std::runtime_error("wrong buffer size");
for (int i = 0; i < numFloats; i++)
buf[i] = (float) arr[i].get<double>();
}
static void LoadStandby(StandbyDevice& device, picojson::value& value) {
if (!value.is<picojson::object>()) return;
auto& obj = value.get<picojson::object>();
const auto &system = obj["tracking_system"];
if (system.is<std::string>()) device.trackingSystem = system.get<std::string>();
const auto& model = obj["model"];
if (model.is<std::string>()) device.model = model.get<std::string>();
const auto& serial = obj["serial"];
if (serial.is<std::string>()) device.serial = serial.get<std::string>();
}
static void VisitAlignmentParams(CalibrationContext& ctx, std::function<void(const char *, double&)> MapParam) {
#define P(s) MapParam(#s, ctx.alignmentSpeedParams.s)
P(align_speed_tiny);
P(align_speed_small);
P(align_speed_large);
P(thr_trans_tiny);
P(thr_trans_small);
P(thr_trans_large);
P(thr_rot_tiny);
P(thr_rot_small);
P(thr_rot_large);
// Convert to double and back
double tmp = ctx.continuousCalibrationThreshold;
MapParam("continuousCalibrationThreshold", tmp);
ctx.continuousCalibrationThreshold = (float)tmp;
}
static void LoadAlignmentParams(CalibrationContext& ctx, picojson::value& value) {
ctx.ResetConfig();
if (!value.is<picojson::object>()) return;
auto& obj = value.get<picojson::object>();
VisitAlignmentParams(ctx, [&](auto name, auto& param) {
const picojson::value& node = obj[name];
if (node.is<double>()) {
param = (float)node.get<double>();
}
});
}
static picojson::object SaveAlignmentParams(CalibrationContext& ctx) {
picojson::object obj;
VisitAlignmentParams(ctx, [&](auto name, auto& param) {
obj[name].set<double>(param);
});
return obj;
}
static void ParseProfile(CalibrationContext &ctx, std::istream &stream)
{
picojson::value v;
std::string err = picojson::parse(v, stream);
if (!err.empty())
throw std::runtime_error(err);
auto arr = v.get<picojson::array>();
if (arr.size() < 1)
throw std::runtime_error("no profiles in file");
auto obj = arr[0].get<picojson::object>();
LoadAlignmentParams(ctx, obj["alignment_params"]);
ctx.referenceTrackingSystem = obj["reference_tracking_system"].get<std::string>();
ctx.targetTrackingSystem = obj["target_tracking_system"].get<std::string>();
ctx.calibratedRotation(0) = obj["roll"].get<double>();
ctx.calibratedRotation(1) = obj["yaw"].get<double>();
ctx.calibratedRotation(2) = obj["pitch"].get<double>();
ctx.calibratedTranslation(0) = obj["x"].get<double>();
ctx.calibratedTranslation(1) = obj["y"].get<double>();
ctx.calibratedTranslation(2) = obj["z"].get<double>();
LoadStandby(ctx.referenceStandby, obj["reference_device"]);
LoadStandby(ctx.targetStandby, obj["target_device"]);
if (obj["autostart_continuous_calibration"].evaluate_as_boolean()) {
ctx.state = CalibrationState::ContinuousStandby;
}
ctx.quashTargetInContinuous = obj["quash_target_in_continuous"].evaluate_as_boolean();
ctx.requireTriggerPressToApply = obj["require_trigger_press_to_apply"].evaluate_as_boolean();
ctx.continuousCalibrationOffset(0) = obj["continuous_calibration_target_offset_x"].get<double>();
ctx.continuousCalibrationOffset(1) = obj["continuous_calibration_target_offset_y"].get<double>();
ctx.continuousCalibrationOffset(2) = obj["continuous_calibration_target_offset_z"].get<double>();
if (obj["scale"].is<double>())
ctx.calibratedScale = obj["scale"].get<double>();
else
ctx.calibratedScale = 1.0;
if (obj["calibration_speed"].is<double>())
ctx.calibrationSpeed = (CalibrationContext::Speed)(int) obj["calibration_speed"].get<double>();
if (obj["chaperone"].is<picojson::object>())
{
auto chaperone = obj["chaperone"].get<picojson::object>();
ctx.chaperone.autoApply = chaperone["auto_apply"].get<bool>();
LoadFloatArray(chaperone["play_space_size"], ctx.chaperone.playSpaceSize.v, 2);
LoadFloatArray(
chaperone["standing_center"],
(float *) ctx.chaperone.standingCenter.m,
sizeof(ctx.chaperone.standingCenter.m) / sizeof(float)
);
if (!chaperone["geometry"].is<picojson::array>())
throw std::runtime_error("chaperone geometry is not an array");
auto &geometry = chaperone["geometry"].get<picojson::array>();
if (geometry.size() > 0)
{
ctx.chaperone.geometry.resize(geometry.size() * sizeof(float) / sizeof(ctx.chaperone.geometry[0]));
LoadFloatArray(chaperone["geometry"], (float *) ctx.chaperone.geometry.data(), geometry.size());
ctx.chaperone.valid = true;
}
}
if (obj["relative_pos_calibrated"].is<bool>()) {
ctx.relativePosCalibrated = obj["relative_pos_calibrated"].get<bool>();
}
if (obj["lock_relative_position"].is<bool>()) {
ctx.lockRelativePosition = obj["lock_relative_position"].get<bool>();
}
if (obj["relative_transform"].is<picojson::object>()) {
auto relTransform = obj["relative_transform"].get<picojson::object>();
Eigen::Vector3d refToTragetRoation;
Eigen::Vector3d refToTargetTranslation;
refToTragetRoation(0) = relTransform["roll"].get<double>();
refToTragetRoation(1) = relTransform["yaw"].get<double>();
refToTragetRoation(2) = relTransform["pitch"].get<double>();
refToTargetTranslation(0) = relTransform["x"].get<double>();
refToTargetTranslation(1) = relTransform["y"].get<double>();
refToTargetTranslation(2) = relTransform["z"].get<double>();
Eigen::Matrix3d rotationMatrix;
rotationMatrix =
Eigen::AngleAxisd(refToTragetRoation[0], Eigen::Vector3d::UnitX()) *
Eigen::AngleAxisd(refToTragetRoation[1], Eigen::Vector3d::UnitY()) *
Eigen::AngleAxisd(refToTragetRoation[2], Eigen::Vector3d::UnitZ());
ctx.refToTargetPose = Eigen::AffineCompact3d::Identity();
ctx.refToTargetPose.linear() = rotationMatrix;
ctx.refToTargetPose.translation() = refToTargetTranslation;
}
ctx.validProfile = true;
}
static void WriteStandby(StandbyDevice& device, picojson::value& value) {
auto obj = picojson::object();
obj["tracking_system"].set<std::string>(device.trackingSystem);
obj["model"].set<std::string>(device.model);
obj["serial"].set<std::string>(device.serial);
value.set<picojson::object>(obj);
}
static void WriteProfile(CalibrationContext &ctx, std::ostream &out)
{
if (!ctx.validProfile)
return;
picojson::object profile;
profile["alignment_params"].set<picojson::object>(SaveAlignmentParams(ctx));
profile["reference_tracking_system"].set<std::string>(ctx.referenceTrackingSystem);
profile["target_tracking_system"].set<std::string>(ctx.targetTrackingSystem);
profile["roll"].set<double>(ctx.calibratedRotation(0));
profile["yaw"].set<double>(ctx.calibratedRotation(1));
profile["pitch"].set<double>(ctx.calibratedRotation(2));
profile["x"].set<double>(ctx.calibratedTranslation(0));
profile["y"].set<double>(ctx.calibratedTranslation(1));
profile["z"].set<double>(ctx.calibratedTranslation(2));
profile["scale"].set<double>(ctx.calibratedScale);
WriteStandby(ctx.referenceStandby, profile["reference_device"]);
WriteStandby(ctx.targetStandby, profile["target_device"]);
bool isInContinuousCalibrationMode = ctx.state == CalibrationState::Continuous || ctx.state == CalibrationState::ContinuousStandby;
profile["autostart_continuous_calibration"].set<bool>(isInContinuousCalibrationMode);
profile["quash_target_in_continuous"].set<bool>(ctx.quashTargetInContinuous);
profile["require_trigger_press_to_apply"].set<bool>(ctx.requireTriggerPressToApply);
profile["continuous_calibration_target_offset_x"].set<double>(ctx.continuousCalibrationOffset(0));
profile["continuous_calibration_target_offset_y"].set<double>(ctx.continuousCalibrationOffset(1));
profile["continuous_calibration_target_offset_z"].set<double>(ctx.continuousCalibrationOffset(2));
double speed = (int) ctx.calibrationSpeed;
profile["calibration_speed"].set<double>(speed);
if (ctx.chaperone.valid)
{
picojson::object chaperone;
chaperone["auto_apply"].set<bool>(ctx.chaperone.autoApply);
chaperone["play_space_size"].set<picojson::array>(FloatArray(ctx.chaperone.playSpaceSize.v, 2));
chaperone["standing_center"].set<picojson::array>(FloatArray(
(float *) ctx.chaperone.standingCenter.m,
sizeof(ctx.chaperone.standingCenter.m) / sizeof(float)
));
chaperone["geometry"].set<picojson::array>(FloatArray(
(float *) ctx.chaperone.geometry.data(),
sizeof(ctx.chaperone.geometry[0]) / sizeof(float) * ctx.chaperone.geometry.size()
));
profile["chaperone"].set<picojson::object>(chaperone);
}
Eigen::Vector3d refToTragetRoation = ctx.refToTargetPose.rotation().eulerAngles(0, 1, 2);
Eigen::Vector3d refToTargetTranslation = ctx.refToTargetPose.translation();
picojson::object refToTarget;
refToTarget["x"].set<double>(refToTargetTranslation(0));
refToTarget["y"].set<double>(refToTargetTranslation(1));
refToTarget["z"].set<double>(refToTargetTranslation(2));
refToTarget["roll"].set<double>(refToTragetRoation(0));
refToTarget["yaw"].set<double>(refToTragetRoation(1));
refToTarget["pitch"].set<double>(refToTragetRoation(2));
profile["relative_pos_calibrated"].set<bool>(ctx.relativePosCalibrated);
profile["lock_relative_position"].set<bool>(ctx.lockRelativePosition);
profile["relative_transform"].set<picojson::object>(refToTarget);
picojson::value profileV;
profileV.set<picojson::object>(profile);
picojson::array profiles;
profiles.push_back(profileV);
picojson::value profilesV;
profilesV.set<picojson::array>(profiles);
out << profilesV.serialize(true);
}
static void LogRegistryResult(LSTATUS result)
{
char *message;
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, result, LANG_USER_DEFAULT, (LPSTR)&message, 0, NULL);
std::cerr << "Opening registry key: " << message << std::endl;
}
static const char *RegistryKey = "Software\\OpenVR-SpaceCalibrator";
static std::string ReadRegistryKey()
{
DWORD size = 0;
auto result = RegGetValueA(HKEY_CURRENT_USER_LOCAL_SETTINGS, RegistryKey, "Config", RRF_RT_REG_SZ, 0, 0, &size);
if (result != ERROR_SUCCESS)
{
LogRegistryResult(result);
return "";
}
std::string str;
str.resize(size);
result = RegGetValueA(HKEY_CURRENT_USER_LOCAL_SETTINGS, RegistryKey, "Config", RRF_RT_REG_SZ, 0, &str[0], &size);
if (result != ERROR_SUCCESS)
{
LogRegistryResult(result);
return "";
}
str.resize(size - 1);
return str;
}
static void WriteRegistryKey(std::string str)
{
HKEY hkey;
auto result = RegCreateKeyExA(HKEY_CURRENT_USER_LOCAL_SETTINGS, RegistryKey, 0, REG_NONE, 0, KEY_ALL_ACCESS, 0, &hkey, 0);
if (result != ERROR_SUCCESS)
{
LogRegistryResult(result);
return;
}
DWORD size = str.size() + 1;
result = RegSetValueExA(hkey, "Config", 0, REG_SZ, reinterpret_cast<const BYTE*>(str.c_str()), size);
if (result != ERROR_SUCCESS)
LogRegistryResult(result);
RegCloseKey(hkey);
}
void LoadProfile(CalibrationContext &ctx)
{
// @TODO: Rewrite this to migrate configs from the registry to the spacecal directory
// I don't know why whoever wrote this thought writing to the registry in the 2020s was a good idea...
// NOTE: HKEY_CURRENT_USER_LOCAL_SETTINGS evaluates to HKCU\Software\Classes\Local Settings
// Settings are currently stored at HKCU\Software\Classes\Local Settings\Software\OpenVR-SpaceCalibrator
ctx.validProfile = false;
auto str = ReadRegistryKey();
if (str == "")
{
std::cout << "Profile is empty" << std::endl;
ctx.Clear();
return;
}
try
{
std::stringstream io(str);
ParseProfile(ctx, io);
std::cout << "Loaded profile" << std::endl;
}
catch (const std::runtime_error &e)
{
std::cerr << "Error loading profile: " << e.what() << std::endl;
}
}
void SaveProfile(CalibrationContext &ctx)
{
std::cout << "Saving profile to registry" << std::endl;
std::stringstream io;
WriteProfile(ctx, io);
WriteRegistryKey(io.str());
}
+6
View File
@@ -0,0 +1,6 @@
#pragma once
#include "Calibration.h"
void LoadProfile(CalibrationContext &ctx);
void SaveProfile(CalibrationContext &ctx);
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
#pragma once
const unsigned int DroidSans_compressed_size = 134345;
extern const unsigned int DroidSans_compressed_data[134348 / 4];
+1
View File
@@ -0,0 +1 @@
#pragma once
+102
View File
@@ -0,0 +1,102 @@
#include "stdafx.h"
#include "IPCClient.h"
#include <string>
std::string WStringToString(const std::wstring& wstr)
{
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string str_to(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &str_to[0], size_needed, NULL, NULL);
return str_to;
}
static std::string LastErrorString(DWORD lastError)
{
LPWSTR buffer = nullptr;
size_t size = FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&buffer, 0, NULL
);
std::wstring message(buffer, size);
LocalFree(buffer);
return WStringToString(message);
}
IPCClient::~IPCClient()
{
if (pipe && pipe != INVALID_HANDLE_VALUE)
CloseHandle(pipe);
}
void IPCClient::Connect()
{
LPTSTR pipeName = TEXT(OPENVR_SPACECALIBRATOR_PIPE_NAME);
WaitNamedPipe(pipeName, 1000);
pipe = CreateFile(pipeName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if (pipe == INVALID_HANDLE_VALUE)
{
throw std::runtime_error("Space Calibrator driver unavailable. Make sure SteamVR is running, and the Space Calibrator addon is enabled in SteamVR settings.");
}
DWORD mode = PIPE_READMODE_MESSAGE;
if (!SetNamedPipeHandleState(pipe, &mode, 0, 0))
{
DWORD lastError = GetLastError();
throw std::runtime_error("Couldn't set pipe mode. Error " + std::to_string(lastError) + ": " + LastErrorString(lastError));
}
auto response = SendBlocking(protocol::Request(protocol::RequestHandshake));
if (response.type != protocol::ResponseHandshake || response.protocol.version != protocol::Version)
{
throw std::runtime_error(
"Incorrect driver version installed, try reinstalling OpenVR-SpaceCalibrator. (Client: " +
std::to_string(protocol::Version) +
", Driver: " +
std::to_string(response.protocol.version) +
")"
);
}
}
protocol::Response IPCClient::SendBlocking(const protocol::Request &request)
{
Send(request);
return Receive();
}
void IPCClient::Send(const protocol::Request &request)
{
DWORD bytesWritten;
BOOL success = WriteFile(pipe, &request, sizeof request, &bytesWritten, 0);
if (!success)
{
DWORD lastError = GetLastError();
throw std::runtime_error("Error writing IPC request. Error " + std::to_string(lastError) + ": " + LastErrorString(lastError));
}
}
protocol::Response IPCClient::Receive()
{
protocol::Response response(protocol::ResponseInvalid);
DWORD bytesRead;
BOOL success = ReadFile(pipe, &response, sizeof response, &bytesRead, 0);
if (!success)
{
DWORD lastError = GetLastError();
if (lastError != ERROR_MORE_DATA)
{
throw std::runtime_error("Error reading IPC response. Error " + std::to_string(lastError) + ": " + LastErrorString(lastError));
}
}
if (bytesRead != sizeof response)
{
throw std::runtime_error("Invalid IPC response. Error SIZE_MISMATCH, got size " + std::to_string(bytesRead));
}
return response;
}
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include "../Protocol.h"
class IPCClient
{
public:
~IPCClient();
void Connect();
protocol::Response SendBlocking(const protocol::Request &request);
void Send(const protocol::Request &request);
protocol::Response Receive();
private:
HANDLE pipe = INVALID_HANDLE_VALUE;
};
+1
View File
@@ -0,0 +1 @@
#pragma once
+521 -105
View File
@@ -1,20 +1,30 @@
#include "stdafx.h"
#include "OpenVR-SpaceCalibrator.h"
#include "stdafx.h"
#include "Calibration.h"
#include "Configuration.h"
#include "EmbeddedFiles.h"
#include "UserInterface.h"
#include <imgui/imgui.h>
#include <imgui/imgui_internal.h>
#include <imgui/imgui_impl_glfw.h>
#include <imgui/imgui_impl_opengl3.h>
#include <implot/implot.h>
#include <GL/gl3w.h>
#include <GLFW/glfw3.h>
#include <openvr.h>
#include <direct.h>
#include <chrono>
#include <thread>
#pragma comment(linker,"\"/manifestdependency:type='win32' \
name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \
processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#define MAX_LOADSTRING 100
#define OPENVR_APPLICATION_KEY "pushrax.SpaceCalibrator"
HINSTANCE hInst;
WCHAR szTitle[MAX_LOADSTRING];
WCHAR szWindowClass[MAX_LOADSTRING];
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
extern "C" __declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001;
void CreateConsole()
{
@@ -30,112 +40,518 @@ void CreateConsole()
}
}
//#define DEBUG_LOGS
void GLFWErrorCallback(int error, const char* description)
{
fprintf(stderr, "GLFW Error %d: %s\n", error, description);
}
void openGLDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam)
{
fprintf(stderr, "OpenGL Debug %u: %.*s\n", id, length, message);
}
static void HandleCommandLine(LPWSTR lpCmdLine);
static GLFWwindow *glfwWindow = nullptr;
static vr::VROverlayHandle_t overlayMainHandle = 0, overlayThumbnailHandle = 0;
static GLuint fboHandle = 0, fboTextureHandle = 0;
static int fboTextureWidth = 0, fboTextureHeight = 0;
static char cwd[MAX_PATH];
const float MINIMIZED_MAX_FPS = 60.0f;
void CreateGLFWWindow()
{
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, false);
#ifdef DEBUG_LOGS
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif
fboTextureWidth = 1200;
fboTextureHeight = 800;
glfwWindow = glfwCreateWindow(fboTextureWidth, fboTextureHeight, "OpenVR-SpaceCalibrator", NULL, NULL);
if (!glfwWindow)
throw std::runtime_error("Failed to create window");
glfwMakeContextCurrent(glfwWindow);
glfwSwapInterval(1);
gl3wInit();
glfwIconifyWindow(glfwWindow);
#ifdef DEBUG_LOGS
glDebugMessageCallback(openGLDebugCallback, nullptr);
glEnable(GL_DEBUG_OUTPUT);
#endif
ImGui::CreateContext();
ImPlot::CreateContext();
ImGuiIO &io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
io.IniFilename = nullptr;
io.Fonts->AddFontFromMemoryCompressedTTF(DroidSans_compressed_data, DroidSans_compressed_size, 24.0f);
ImGui_ImplGlfw_InitForOpenGL(glfwWindow, true);
ImGui_ImplOpenGL3_Init("#version 330");
ImGui::StyleColorsDark();
glGenTextures(1, &fboTextureHandle);
glBindTexture(GL_TEXTURE_2D, fboTextureHandle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, fboTextureWidth, fboTextureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glGenFramebuffers(1, &fboHandle);
glBindFramebuffer(GL_FRAMEBUFFER, fboHandle);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextureHandle, 0);
GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(1, drawBuffers);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
throw std::runtime_error("OpenGL framebuffer incomplete");
}
}
void TryCreateVROverlay()
{
if (overlayMainHandle || !vr::VROverlay())
return;
vr::VROverlayError error = vr::VROverlay()->CreateDashboardOverlay(
"pushrax.SpaceCalibrator", "Space Cal",
&overlayMainHandle, &overlayThumbnailHandle
);
if (error == vr::VROverlayError_KeyInUse)
{
throw std::runtime_error("Another instance of OpenVR Space Calibrator is already running");
}
else if (error != vr::VROverlayError_None)
{
throw std::runtime_error("Error creating VR overlay: " + std::string(vr::VROverlay()->GetOverlayErrorNameFromEnum(error)));
}
vr::VROverlay()->SetOverlayWidthInMeters(overlayMainHandle, 3.0f);
vr::VROverlay()->SetOverlayInputMethod(overlayMainHandle, vr::VROverlayInputMethod_Mouse);
vr::VROverlay()->SetOverlayFlag(overlayMainHandle, vr::VROverlayFlags_SendVRDiscreteScrollEvents, true);
std::string iconPath = cwd;
iconPath += "\\icon.png";
vr::VROverlay()->SetOverlayFromFile(overlayThumbnailHandle, iconPath.c_str());
}
void ActivateMultipleDrivers()
{
vr::EVRSettingsError vrSettingsError;
bool enabled = vr::VRSettings()->GetBool(vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_ActivateMultipleDrivers_Bool, &vrSettingsError);
if (vrSettingsError != vr::VRSettingsError_None)
{
std::string err = "Could not read \"" + std::string(vr::k_pch_SteamVR_ActivateMultipleDrivers_Bool) + "\" setting: "
+ vr::VRSettings()->GetSettingsErrorNameFromEnum(vrSettingsError);
throw std::runtime_error(err);
}
if (!enabled)
{
vr::VRSettings()->SetBool(vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_ActivateMultipleDrivers_Bool, true, &vrSettingsError);
if (vrSettingsError != vr::VRSettingsError_None)
{
std::string err = "Could not set \"" + std::string(vr::k_pch_SteamVR_ActivateMultipleDrivers_Bool) + "\" setting: "
+ vr::VRSettings()->GetSettingsErrorNameFromEnum(vrSettingsError);
throw std::runtime_error(err);
}
std::cerr << "Enabled \"" << vr::k_pch_SteamVR_ActivateMultipleDrivers_Bool << "\" setting" << std::endl;
}
else
{
std::cerr << "\"" << vr::k_pch_SteamVR_ActivateMultipleDrivers_Bool << "\" setting previously enabled" << std::endl;
}
}
void InitVR()
{
auto initError = vr::VRInitError_None;
vr::VR_Init(&initError, vr::VRApplication_Other);
if (initError != vr::VRInitError_None)
{
auto error = vr::VR_GetVRInitErrorAsEnglishDescription(initError);
throw std::runtime_error("OpenVR error:" + std::string(error));
}
if (!vr::VR_IsInterfaceVersionValid(vr::IVRSystem_Version))
{
throw std::runtime_error("OpenVR error: Outdated IVRSystem_Version");
}
else if (!vr::VR_IsInterfaceVersionValid(vr::IVRSettings_Version))
{
throw std::runtime_error("OpenVR error: Outdated IVRSettings_Version");
}
else if (!vr::VR_IsInterfaceVersionValid(vr::IVROverlay_Version))
{
throw std::runtime_error("OpenVR error: Outdated IVROverlay_Version");
}
ActivateMultipleDrivers();
}
static char textBuf[0x400];
static bool immediateRedraw;
void RequestImmediateRedraw() {
immediateRedraw = true;
}
double lastFrameStartTime = glfwGetTime();
void RunLoop()
{
while (!glfwWindowShouldClose(glfwWindow))
{
TryCreateVROverlay();
double time = glfwGetTime();
CalibrationTick(time);
bool dashboardVisible = false;
int width, height;
glfwGetFramebufferSize(glfwWindow, &width, &height);
const bool windowVisible = (width > 0 && height > 0);
if (overlayMainHandle && vr::VROverlay())
{
auto &io = ImGui::GetIO();
dashboardVisible = vr::VROverlay()->IsActiveDashboardOverlay(overlayMainHandle);
static bool keyboardOpen = false, keyboardJustClosed = false;
// After closing the keyboard, this code waits one frame for ImGui to pick up the new text from SetActiveText
// before clearing the active widget. Then it waits another frame before allowing the keyboard to open again,
// otherwise it will do so instantly since WantTextInput is still true on the second frame.
if (keyboardJustClosed && keyboardOpen)
{
ImGui::ClearActiveID();
keyboardOpen = false;
}
else if (keyboardJustClosed)
{
keyboardJustClosed = false;
}
else if (!io.WantTextInput)
{
// User might close the keyboard without hitting Done, so we unset the flag to allow it to open again.
keyboardOpen = false;
}
else if (io.WantTextInput && !keyboardOpen && !keyboardJustClosed)
{
int id = ImGui::GetActiveID();
auto textInfo = ImGui::GetInputTextState(id);
if (textInfo != nullptr) {
textBuf[0] = 0;
int len = WideCharToMultiByte(CP_ACP, 0, (LPCWCH)textInfo->TextW.Data, textInfo->TextW.Size, textBuf, sizeof(textBuf), NULL, NULL);
textBuf[min(len, sizeof(textBuf) - 1)] = 0;
uint32_t unFlags = 0; // EKeyboardFlags
vr::VROverlay()->ShowKeyboardForOverlay(
overlayMainHandle, vr::k_EGamepadTextInputModeNormal, vr::k_EGamepadTextInputLineModeSingleLine,
unFlags, "Space Calibrator Overlay", sizeof textBuf, textBuf, 0
);
keyboardOpen = true;
}
}
vr::VREvent_t vrEvent;
while (vr::VROverlay()->PollNextOverlayEvent(overlayMainHandle, &vrEvent, sizeof(vrEvent)))
{
switch (vrEvent.eventType) {
case vr::VREvent_MouseMove:
io.AddMousePosEvent(vrEvent.data.mouse.x, vrEvent.data.mouse.y);
break;
case vr::VREvent_MouseButtonDown:
io.AddMouseButtonEvent(vrEvent.data.mouse.button == vr::VRMouseButton_Left ? 0 : 1, true);
break;
case vr::VREvent_MouseButtonUp:
io.AddMouseButtonEvent(vrEvent.data.mouse.button == vr::VRMouseButton_Left ? 0 : 1, false);
break;
case vr::VREvent_ScrollDiscrete:
{
float x = vrEvent.data.scroll.xdelta * 360.0f * 8.0f;
float y = vrEvent.data.scroll.ydelta * 360.0f * 8.0f;
io.AddMouseWheelEvent(x, y);
break;
}
case vr::VREvent_KeyboardDone: {
vr::VROverlay()->GetKeyboardText(textBuf, sizeof textBuf);
int id = ImGui::GetActiveID();
auto textInfo = ImGui::GetInputTextState(id);
int bufSize = MultiByteToWideChar(CP_ACP, 0, textBuf, -1, NULL, 0);
textInfo->TextW.resize(bufSize);
MultiByteToWideChar(CP_ACP, 0, textBuf, -1, (LPWSTR)textInfo->TextW.Data, bufSize);
textInfo->CurLenW = bufSize;
textInfo->CurLenA = WideCharToMultiByte(CP_UTF8, 0, (LPCWCH)textInfo->TextW.Data, textInfo->TextW.Size, NULL, 0, NULL, NULL);
keyboardJustClosed = true;
break;
}
case vr::VREvent_Quit:
return;
}
}
}
if (windowVisible || dashboardVisible)
{
auto &io = ImGui::GetIO();
io.DisplaySize = ImVec2((float) fboTextureWidth, (float) fboTextureHeight);
io.DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
io.ConfigFlags = io.ConfigFlags & ~ImGuiConfigFlags_NoMouseCursorChange;
if (dashboardVisible) {
io.ConfigFlags = io.ConfigFlags | ImGuiConfigFlags_NoMouseCursorChange;
}
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
BuildMainWindow(dashboardVisible);
ImGui::Render();
glBindFramebuffer(GL_FRAMEBUFFER, fboHandle);
glViewport(0, 0, fboTextureWidth, fboTextureHeight);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glBindFramebuffer(GL_FRAMEBUFFER, 0);
if (width && height)
{
glBindFramebuffer(GL_READ_FRAMEBUFFER, fboHandle);
glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
glfwSwapBuffers(glfwWindow);
}
if (dashboardVisible)
{
vr::Texture_t vrTex;
vrTex.eType = vr::TextureType_OpenGL;
vrTex.eColorSpace = vr::ColorSpace_Auto;
vrTex.handle = (void *)
#if defined _WIN64 || defined _LP64
(uint64_t)
#endif
fboTextureHandle;
vr::HmdVector2_t mouseScale = { (float) fboTextureWidth, (float) fboTextureHeight };
vr::VROverlay()->SetOverlayTexture(overlayMainHandle, &vrTex);
vr::VROverlay()->SetOverlayMouseScale(overlayMainHandle, &mouseScale);
}
}
const double dashboardInterval = 1.0 / 90.0; // fps
double waitEventsTimeout = max(CalCtx.wantedUpdateInterval, dashboardInterval);
if (dashboardVisible && waitEventsTimeout > dashboardInterval)
waitEventsTimeout = dashboardInterval;
if (immediateRedraw) {
waitEventsTimeout = 0;
immediateRedraw = false;
}
glfwWaitEventsTimeout(waitEventsTimeout);
// If we're minimized rendering won't limit our frame rate so we need to do it ourselves.
if (glfwGetWindowAttrib(glfwWindow, GLFW_ICONIFIED))
{
double targetFrameTime = 1 / MINIMIZED_MAX_FPS;
double waitTime = targetFrameTime - (glfwGetTime() - lastFrameStartTime);
if (waitTime > 0)
{
std::this_thread::sleep_for(std::chrono::duration<double>(waitTime));
}
lastFrameStartTime += targetFrameTime;
}
}
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
_getcwd(cwd, MAX_PATH);
HandleCommandLine(lpCmdLine);
if (!InitVR())
return FALSE;
#ifdef DEBUG_LOGS
CreateConsole();
#endif
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_OPENVRSPACECALIBRATOR, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
if (!InitInstance(hInstance, nCmdShow))
return FALSE;
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_OPENVRSPACECALIBRATOR));
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0))
if (!glfwInit())
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
MessageBox(nullptr, L"Failed to initialize GLFW", L"", 0);
return 0;
}
return (int)msg.wParam;
}
glfwSetErrorCallback(GLFWErrorCallback);
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
try {
InitVR();
CreateGLFWWindow();
InitCalibrator();
LoadProfile(CalCtx);
RunLoop();
wcex.cbSize = sizeof(WNDCLASSEX);
vr::VR_Shutdown();
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_OPENVRSPACECALIBRATOR));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_OPENVRSPACECALIBRATOR);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
if (fboHandle)
glDeleteFramebuffers(1, &fboHandle);
return RegisterClassExW(&wcex);
}
if (fboTextureHandle)
glDeleteTextures(1, &fboTextureHandle);
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance;
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT, 300, 200, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
return FALSE;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
SetTimer(hWnd, 1337, 50, nullptr);
return TRUE;
}
#define CAL_BTN_ID 1001
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HFONT hFont;
HWND button;
switch (message)
{
case WM_CREATE:
button = CreateWindow(L"button", L"Start Calibration", WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON,
40, 30, 200, 100, hWnd, (HMENU)CAL_BTN_ID, hInst, NULL);
hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
SendMessage(button, WM_SETFONT, (WPARAM)hFont, true);
break;
case WM_TIMER:
CalibrationTick();
break;
case WM_COMMAND:
if (wParam == CAL_BTN_ID)
{
CreateConsole();
StartCalibration();
}
return DefWindowProc(hWnd, message, wParam, lParam);
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImPlot::DestroyContext();
ImGui::DestroyContext();
}
catch (std::runtime_error &e)
{
std::cerr << "Runtime error: " << e.what() << std::endl;
wchar_t message[1024];
swprintf(message, 1024, L"%hs", e.what());
MessageBox(nullptr, message, L"Runtime Error", 0);
}
if (glfwWindow)
glfwDestroyWindow(glfwWindow);
glfwTerminate();
return 0;
}
}
static void HandleCommandLine(LPWSTR lpCmdLine)
{
if (lstrcmp(lpCmdLine, L"-openvrpath") == 0)
{
auto vrErr = vr::VRInitError_None;
vr::VR_Init(&vrErr, vr::VRApplication_Utility);
if (vrErr == vr::VRInitError_None)
{
char cruntimePath[MAX_PATH] = { 0 };
unsigned int pathLen;
vr::VR_GetRuntimePath(cruntimePath, MAX_PATH, &pathLen);
printf("%s", cruntimePath);
vr::VR_Shutdown();
exit(0);
}
fprintf(stderr, "Failed to initialize OpenVR: %s\n", vr::VR_GetVRInitErrorAsEnglishDescription(vrErr));
vr::VR_Shutdown();
exit(-2);
}
else if (lstrcmp(lpCmdLine, L"-installmanifest") == 0)
{
auto vrErr = vr::VRInitError_None;
vr::VR_Init(&vrErr, vr::VRApplication_Utility);
if (vrErr == vr::VRInitError_None)
{
if (vr::VRApplications()->IsApplicationInstalled(OPENVR_APPLICATION_KEY))
{
char oldWd[MAX_PATH] = { 0 };
auto vrAppErr = vr::VRApplicationError_None;
vr::VRApplications()->GetApplicationPropertyString(OPENVR_APPLICATION_KEY, vr::VRApplicationProperty_WorkingDirectory_String, oldWd, MAX_PATH, &vrAppErr);
if (vrAppErr != vr::VRApplicationError_None)
{
fprintf(stderr, "Failed to get old working dir, skipping removal: %s\n", vr::VRApplications()->GetApplicationsErrorNameFromEnum(vrAppErr));
}
else
{
std::string manifestPath = oldWd;
manifestPath += "\\manifest.vrmanifest";
std::cout << "Removing old manifest path: " << manifestPath << std::endl;
vr::VRApplications()->RemoveApplicationManifest(manifestPath.c_str());
}
}
std::string manifestPath = cwd;
manifestPath += "\\manifest.vrmanifest";
std::cout << "Adding manifest path: " << manifestPath << std::endl;
auto vrAppErr = vr::VRApplications()->AddApplicationManifest(manifestPath.c_str());
if (vrAppErr != vr::VRApplicationError_None)
{
fprintf(stderr, "Failed to add manifest: %s\n", vr::VRApplications()->GetApplicationsErrorNameFromEnum(vrAppErr));
}
else
{
vr::VRApplications()->SetApplicationAutoLaunch(OPENVR_APPLICATION_KEY, true);
}
vr::VR_Shutdown();
exit(-2);
}
fprintf(stderr, "Failed to initialize OpenVR: %s\n", vr::VR_GetVRInitErrorAsEnglishDescription(vrErr));
vr::VR_Shutdown();
exit(-2);
}
else if (lstrcmp(lpCmdLine, L"-removemanifest") == 0)
{
auto vrErr = vr::VRInitError_None;
vr::VR_Init(&vrErr, vr::VRApplication_Utility);
if (vrErr == vr::VRInitError_None)
{
if (vr::VRApplications()->IsApplicationInstalled(OPENVR_APPLICATION_KEY))
{
std::string manifestPath = cwd;
manifestPath += "\\manifest.vrmanifest";
std::cout << "Removing manifest path: " << manifestPath << std::endl;
vr::VRApplications()->RemoveApplicationManifest(manifestPath.c_str());
}
vr::VR_Shutdown();
exit(0);
}
fprintf(stderr, "Failed to initialize OpenVR: %s\n", vr::VR_GetVRInitErrorAsEnglishDescription(vrErr));
vr::VR_Shutdown();
exit(-2);
}
else if (lstrcmp(lpCmdLine, L"-activatemultipledrivers") == 0)
{
int ret = -2;
auto vrErr = vr::VRInitError_None;
vr::VR_Init(&vrErr, vr::VRApplication_Utility);
if (vrErr == vr::VRInitError_None)
{
try
{
ActivateMultipleDrivers();
ret = 0;
}
catch (std::runtime_error &e)
{
std::cerr << e.what() << std::endl;
}
}
else
{
fprintf(stderr, "Failed to initialize OpenVR: %s\n", vr::VR_GetVRInitErrorAsEnglishDescription(vrErr));
}
vr::VR_Shutdown();
exit(ret);
}
}
@@ -1,3 +0,0 @@
#pragma once
#include "resource.h"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 70 KiB

@@ -1,14 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
@@ -22,32 +14,19 @@
<ProjectGuid>{63BAE169-D595-4464-8E7E-50D6FD379348}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>OpenVRSpaceCalibrator</RootNamespace>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
@@ -56,12 +35,6 @@
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
@@ -69,127 +42,112 @@
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>..\lib\openvr;..\lib\boost_1_63_0;..\lib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>..\lib\openvr\openvr_api.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\lib\boost_1_63_0</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_SCL_SECURE_NO_WARNINGS;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>..\lib\openvr;..\lib\boost_1_63_0;..\lib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>..\lib\imgui;..\lib\gl3w\include;..\lib\glfw\include;..\lib\openvr;..\lib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>..\lib\boost_1_63_0\lib64-msvc-14.0;..\lib\openvr\lib\win64</AdditionalLibraryDirectories>
<AdditionalDependencies>openvr_api.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>..\lib\openvr;..\lib\boost_1_63_0;..\lib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>..\lib\openvr\openvr_api.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\lib\boost_1_63_0</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories>..\lib\glfw\lib-vc2015;..\lib\openvr\lib\win64</AdditionalLibraryDirectories>
<AdditionalDependencies>opengl32.lib;glfw3.lib;openvr_api.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>_SCL_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>..\lib\openvr;..\lib\boost_1_63_0;..\lib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>..\lib\imgui;..\lib\gl3w\include;..\lib\glfw\include;..\lib\openvr;..\lib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>..\lib\boost_1_63_0\lib64-msvc-14.0;..\lib\openvr\lib\win64</AdditionalLibraryDirectories>
<AdditionalDependencies>openvr_api.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\lib\glfw\lib-vc2015;..\lib\openvr\lib\win64</AdditionalLibraryDirectories>
<AdditionalDependencies>opengl32.lib;glfw3.lib;openvr_api.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\lib\lib_vrinputemulator\ipc_protocol.h" />
<ClInclude Include="..\lib\lib_vrinputemulator\vrinputemulator.h" />
<ClInclude Include="..\lib\lib_vrinputemulator\vrinputemulator_types.h" />
<ClInclude Include="..\lib\implot\implot.h" />
<ClInclude Include="..\lib\implot\implot_internal.h" />
<ClInclude Include="..\Version.h" />
<ClInclude Include="Calibration.h" />
<ClInclude Include="OpenVR-SpaceCalibrator.h" />
<ClInclude Include="Resource.h" />
<ClInclude Include="CalibrationCalc.h" />
<ClInclude Include="CalibrationMetrics.h" />
<ClInclude Include="Configuration.h" />
<ClInclude Include="EmbeddedFiles.h" />
<ClInclude Include="imgui_extensions.h" />
<ClInclude Include="IPCClient.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
<ClInclude Include="UserInterface.h" />
<ClInclude Include="VRState.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\lib\lib_vrinputemulator\vrinputemulator.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
<ClCompile Include="..\lib\gl3w\src\gl3w.c">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="..\lib\imgui\imgui.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="..\lib\imgui\imgui_demo.cpp" />
<ClCompile Include="..\lib\imgui\imgui_draw.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="..\lib\imgui\imgui_impl_glfw.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="..\lib\imgui\imgui_impl_opengl3.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="..\lib\imgui\imgui_tables.cpp" />
<ClCompile Include="..\lib\imgui\imgui_widgets.cpp" />
<ClCompile Include="..\lib\implot\implot.cpp" />
<ClCompile Include="..\lib\implot\implot_demo.cpp" />
<ClCompile Include="..\lib\implot\implot_items.cpp" />
<ClCompile Include="Calibration.cpp" />
<ClCompile Include="CalibrationCalc.cpp" />
<ClCompile Include="CalibrationDebug.cpp" />
<ClCompile Include="CalibrationMetrics.cpp" />
<ClCompile Include="Configuration.cpp" />
<ClCompile Include="EmbeddedFiles.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="imgui_extensions.cpp" />
<ClCompile Include="IPCClient.cpp" />
<ClCompile Include="OpenVR-SpaceCalibrator.cpp" />
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\lib;..\lib\openvr;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="OpenVR-SpaceCalibrator.rc" />
<ClCompile Include="UserInterface.cpp" />
<ClCompile Include="VRState.cpp" />
</ItemGroup>
<ItemGroup>
<Image Include="OpenVR-SpaceCalibrator.ico" />
<Image Include="small.ico" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="OpenVR-SpaceCalibrator.rc" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
@@ -13,9 +13,15 @@
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
<Filter Include="Source Files\ImGui">
<UniqueIdentifier>{948e4c13-6f2b-44e3-a8b7-1a12c79aeeb7}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\GL">
<UniqueIdentifier>{d156ae5c-9fe6-41f0-a34e-333dc7a6b2f8}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\ImGui\ImPlot">
<UniqueIdentifier>{7334a0fc-18cd-446d-b621-6dadb942fe6f}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdafx.h">
@@ -24,22 +30,40 @@
<ClInclude Include="targetver.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Resource.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="OpenVR-SpaceCalibrator.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Calibration.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\lib\lib_vrinputemulator\ipc_protocol.h">
<ClInclude Include="EmbeddedFiles.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\lib\lib_vrinputemulator\vrinputemulator.h">
<ClInclude Include="UserInterface.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\lib\lib_vrinputemulator\vrinputemulator_types.h">
<ClInclude Include="Configuration.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="IPCClient.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Version.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="CalibrationCalc.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\lib\implot\implot.h">
<Filter>Source Files\ImGui\ImPlot</Filter>
</ClInclude>
<ClInclude Include="..\lib\implot\implot_internal.h">
<Filter>Source Files\ImGui\ImPlot</Filter>
</ClInclude>
<ClInclude Include="VRState.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="CalibrationMetrics.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="imgui_extensions.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
@@ -47,20 +71,72 @@
<ClCompile Include="stdafx.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="OpenVR-SpaceCalibrator.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Calibration.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\lib\lib_vrinputemulator\vrinputemulator.cpp">
<ClCompile Include="..\lib\imgui\imgui.cpp">
<Filter>Source Files\ImGui</Filter>
</ClCompile>
<ClCompile Include="..\lib\imgui\imgui_impl_glfw.cpp">
<Filter>Source Files\ImGui</Filter>
</ClCompile>
<ClCompile Include="..\lib\imgui\imgui_impl_opengl3.cpp">
<Filter>Source Files\ImGui</Filter>
</ClCompile>
<ClCompile Include="..\lib\gl3w\src\gl3w.c">
<Filter>Source Files\GL</Filter>
</ClCompile>
<ClCompile Include="..\lib\imgui\imgui_draw.cpp">
<Filter>Source Files\ImGui</Filter>
</ClCompile>
<ClCompile Include="EmbeddedFiles.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="UserInterface.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Configuration.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="IPCClient.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="OpenVR-SpaceCalibrator.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="CalibrationCalc.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\lib\imgui\imgui_tables.cpp">
<Filter>Source Files\ImGui</Filter>
</ClCompile>
<ClCompile Include="..\lib\imgui\imgui_widgets.cpp">
<Filter>Source Files\ImGui</Filter>
</ClCompile>
<ClCompile Include="..\lib\implot\implot.cpp">
<Filter>Source Files\ImGui\ImPlot</Filter>
</ClCompile>
<ClCompile Include="..\lib\implot\implot_demo.cpp">
<Filter>Source Files\ImGui\ImPlot</Filter>
</ClCompile>
<ClCompile Include="..\lib\implot\implot_items.cpp">
<Filter>Source Files\ImGui\ImPlot</Filter>
</ClCompile>
<ClCompile Include="..\lib\imgui\imgui_demo.cpp">
<Filter>Source Files\ImGui</Filter>
</ClCompile>
<ClCompile Include="CalibrationDebug.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="VRState.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="CalibrationMetrics.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="imgui_extensions.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="OpenVR-SpaceCalibrator.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
<Image Include="small.ico">
@@ -70,4 +146,9 @@
<Filter>Resource Files</Filter>
</Image>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="OpenVR-SpaceCalibrator.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
</Project>
+903
View File
@@ -0,0 +1,903 @@
#include "stdafx.h"
#include "UserInterface.h"
#include "Calibration.h"
#include "Configuration.h"
#include "VRState.h"
#include "CalibrationMetrics.h"
#include "../Version.h"
#include <thread>
#include <string>
#include <vector>
#include <algorithm>
#include <imgui/imgui.h>
#include "imgui_extensions.h"
void TextWithWidth(const char *label, const char *text, float width);
VRState LoadVRState();
void BuildSystemSelection(const VRState &state);
void BuildDeviceSelections(const VRState &state);
void BuildProfileEditor();
void BuildMenu(bool runningInOverlay);
static const ImGuiWindowFlags bareWindowFlags =
ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoScrollbar |
ImGuiWindowFlags_NoScrollWithMouse |
ImGuiWindowFlags_NoCollapse;
void BuildContinuousCalDisplay();
void ShowVersionLine();
static bool runningInOverlay;
void BuildMainWindow(bool runningInOverlay_)
{
runningInOverlay = runningInOverlay_;
bool continuousCalibration = CalCtx.state == CalibrationState::Continuous || CalCtx.state == CalibrationState::ContinuousStandby;
auto &io = ImGui::GetIO();
ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f), ImGuiCond_Always);
ImGui::SetNextWindowSize(io.DisplaySize, ImGuiCond_Always);
if (!ImGui::Begin("OpenVRSpaceCalibrator", nullptr, bareWindowFlags))
{
ImGui::End();
return;
}
ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImGui::GetStyleColorVec4(ImGuiCol_Button));
if (continuousCalibration) {
BuildContinuousCalDisplay();
}
else {
auto state = LoadVRState();
ImGui::BeginDisabled(CalCtx.state == CalibrationState::Continuous);
BuildSystemSelection(state);
BuildDeviceSelections(state);
ImGui::EndDisabled();
BuildMenu(runningInOverlay);
}
ShowVersionLine();
ImGui::PopStyleColor();
ImGui::End();
}
void ShowVersionLine() {
ImGui::SetNextWindowPos(ImVec2(10.0f, ImGui::GetWindowHeight() - ImGui::GetFrameHeightWithSpacing()));
if (!ImGui::BeginChild("bottom line", ImVec2(ImGui::GetWindowWidth() - 20.0f, ImGui::GetFrameHeightWithSpacing() * 2), false)) {
ImGui::EndChild();
return;
}
ImGui::Text("OpenVR Space Calibrator v" SPACECAL_VERSION_STRING);
if (runningInOverlay)
{
ImGui::SameLine();
ImGui::Text("- close VR overlay to use mouse");
}
ImGui::EndChild();
}
void CCal_BasicInfo();
void CCal_DrawSettings();
void BuildContinuousCalDisplay() {
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(ImGui::GetWindowSize());
ImGui::SetNextWindowBgAlpha(1);
if (!ImGui::Begin("Continuous Calibration", nullptr,
bareWindowFlags & ~ImGuiWindowFlags_NoTitleBar
)) {
ImGui::End();
return;
}
ImVec2 contentRegion;
contentRegion.x = ImGui::GetWindowContentRegionWidth();
contentRegion.y = ImGui::GetWindowHeight() - ImGui::GetFrameHeightWithSpacing() * 2.1;
if (!ImGui::BeginChild("CCalDisplayFrame", contentRegion, false)) {
ImGui::EndChild();
return;
}
if (ImGui::BeginTabBar("CCalTabs", 0)) {
if (ImGui::BeginTabItem("Status")) {
CCal_BasicInfo();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("More Graphs")) {
ShowCalibrationDebug(2, 3);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Settings")) {
CCal_DrawSettings();
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::EndChild();
ShowVersionLine();
ImGui::End();
}
static void ScaledDragFloat(const char* label, double& f, double scale, double min, double max, int flags = ImGuiSliderFlags_AlwaysClamp) {
float v = (float) (f * scale);
std::string labelStr = std::string(label);
// If starts with ##, just do a normal SliderFloat
if (labelStr.size() > 2 && labelStr[0] == '#' && labelStr[1] == '#') {
ImGui::SliderFloat(label, &v, (float)min, (float)max, "%1.2f", flags);
} else {
// Otherwise do funny
ImGui::Text(label);
ImGui::SameLine();
ImGui::PushID((std::string(label) + "_id").c_str());
// Line up to a column, multiples of 100
constexpr uint32_t LABEL_CURSOR = 100;
uint32_t cursorPosX = ImGui::GetCursorPosX();
uint32_t roundedPosition = ((cursorPosX + LABEL_CURSOR / 2) / LABEL_CURSOR) * LABEL_CURSOR;
ImGui::SetCursorPosX(roundedPosition);
ImGui::SliderFloat((std::string("##") + label).c_str(), &v, (float)min, (float)max, "%1.2f", flags);
ImGui::PopID();
}
f = v / scale;
}
void DrawVectorElement(std::string id, const char* text, double* value);
void CCal_DrawSettings() {
// panel size for boxes
ImVec2 panel_size { ImGui::GetWindowContentRegionMax().x - ImGui::GetWindowContentRegionMin().x, 0 };
ImGui::BeginGroupPanel("Tip", panel_size);
ImGui::Text("Hover over settings to learn more about them!");
ImGui::EndGroupPanel();
// @TODO: Group in UI
// Section: Alignment speeds
{
ImGui::BeginGroupPanel("Calibration speeds", panel_size);
ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
ImGui::TextWrapped(
"SpaceCalibrator uses up to three different speeds at which it drags the calibration back into "
"position when drift occurs. These settings control how far off the calibration should be before going back to low speed (for "
"Decel) or going to higher speeds (for Slow and Fast)."
);
ImGui::PopStyleColor();
if (ImGui::BeginTable("SpeedThresholds", 3, 0)) {
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(1);
ImGui::Text("Translation (mm)");
ImGui::TableSetColumnIndex(2);
ImGui::Text("Rotation (degrees)");
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
ImGui::Text("Decel");
ImGui::TableSetColumnIndex(1);
ScaledDragFloat("##TransDecel", CalCtx.alignmentSpeedParams.thr_trans_tiny, 1000.0, 0, 20.0);
ImGui::TableSetColumnIndex(2);
ScaledDragFloat("##RotDecel", CalCtx.alignmentSpeedParams.thr_rot_tiny, 180.0 / EIGEN_PI, 0, 5.0);
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
ImGui::Text("Slow");
ImGui::TableSetColumnIndex(1);
ScaledDragFloat("##TransSlow", CalCtx.alignmentSpeedParams.thr_trans_small, 1000.0,
CalCtx.alignmentSpeedParams.thr_trans_tiny * 1000.0, 20.0);
ImGui::TableSetColumnIndex(2);
ScaledDragFloat("##RotSlow", CalCtx.alignmentSpeedParams.thr_rot_small, 180.0 / EIGEN_PI,
CalCtx.alignmentSpeedParams.thr_rot_tiny * (180.0 / EIGEN_PI), 10.0);
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
ImGui::Text("Fast");
ImGui::TableSetColumnIndex(1);
ScaledDragFloat("##TransFast", CalCtx.alignmentSpeedParams.thr_trans_large, 1000.0,
CalCtx.alignmentSpeedParams.thr_trans_small * 1000.0, 50.0);
ImGui::TableSetColumnIndex(2);
ScaledDragFloat("##RotFast", CalCtx.alignmentSpeedParams.thr_rot_large, 180.0 / EIGEN_PI,
CalCtx.alignmentSpeedParams.thr_rot_small * (180.0 / EIGEN_PI), 20.0);
ImGui::EndTable();
}
ImGui::EndGroupPanel();
}
// Section: Alignment speeds
{
ImGui::BeginGroupPanel("Alignment speeds", panel_size);
// ImGui::Separator();
// ImGui::Text("Alignment speeds");
ScaledDragFloat("Decel", CalCtx.alignmentSpeedParams.align_speed_tiny, 1.0, 0, 2.0, 0);
ScaledDragFloat("Slow", CalCtx.alignmentSpeedParams.align_speed_small, 1.0, 0, 2.0, 0);
ScaledDragFloat("Fast", CalCtx.alignmentSpeedParams.align_speed_large, 1.0, 0, 2.0, 0);
ImGui::EndGroupPanel();
}
// Section: Continuous Calibration settings
{
ImGui::BeginGroupPanel("Continuous calibration", panel_size);
{
// @TODO: Reduce code duplication (tooltips)
// Recalibration threshold
ImGui::Text("Recalibration threshold");
ImGui::SameLine();
ImGui::PushID("recalibration_threshold");
ImGui::SliderFloat("##recalibration_threshold_slider", &CalCtx.continuousCalibrationThreshold, 1.01f, 10.0f, "%1.1f", 0);
if (ImGui::IsItemHovered(0)) {
ImGui::SetTooltip("Controls how good the calibration must be before realigning the trackers.\n"
"Higher values cause calibration to happen less often, and may be useful for system with lots of tracking drift.");
}
ImGui::PopID();
ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
ImGui::TextWrapped("Controls how often SpaceCalibrator synchronises playspaces.");
ImGui::PopStyleColor();
if (ImGui::IsItemHovered(0)) {
ImGui::SetTooltip("Controls how good the calibration must be before realigning the trackers.\n"
"Higher values cause calibration to happen less often, and may be useful for system with lots of tracking drift.");
}
}
{
// Tracker offset
// ImVec2 panel_size_inner { ImGui::GetCurrentWindow()->DC.ItemWidth, 0};
ImVec2 panel_size_inner { panel_size.x - 11 * 2, 0};
ImGui::BeginGroupPanel("Tracker offset", panel_size_inner);
DrawVectorElement("cc_tracker_offset", "X", &CalCtx.continuousCalibrationOffset.x());
DrawVectorElement("cc_tracker_offset", "Y", &CalCtx.continuousCalibrationOffset.y());
DrawVectorElement("cc_tracker_offset", "Z", &CalCtx.continuousCalibrationOffset.z());
ImGui::EndGroupPanel();
}
{
// Playspace offset
ImVec2 panel_size_inner{ panel_size.x - 11 * 2, 0 };
ImGui::BeginGroupPanel("Playspace scale", panel_size_inner);
DrawVectorElement("cc_playspace_scale", "PLayspace Scale", &CalCtx.calibratedScale);
ImGui::EndGroupPanel();
}
ImGui::EndGroupPanel();
}
ImGui::NewLine();
ImGui::Indent();
if (ImGui::Button("Reset settings")) {
CalCtx.ResetConfig();
}
ImGui::Unindent();
ImGui::NewLine();
// Section: Contributors credits
{
ImGui::BeginGroupPanel("Credits", panel_size);
ImGui::TextDisabled("tach");
ImGui::TextDisabled("pushrax");
ImGui::TextDisabled("bd_");
ImGui::TextDisabled("ArcticFox");
ImGui::TextDisabled("hekky");
ImGui::EndGroupPanel();
}
}
void DrawVectorElement(std::string id, const char* text, double* value) {
constexpr float CONTINUOUS_CALIBRATION_TRACKER_OFFSET_DELTA = 0.01f;
ImGui::Text(text);
ImGui::SameLine();
ImGui::PushID((id + text + "_btn_reset").c_str());
if (ImGui::Button(" 0 ")) {
*value *= 0;
}
ImGui::PopID();
ImGui::SameLine();
if (ImGui::ArrowButton((id + text + "_decrease").c_str(), ImGuiDir_Down)) {
*value -= CONTINUOUS_CALIBRATION_TRACKER_OFFSET_DELTA;
}
ImGui::SameLine();
ImGui::PushItemWidth(100);
ImGui::PushID((id + text + "_text_field").c_str());
ImGui::InputDouble("##label", value, 0, 0, "%.2f");
ImGui::PopID();
ImGui::PopItemWidth();
ImGui::SameLine();
if (ImGui::ArrowButton((id + text + "_increase").c_str(), ImGuiDir_Up)) {
*value += CONTINUOUS_CALIBRATION_TRACKER_OFFSET_DELTA;
}
}
void CCal_BasicInfo() {
if (ImGui::BeginTable("DeviceInfo", 2, 0)) {
ImGui::TableSetupColumn("Reference device");
ImGui::TableSetupColumn("Target device");
ImGui::TableHeadersRow();
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
ImGui::BeginGroup();
ImGui::Text("%s / %s / %s",
CalCtx.referenceStandby.trackingSystem.c_str(),
CalCtx.referenceStandby.model.c_str(),
CalCtx.referenceStandby.serial.c_str()
);
const char* status;
if (CalCtx.referenceID < 0) {
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, 0xFF000080);
status = "NOT FOUND";
}
else if (!CalCtx.ReferencePoseIsValid()) {
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, 0xFFFF0080);
status = "NOT TRACKING";
}
else {
status = "OK";
}
ImGui::Text("Status: %s", status);
ImGui::EndGroup();
ImGui::TableSetColumnIndex(1);
ImGui::BeginGroup();
ImGui::Text("%s / %s / %s",
CalCtx.targetStandby.trackingSystem.c_str(),
CalCtx.targetStandby.model.c_str(),
CalCtx.targetStandby.serial.c_str()
);
if (CalCtx.targetID < 0) {
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, 0xFF000080);
status = "NOT FOUND";
}
else if (!CalCtx.TargetPoseIsValid()) {
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, 0xFFFF0080);
status = "NOT TRACKING";
}
else {
status = "OK";
}
ImGui::Text("Status: %s", status);
ImGui::EndGroup();
ImGui::EndTable();
}
float width = ImGui::GetWindowContentRegionWidth(), scale = 1.0f;
if (ImGui::BeginTable("##CCal_Cancel", Metrics::enableLogs ? 3 : 2, 0, ImVec2(width * scale, ImGui::GetTextLineHeight() * 2))) {
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
if (ImGui::Button("Cancel Continuous Calibration", ImVec2(-FLT_MIN, 0.0f))) {
EndContinuousCalibration();
}
ImGui::TableSetColumnIndex(1);
if (ImGui::Button("Debug: Force break calibration", ImVec2(-FLT_MIN, 0.0f))) {
DebugApplyRandomOffset();
}
if (Metrics::enableLogs) {
ImGui::TableSetColumnIndex(2);
if (ImGui::Button("Debug: Mark logs", ImVec2(-FLT_MIN, 0.0f))) {
Metrics::WriteLogAnnotation("MARK LOGS");
}
}
ImGui::EndTable();
}
ImGui::Checkbox("Hide tracker", &CalCtx.quashTargetInContinuous);
ImGui::SameLine();
ImGui::Checkbox("Static recalibration", &CalCtx.enableStaticRecalibration);
ImGui::SameLine();
ImGui::Checkbox("Enable debug logs", &Metrics::enableLogs);
ImGui::SameLine();
ImGui::Checkbox("Lock relative transform", &CalCtx.lockRelativePosition);
ImGui::SameLine();
ImGui::Checkbox("Require triggers", &CalCtx.requireTriggerPressToApply);
// Status field...
ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0, 0, 0, 1));
for (const auto& msg : CalCtx.messages) {
if (msg.type == CalibrationContext::Message::String) {
ImGui::TextWrapped("> %s", msg.str.c_str());
}
}
ImGui::PopStyleColor();
ShowCalibrationDebug(1, 3);
}
void BuildMenu(bool runningInOverlay)
{
auto &io = ImGui::GetIO();
ImGuiStyle &style = ImGui::GetStyle();
ImGui::Text("");
if (CalCtx.state == CalibrationState::None)
{
if (CalCtx.validProfile && !CalCtx.enabled)
{
ImGui::TextColored(ImVec4(0.8f, 0.2f, 0.2f, 1), "Reference (%s) HMD not detected, profile disabled", CalCtx.referenceTrackingSystem.c_str());
ImGui::Text("");
}
float width = ImGui::GetWindowContentRegionWidth(), scale = 1.0f;
if (CalCtx.validProfile)
{
width -= style.FramePadding.x * 4.0f;
scale = 1.0f / 4.0f;
}
if (ImGui::Button("Start Calibration", ImVec2(width * scale, ImGui::GetTextLineHeight() * 2)))
{
ImGui::OpenPopup("Calibration Progress");
StartCalibration();
}
ImGui::SameLine();
if (ImGui::Button("Continuous Calibration", ImVec2(width * scale, ImGui::GetTextLineHeight() * 2))) {
StartContinuousCalibration();
}
if (CalCtx.validProfile)
{
ImGui::SameLine();
if (ImGui::Button("Edit Calibration", ImVec2(width * scale, ImGui::GetTextLineHeight() * 2)))
{
CalCtx.state = CalibrationState::Editing;
}
ImGui::SameLine();
if (ImGui::Button("Clear Calibration", ImVec2(width * scale, ImGui::GetTextLineHeight() * 2)))
{
CalCtx.Clear();
SaveProfile(CalCtx);
}
}
width = ImGui::GetWindowContentRegionWidth();
scale = 1.0f;
if (CalCtx.chaperone.valid)
{
width -= style.FramePadding.x * 2.0f;
scale = 0.5;
}
ImGui::Text("");
if (ImGui::Button("Copy Chaperone Bounds to profile", ImVec2(width * scale, ImGui::GetTextLineHeight() * 2)))
{
LoadChaperoneBounds();
SaveProfile(CalCtx);
}
if (CalCtx.chaperone.valid)
{
ImGui::SameLine();
if (ImGui::Button("Paste Chaperone Bounds", ImVec2(width * scale, ImGui::GetTextLineHeight() * 2)))
{
ApplyChaperoneBounds();
}
if (ImGui::Checkbox(" Paste Chaperone Bounds automatically when geometry resets", &CalCtx.chaperone.autoApply))
{
SaveProfile(CalCtx);
}
}
ImGui::Text("");
auto speed = CalCtx.calibrationSpeed;
ImGui::Columns(4, NULL, false);
ImGui::Text("Calibration Speed");
ImGui::NextColumn();
if (ImGui::RadioButton(" Fast ", speed == CalibrationContext::FAST))
CalCtx.calibrationSpeed = CalibrationContext::FAST;
ImGui::NextColumn();
if (ImGui::RadioButton(" Slow ", speed == CalibrationContext::SLOW))
CalCtx.calibrationSpeed = CalibrationContext::SLOW;
ImGui::NextColumn();
if (ImGui::RadioButton(" Very Slow ", speed == CalibrationContext::VERY_SLOW))
CalCtx.calibrationSpeed = CalibrationContext::VERY_SLOW;
ImGui::Columns(1);
}
else if (CalCtx.state == CalibrationState::Editing)
{
BuildProfileEditor();
if (ImGui::Button("Save Profile", ImVec2(ImGui::GetWindowContentRegionWidth(), ImGui::GetTextLineHeight() * 2)))
{
SaveProfile(CalCtx);
CalCtx.state = CalibrationState::None;
}
}
else
{
ImGui::Button("Calibration in progress...", ImVec2(ImGui::GetWindowContentRegionWidth(), ImGui::GetTextLineHeight() * 2));
}
ImGui::SetNextWindowPos(ImVec2(20.0f, 20.0f), ImGuiCond_Always);
ImGui::SetNextWindowSize(ImVec2(io.DisplaySize.x - 40.0f, io.DisplaySize.y - 40.0f), ImGuiCond_Always);
if (ImGui::BeginPopupModal("Calibration Progress", nullptr, bareWindowFlags))
{
ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImVec4(0, 0, 0, 1));
for (auto &message : CalCtx.messages)
{
switch (message.type)
{
case CalibrationContext::Message::String:
ImGui::TextWrapped(message.str.c_str());
break;
case CalibrationContext::Message::Progress:
float fraction = (float)message.progress / (float)message.target;
ImGui::Text("");
ImGui::ProgressBar(fraction, ImVec2(-1.0f, 0.0f), "");
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - ImGui::GetFontSize() - style.FramePadding.y * 2);
ImGui::Text(" %d%%", (int)(fraction * 100));
break;
}
}
ImGui::PopStyleColor();
if (CalCtx.state == CalibrationState::None)
{
ImGui::Text("");
if (ImGui::Button("Close", ImVec2(ImGui::GetWindowContentRegionWidth(), ImGui::GetTextLineHeight() * 2)))
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
}
void BuildSystemSelection(const VRState &state)
{
if (state.trackingSystems.empty())
{
ImGui::Text("No tracked devices are present");
return;
}
ImGuiStyle &style = ImGui::GetStyle();
float paneWidth = ImGui::GetWindowContentRegionWidth() / 2 - style.FramePadding.x;
TextWithWidth("ReferenceSystemLabel", "Reference Space", paneWidth);
ImGui::SameLine();
TextWithWidth("TargetSystemLabel", "Target Space", paneWidth);
int currentReferenceSystem = -1;
int currentTargetSystem = -1;
int firstReferenceSystemNotTargetSystem = -1;
std::vector<const char *> referenceSystems;
for (auto &str : state.trackingSystems)
{
if (str == CalCtx.referenceTrackingSystem)
{
currentReferenceSystem = (int) referenceSystems.size();
}
else if (firstReferenceSystemNotTargetSystem == -1 && str != CalCtx.targetTrackingSystem)
{
firstReferenceSystemNotTargetSystem = (int) referenceSystems.size();
}
referenceSystems.push_back(str.c_str());
}
if (currentReferenceSystem == -1 && CalCtx.referenceTrackingSystem == "")
{
if (CalCtx.state == CalibrationState::ContinuousStandby) {
auto iter = std::find(state.trackingSystems.begin(), state.trackingSystems.end(), CalCtx.referenceStandby.trackingSystem);
if (iter != state.trackingSystems.end()) {
currentReferenceSystem = iter - state.trackingSystems.begin();
}
}
else {
currentReferenceSystem = firstReferenceSystemNotTargetSystem;
}
}
ImGui::PushItemWidth(paneWidth);
ImGui::Combo("##ReferenceTrackingSystem", &currentReferenceSystem, &referenceSystems[0], (int) referenceSystems.size());
if (currentReferenceSystem != -1 && currentReferenceSystem < (int) referenceSystems.size())
{
CalCtx.referenceTrackingSystem = std::string(referenceSystems[currentReferenceSystem]);
if (CalCtx.referenceTrackingSystem == CalCtx.targetTrackingSystem)
CalCtx.targetTrackingSystem = "";
}
if (CalCtx.targetTrackingSystem == "") {
if (CalCtx.state == CalibrationState::ContinuousStandby) {
auto iter = std::find(state.trackingSystems.begin(), state.trackingSystems.end(), CalCtx.targetStandby.trackingSystem);
if (iter != state.trackingSystems.end()) {
currentTargetSystem = iter - state.trackingSystems.begin();
}
}
else {
currentTargetSystem = 0;
}
}
std::vector<const char *> targetSystems;
for (auto &str : state.trackingSystems)
{
if (str != CalCtx.referenceTrackingSystem)
{
if (str != "" && str == CalCtx.targetTrackingSystem)
currentTargetSystem = (int) targetSystems.size();
targetSystems.push_back(str.c_str());
}
}
ImGui::SameLine();
ImGui::Combo("##TargetTrackingSystem", &currentTargetSystem, &targetSystems[0], (int) targetSystems.size());
if (currentTargetSystem != -1 && currentTargetSystem < targetSystems.size())
{
CalCtx.targetTrackingSystem = std::string(targetSystems[currentTargetSystem]);
}
ImGui::PopItemWidth();
}
void AppendSeparated(std::string &buffer, const std::string &suffix)
{
if (!buffer.empty())
buffer += " | ";
buffer += suffix;
}
std::string LabelString(const VRDevice &device)
{
std::string label;
/*if (device.controllerRole == vr::TrackedControllerRole_LeftHand)
label = "Left Controller";
else if (device.controllerRole == vr::TrackedControllerRole_RightHand)
label = "Right Controller";
else if (device.deviceClass == vr::TrackedDeviceClass_Controller)
label = "Controller";
else if (device.deviceClass == vr::TrackedDeviceClass_HMD)
label = "HMD";
else if (device.deviceClass == vr::TrackedDeviceClass_GenericTracker)
label = "Tracker";*/
AppendSeparated(label, device.model);
AppendSeparated(label, device.serial);
return label;
}
std::string LabelString(const StandbyDevice& device) {
std::string label("< ");
label += device.model;
AppendSeparated(label, device.serial);
label += " >";
return label;
}
void BuildDeviceSelection(const VRState &state, int &initialSelected, const std::string &system, StandbyDevice &standbyDevice)
{
int selected = initialSelected;
ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 1), "Devices from: %s", system.c_str());
if (selected != -1)
{
bool matched = false;
for (auto &device : state.devices)
{
if (device.trackingSystem != system)
continue;
if (selected == device.id)
{
matched = true;
break;
}
}
if (!matched)
{
// Device is no longer present.
selected = -1;
}
}
bool standby = CalCtx.state == CalibrationState::ContinuousStandby;
if (selected == -1 && !standby)
{
for (auto &device : state.devices)
{
if (device.trackingSystem != system)
continue;
if (device.controllerRole == vr::TrackedControllerRole_LeftHand)
{
selected = device.id;
break;
}
}
if (selected == -1) {
for (auto& device : state.devices)
{
if (device.trackingSystem != system)
continue;
selected = device.id;
break;
}
}
}
if (selected == -1 && standby) {
bool present = false;
for (auto& device : state.devices)
{
if (device.trackingSystem != system)
continue;
if (standbyDevice.model != device.model) continue;
if (standbyDevice.serial != device.serial) continue;
present = true;
break;
}
if (!present) {
auto label = LabelString(standbyDevice);
ImGui::Selectable(label.c_str(), true);
}
}
for (auto &device : state.devices)
{
if (device.trackingSystem != system)
continue;
auto label = LabelString(device);
if (ImGui::Selectable(label.c_str(), selected == device.id)) {
selected = device.id;
}
}
if (selected != initialSelected) {
const auto& device = std::find_if(state.devices.begin(), state.devices.end(), [&](const auto& d) { return d.id == selected; });
if (device == state.devices.end()) return;
initialSelected = selected;
standbyDevice.trackingSystem = system;
standbyDevice.model = device->model;
standbyDevice.serial = device->serial;
}
}
void BuildDeviceSelections(const VRState &state)
{
ImGuiStyle &style = ImGui::GetStyle();
ImVec2 paneSize(ImGui::GetWindowContentRegionWidth() / 2 - style.FramePadding.x, ImGui::GetTextLineHeightWithSpacing() * 5 + style.ItemSpacing.y * 4);
ImGui::BeginChild("left device pane", paneSize, true);
BuildDeviceSelection(state, CalCtx.referenceID, CalCtx.referenceTrackingSystem, CalCtx.referenceStandby);
ImGui::EndChild();
ImGui::SameLine();
ImGui::BeginChild("right device pane", paneSize, true);
BuildDeviceSelection(state, CalCtx.targetID, CalCtx.targetTrackingSystem, CalCtx.targetStandby);
ImGui::EndChild();
if (ImGui::Button("Identify selected devices (blinks LED or vibrates)", ImVec2(ImGui::GetWindowContentRegionWidth(), ImGui::GetTextLineHeightWithSpacing() + 4.0f)))
{
for (unsigned i = 0; i < 100; ++i)
{
vr::VRSystem()->TriggerHapticPulse(CalCtx.targetID, 0, 2000);
vr::VRSystem()->TriggerHapticPulse(CalCtx.referenceID, 0, 2000);
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
}
}
VRState LoadVRState() {
VRState state = VRState::Load();
auto& trackingSystems = state.trackingSystems;
// Inject entries for continuous calibration targets which have yet to load
if (CalCtx.state == CalibrationState::ContinuousStandby) {
auto existing = std::find(trackingSystems.begin(), trackingSystems.end(), CalCtx.referenceTrackingSystem);
if (existing == trackingSystems.end()) {
trackingSystems.push_back(CalCtx.referenceTrackingSystem);
}
existing = std::find(trackingSystems.begin(), trackingSystems.end(), CalCtx.targetTrackingSystem);
if (existing == trackingSystems.end()) {
trackingSystems.push_back(CalCtx.targetTrackingSystem);
}
}
return state;
}
void BuildProfileEditor()
{
ImGuiStyle &style = ImGui::GetStyle();
float width = ImGui::GetWindowContentRegionWidth() / 3.0f - style.FramePadding.x;
float widthF = width - style.FramePadding.x;
TextWithWidth("YawLabel", "Yaw", width);
ImGui::SameLine();
TextWithWidth("PitchLabel", "Pitch", width);
ImGui::SameLine();
TextWithWidth("RollLabel", "Roll", width);
ImGui::PushItemWidth(widthF);
ImGui::InputDouble("##Yaw", &CalCtx.calibratedRotation(1), 0.1, 1.0, "%.8f");
ImGui::SameLine();
ImGui::InputDouble("##Pitch", &CalCtx.calibratedRotation(2), 0.1, 1.0, "%.8f");
ImGui::SameLine();
ImGui::InputDouble("##Roll", &CalCtx.calibratedRotation(0), 0.1, 1.0, "%.8f");
TextWithWidth("XLabel", "X", width);
ImGui::SameLine();
TextWithWidth("YLabel", "Y", width);
ImGui::SameLine();
TextWithWidth("ZLabel", "Z", width);
ImGui::InputDouble("##X", &CalCtx.calibratedTranslation(0), 1.0, 10.0, "%.8f");
ImGui::SameLine();
ImGui::InputDouble("##Y", &CalCtx.calibratedTranslation(1), 1.0, 10.0, "%.8f");
ImGui::SameLine();
ImGui::InputDouble("##Z", &CalCtx.calibratedTranslation(2), 1.0, 10.0, "%.8f");
TextWithWidth("ScaleLabel", "Scale", width);
ImGui::InputDouble("##Scale", &CalCtx.calibratedScale, 0.0001, 0.01, "%.8f");
ImGui::PopItemWidth();
}
void TextWithWidth(const char *label, const char *text, float width)
{
ImGui::BeginChild(label, ImVec2(width, ImGui::GetTextLineHeightWithSpacing()));
ImGui::Text(text);
ImGui::EndChild();
}
+4
View File
@@ -0,0 +1,4 @@
#pragma once
void BuildMainWindow(bool runningInOverlay);
void RequestImmediateRedraw();
+108
View File
@@ -0,0 +1,108 @@
#include "stdafx.h"
#include "VRState.h"
VRState VRState::Load()
{
VRState state;
auto& trackingSystems = state.trackingSystems;
char buffer[vr::k_unMaxPropertyStringSize];
for (uint32_t id = 0; id < vr::k_unMaxTrackedDeviceCount; ++id)
{
vr::ETrackedPropertyError err = vr::TrackedProp_Success;
auto deviceClass = vr::VRSystem()->GetTrackedDeviceClass(id);
if (deviceClass == vr::TrackedDeviceClass_Invalid)
continue;
if (deviceClass != vr::TrackedDeviceClass_TrackingReference)
{
vr::VRSystem()->GetStringTrackedDeviceProperty(id, vr::Prop_TrackingSystemName_String, buffer, vr::k_unMaxPropertyStringSize, &err);
if (err == vr::TrackedProp_Success)
{
std::string system(buffer);
// Check if the current HMD is a Pimax crystal
if (deviceClass == vr::TrackedDeviceClass_HMD && system == "aapvr") {
// HMD is a Pimax HMD
vr::HmdMatrix34_t eyeToHeadLeft = vr::VRSystem()->GetEyeToHeadTransform(vr::Eye_Left);
// Crystal's projection matrix is constant 0s or 1s except for [0][3], which stores the IPD offset from the nose
bool isCrystalHmd =
eyeToHeadLeft.m[0][0] == 1 && eyeToHeadLeft.m[0][1] == 0 && eyeToHeadLeft.m[0][2] == 0 && // IPD
eyeToHeadLeft.m[1][0] == 0 && eyeToHeadLeft.m[1][1] == 1 && eyeToHeadLeft.m[1][2] == 0 && eyeToHeadLeft.m[1][3] == 0 &&
eyeToHeadLeft.m[2][0] == 0 && eyeToHeadLeft.m[2][1] == 0 && eyeToHeadLeft.m[2][2] == 1 && eyeToHeadLeft.m[2][3] == 0;
if (isCrystalHmd) {
// Move it outside the aapvr system ; we treat aapvr as if it were lighthouse
system = "Pimax Crystal HMD";
}
} else if (deviceClass == vr::TrackedDeviceClass_Controller && system == "oculus") {
vr::VRSystem()->GetStringTrackedDeviceProperty(id, vr::Prop_RenderModelName_String, buffer, vr::k_unMaxPropertyStringSize, &err);
std::string renderModel(buffer);
vr::VRSystem()->GetStringTrackedDeviceProperty(id, vr::Prop_ConnectedWirelessDongle_String, buffer, vr::k_unMaxPropertyStringSize, &err);
std::string connectedWirelessDongle(buffer);
// Check if the controller claims its an oculus controller but also pimax
if (renderModel.find("{aapvr}") != std::string::npos &&
renderModel.find("crystal") != std::string::npos &&
connectedWirelessDongle.find("lighthouse") != std::string::npos) {
system = "Pimax Crystal Controllers";
}
}
auto existing = std::find(trackingSystems.begin(), trackingSystems.end(), system);
if (existing != trackingSystems.end())
{
if (deviceClass == vr::TrackedDeviceClass_HMD)
{
trackingSystems.erase(existing);
trackingSystems.insert(trackingSystems.begin(), system);
}
}
else
{
trackingSystems.push_back(system);
}
VRDevice device;
device.id = id;
device.deviceClass = deviceClass;
device.trackingSystem = system;
vr::VRSystem()->GetStringTrackedDeviceProperty(id, vr::Prop_ModelNumber_String, buffer, vr::k_unMaxPropertyStringSize, &err);
device.model = std::string(buffer);
vr::VRSystem()->GetStringTrackedDeviceProperty(id, vr::Prop_SerialNumber_String, buffer, vr::k_unMaxPropertyStringSize, &err);
device.serial = std::string(buffer);
device.controllerRole = (vr::ETrackedControllerRole)vr::VRSystem()->GetInt32TrackedDeviceProperty(id, vr::Prop_ControllerRoleHint_Int32, &err);
state.devices.push_back(device);
}
else
{
printf("failed to get tracking system name for id %d\n", id);
}
}
}
return state;
}
int VRState::FindDevice(const std::string& trackingSystem, const std::string& model, const std::string& serial) const {
for (int i = 0; i < devices.size(); i++) {
const auto& device = devices[i];
if (device.trackingSystem == trackingSystem && device.model == model && device.serial == serial) return device.id;
}
// allow fallback excluding serial for HMD specifically
for (int i = 0; i < devices.size(); i++) {
const auto& device = devices[i];
if (device.trackingSystem == trackingSystem && device.model == model && device.deviceClass == vr::TrackedDeviceClass::TrackedDeviceClass_HMD) return device.id;
}
return -1;
}
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include <string>
#include <vector>
#include <openvr.h>
struct VRDevice
{
int id = -1;
vr::TrackedDeviceClass deviceClass;
std::string model = "";
std::string serial = "";
std::string trackingSystem = "";
vr::ETrackedControllerRole controllerRole = vr::TrackedControllerRole_Invalid;
};
struct VRState
{
std::vector<std::string> trackingSystems;
std::vector<VRDevice> devices;
int FindDevice(const std::string& trackingSystem, const std::string& model, const std::string& serial) const;
static VRState Load();
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

+128
View File
@@ -0,0 +1,128 @@
#include "imgui_extensions.h"
#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui_internal.h"
static ImVector<ImRect> s_GroupPanelLabelStack;
void ImGui::BeginGroupPanel(const char* name, const ImVec2& size)
{
ImGui::BeginGroup();
auto cursorPos = ImGui::GetCursorScreenPos();
auto itemSpacing = ImGui::GetStyle().ItemSpacing;
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f));
auto frameHeight = ImGui::GetFrameHeight();
ImGui::BeginGroup();
ImVec2 effectiveSize = size;
if (size.x < 0.0f)
effectiveSize.x = ImGui::GetContentRegionAvail().x;
else
effectiveSize.x = size.x;
ImGui::Dummy(ImVec2(effectiveSize.x, 0.0f));
ImGui::Dummy(ImVec2(frameHeight * 0.5f, 0.0f));
ImGui::SameLine(0.0f, 0.0f);
ImGui::BeginGroup();
ImGui::Dummy(ImVec2(frameHeight * 0.5f, 0.0f));
ImGui::SameLine(0.0f, 0.0f);
ImGui::TextUnformatted(name);
auto labelMin = ImGui::GetItemRectMin();
auto labelMax = ImGui::GetItemRectMax();
ImGui::SameLine(0.0f, 0.0f);
ImGui::Dummy(ImVec2(0.0, frameHeight + itemSpacing.y));
ImGui::BeginGroup();
//ImGui::GetWindowDrawList()->AddRect(labelMin, labelMax, IM_COL32(255, 0, 255, 255));
ImGui::PopStyleVar(2);
#if IMGUI_VERSION_NUM >= 17301
ImGui::GetCurrentWindow()->ContentRegionRect.Max.x -= frameHeight * 0.5f;
ImGui::GetCurrentWindow()->WorkRect.Max.x -= frameHeight * 0.5f;
ImGui::GetCurrentWindow()->InnerRect.Max.x -= frameHeight * 0.5f;
#else
ImGui::GetCurrentWindow()->ContentsRegionRect.Max.x -= frameHeight * 0.5f;
#endif
ImGui::GetCurrentWindow()->Size.x -= frameHeight;
auto itemWidth = ImGui::CalcItemWidth();
ImGui::PushItemWidth(ImMax(0.0f, itemWidth - frameHeight));
s_GroupPanelLabelStack.push_back(ImRect(labelMin, labelMax));
}
void ImGui::EndGroupPanel()
{
ImGui::PopItemWidth();
auto itemSpacing = ImGui::GetStyle().ItemSpacing;
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f));
auto frameHeight = ImGui::GetFrameHeight();
ImGui::EndGroup();
//ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(0, 255, 0, 64), 4.0f);
ImGui::EndGroup();
ImGui::SameLine(0.0f, 0.0f);
ImGui::Dummy(ImVec2(frameHeight * 0.5f, 0.0f));
ImGui::Dummy(ImVec2(0.0, frameHeight - frameHeight * 0.5f - itemSpacing.y));
ImGui::EndGroup();
auto itemMin = ImGui::GetItemRectMin();
auto itemMax = ImGui::GetItemRectMax();
//ImGui::GetWindowDrawList()->AddRectFilled(itemMin, itemMax, IM_COL32(255, 0, 0, 64), 4.0f);
auto labelRect = s_GroupPanelLabelStack.back();
s_GroupPanelLabelStack.pop_back();
ImVec2 halfFrame = ImVec2(frameHeight * 0.25f, frameHeight) * 0.5f;
ImRect frameRect = ImRect(itemMin + halfFrame, itemMax - ImVec2(halfFrame.x, 0.0f));
labelRect.Min.x -= itemSpacing.x;
labelRect.Max.x += itemSpacing.x;
for (int i = 0; i < 4; ++i)
{
switch (i)
{
// left half-plane
case 0: ImGui::PushClipRect(ImVec2(-FLT_MAX, -FLT_MAX), ImVec2(labelRect.Min.x, FLT_MAX), true); break;
// right half-plane
case 1: ImGui::PushClipRect(ImVec2(labelRect.Max.x, -FLT_MAX), ImVec2(FLT_MAX, FLT_MAX), true); break;
// top
case 2: ImGui::PushClipRect(ImVec2(labelRect.Min.x, -FLT_MAX), ImVec2(labelRect.Max.x, labelRect.Min.y), true); break;
// bottom
case 3: ImGui::PushClipRect(ImVec2(labelRect.Min.x, labelRect.Max.y), ImVec2(labelRect.Max.x, FLT_MAX), true); break;
}
ImGui::GetWindowDrawList()->AddRect(
frameRect.Min, frameRect.Max,
ImColor(ImGui::GetStyleColorVec4(ImGuiCol_Border)),
halfFrame.x);
ImGui::PopClipRect();
}
ImGui::PopStyleVar(2);
#if IMGUI_VERSION_NUM >= 17301
ImGui::GetCurrentWindow()->ContentRegionRect.Max.x += frameHeight * 0.5f;
ImGui::GetCurrentWindow()->WorkRect.Max.x += frameHeight * 0.5f;
ImGui::GetCurrentWindow()->InnerRect.Max.x += frameHeight * 0.5f;
#else
ImGui::GetCurrentWindow()->ContentsRegionRect.Max.x += frameHeight * 0.5f;
#endif
ImGui::GetCurrentWindow()->Size.x += frameHeight;
ImGui::Dummy(ImVec2(0.0f, 0.0f));
ImGui::EndGroup();
}
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include <imgui.h>
namespace ImGui
{
// Group panels taken from https://github.com/ocornut/imgui/issues/1496#issuecomment-655048353
// Licensed under CC0 license as per https://github.com/ocornut/imgui/issues/1496#issuecomment-1287772456
void BeginGroupPanel(const char* name, const ImVec2& size = ImVec2(0.0f, 0.0f));
void EndGroupPanel();
}
@@ -0,0 +1,16 @@
{
"source" : "builtin",
"applications": [{
"app_key": "pushrax.SpaceCalibrator",
"launch_type": "binary",
"binary_path_windows": "OpenVR-SpaceCalibrator.exe",
"is_dashboard_overlay": true,
"strings": {
"en_us": {
"name": "Space Calibrator",
"description": "OpenVR Space Calibrator Overlay"
}
}
}]
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 70 KiB

+2
View File
@@ -1,5 +1,7 @@
#pragma once
#define EIGEN_MPL2_ONLY
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN
@@ -0,0 +1,6 @@
{
"alwaysActivate": true,
"name" : "01spacecalibrator",
"directory" : "",
"resourceOnly" : false
}
@@ -0,0 +1,5 @@
{
"jsonid" : "vrresources",
"statusicons" : {
}
}
@@ -0,0 +1,4 @@
{
"driver_01spacecalibrator" : {
}
}
+27
View File
@@ -0,0 +1,27 @@
#include "Hooking.h"
std::map<std::string, IHook *> IHook::hooks;
bool IHook::Exists(const std::string &name)
{
return hooks.find(name) != hooks.end();
}
void IHook::Register(IHook *hook)
{
hooks[hook->name] = hook;
}
void IHook::Unregister(IHook *hook)
{
hooks.erase(hook->name);
}
void IHook::DestroyAll()
{
for (auto &hook : hooks)
{
hook.second->Destroy();
}
hooks.clear();
}
+75
View File
@@ -0,0 +1,75 @@
#pragma once
#include "Logging.h"
#include <MinHook.h>
#include <map>
#include <string>
class IHook
{
public:
const std::string name;
IHook(const std::string &name) : name(name) { }
virtual ~IHook() { }
virtual void Destroy() = 0;
static bool Exists(const std::string &name);
static void Register(IHook *hook);
static void Unregister(IHook *hook);
static void DestroyAll();
private:
static std::map<std::string, IHook *> hooks;
};
template<class FuncType> class Hook : public IHook
{
public:
FuncType originalFunc = nullptr;
Hook(const std::string &name) : IHook(name) { }
bool CreateHookInObjectVTable(void *object, int vtableOffset, void *detourFunction)
{
// For virtual objects, VC++ adds a pointer to the vtable as the first member.
// To access the vtable, we simply dereference the object.
void **vtable = *((void ***)object);
// The vtable itself is an array of pointers to member functions,
// in the order they were declared in.
targetFunc = vtable[vtableOffset];
auto err = MH_CreateHook(targetFunc, detourFunction, (LPVOID *)&originalFunc);
if (err != MH_OK)
{
LOG("Failed to create hook for %s, error: %s", name.c_str(), MH_StatusToString(err));
return false;
}
err = MH_EnableHook(targetFunc);
if (err != MH_OK)
{
LOG("Failed to enable hook for %s, error: %s", name.c_str(), MH_StatusToString(err));
MH_RemoveHook(targetFunc);
return false;
}
LOG("Enabled hook for %s", name.c_str());
enabled = true;
return true;
}
void Destroy()
{
if (enabled)
{
MH_RemoveHook(targetFunc);
enabled = false;
}
}
private:
bool enabled = false;
void* targetFunc = nullptr;
};
+230
View File
@@ -0,0 +1,230 @@
#include "IPCServer.h"
#include "Logging.h"
#include "ServerTrackedDeviceProvider.h"
void IPCServer::HandleRequest(const protocol::Request &request, protocol::Response &response)
{
switch (request.type)
{
case protocol::RequestHandshake:
response.type = protocol::ResponseHandshake;
response.protocol.version = protocol::Version;
break;
case protocol::RequestSetDeviceTransform:
driver->SetDeviceTransform(request.setDeviceTransform);
response.type = protocol::ResponseSuccess;
break;
case protocol::RequestDebugOffset:
driver->HandleApplyRandomOffset();
response.type = protocol::ResponseSuccess;
break;
case protocol::RequestSetAlignmentSpeedParams:
driver->HandleSetAlignmentSpeedParams(request.setAlignmentSpeedParams);
response.type = protocol::ResponseSuccess;
break;
default:
LOG("Invalid IPC request: %d", request.type);
break;
}
}
IPCServer::~IPCServer()
{
Stop();
}
void IPCServer::Run()
{
mainThread = std::thread(RunThread, this);
}
void IPCServer::Stop()
{
TRACE("IPCServer::Stop()");
if (!running)
return;
stop = true;
SetEvent(connectEvent);
mainThread.join();
running = false;
TRACE("IPCServer::Stop() finished");
}
IPCServer::PipeInstance *IPCServer::CreatePipeInstance(HANDLE pipe)
{
auto pipeInst = new PipeInstance;
pipeInst->pipe = pipe;
pipeInst->server = this;
pipes.insert(pipeInst);
return pipeInst;
}
void IPCServer::ClosePipeInstance(PipeInstance *pipeInst)
{
DisconnectNamedPipe(pipeInst->pipe);
CloseHandle(pipeInst->pipe);
pipes.erase(pipeInst);
delete pipeInst;
}
void IPCServer::RunThread(IPCServer *_this)
{
_this->running = true;
LPTSTR pipeName = TEXT(OPENVR_SPACECALIBRATOR_PIPE_NAME);
HANDLE connectEvent = _this->connectEvent = CreateEvent(0, TRUE, TRUE, 0);
if (!connectEvent)
{
LOG("CreateEvent failed in RunThread. Error: %d", GetLastError());
return;
}
OVERLAPPED connectOverlap;
connectOverlap.hEvent = connectEvent;
HANDLE nextPipe;
BOOL connectPending = CreateAndConnectInstance(&connectOverlap, nextPipe);
while (!_this->stop)
{
DWORD wait = WaitForSingleObjectEx(connectEvent, INFINITE, TRUE);
if (_this->stop)
{
break;
}
else if (wait == 0)
{
// When connectPending is false, the last call to CreateAndConnectInstance
// picked up a connected client and triggered this event, so we can simply
// create a new pipe instance for it. If true, the client was still pending
// connection when CreateAndConnectInstance returned, so this event was triggered
// internally and we need to flush out the result, or something like that.
if (connectPending)
{
DWORD bytesConnect;
BOOL success = GetOverlappedResult(nextPipe, &connectOverlap, &bytesConnect, FALSE);
if (!success)
{
LOG("GetOverlappedResult failed in RunThread. Error: %d", GetLastError());
return;
}
}
LOG("IPC client connected");
auto pipeInst = _this->CreatePipeInstance(nextPipe);
CompletedWriteCallback(0, sizeof protocol::Response, (LPOVERLAPPED) pipeInst);
connectPending = CreateAndConnectInstance(&connectOverlap, nextPipe);
}
else if (wait != WAIT_IO_COMPLETION)
{
printf("WaitForSingleObjectEx failed in RunThread. Error %d", GetLastError());
return;
}
}
for (auto &pipeInst : _this->pipes)
{
_this->ClosePipeInstance(pipeInst);
}
_this->pipes.clear();
}
BOOL IPCServer::CreateAndConnectInstance(LPOVERLAPPED overlap, HANDLE &pipe)
{
pipe = CreateNamedPipe(
TEXT(OPENVR_SPACECALIBRATOR_PIPE_NAME),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
sizeof protocol::Request,
sizeof protocol::Response,
1000,
0
);
if (pipe == INVALID_HANDLE_VALUE)
{
LOG("CreateNamedPipe failed. Error: %d", GetLastError());
return FALSE;
}
ConnectNamedPipe(pipe, overlap);
switch(GetLastError())
{
case ERROR_IO_PENDING:
// Mark a pending connection by returning true, and when the connection
// completes an event will trigger automatically.
return TRUE;
case ERROR_PIPE_CONNECTED:
// Signal the event loop that a client is connected.
if (SetEvent(overlap->hEvent))
return FALSE;
}
LOG("ConnectNamedPipe failed. Error: %d", GetLastError());
return FALSE;
}
void IPCServer::CompletedReadCallback(DWORD err, DWORD bytesRead, LPOVERLAPPED overlap)
{
PipeInstance *pipeInst = (PipeInstance *) overlap;
BOOL success = FALSE;
if (err == 0 && bytesRead > 0)
{
pipeInst->server->HandleRequest(pipeInst->request, pipeInst->response);
success = WriteFileEx(
pipeInst->pipe,
&pipeInst->response,
sizeof protocol::Response,
overlap,
(LPOVERLAPPED_COMPLETION_ROUTINE) CompletedWriteCallback
);
}
if (!success)
{
if (err == ERROR_BROKEN_PIPE)
{
LOG("IPC client disconnecting normally");
}
else
{
LOG("IPC client disconnecting due to error (via CompletedReadCallback), error: %d, bytesRead: %d", err, bytesRead);
}
pipeInst->server->ClosePipeInstance(pipeInst);
}
}
void IPCServer::CompletedWriteCallback(DWORD err, DWORD bytesWritten, LPOVERLAPPED overlap)
{
PipeInstance *pipeInst = (PipeInstance *) overlap;
BOOL success = FALSE;
if (err == 0 && bytesWritten == sizeof protocol::Response)
{
success = ReadFileEx(
pipeInst->pipe,
&pipeInst->request,
sizeof protocol::Request,
overlap,
(LPOVERLAPPED_COMPLETION_ROUTINE) CompletedReadCallback
);
}
if (!success)
{
LOG("IPC client disconnecting due to error (via CompletedWriteCallback), error: %d, bytesWritten: %d", err, bytesWritten);
pipeInst->server->ClosePipeInstance(pipeInst);
}
}
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include "../Protocol.h"
#include <thread>
#include <set>
#include <mutex>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
class ServerTrackedDeviceProvider;
class IPCServer
{
public:
IPCServer(ServerTrackedDeviceProvider *driver) : driver(driver) { }
~IPCServer();
void Run();
void Stop();
private:
void HandleRequest(const protocol::Request &request, protocol::Response &response);
struct PipeInstance
{
OVERLAPPED overlap; // Used by the API
HANDLE pipe;
IPCServer *server;
protocol::Request request;
protocol::Response response;
};
PipeInstance *CreatePipeInstance(HANDLE pipe);
void ClosePipeInstance(PipeInstance *pipeInst);
static void RunThread(IPCServer *_this);
static BOOL CreateAndConnectInstance(LPOVERLAPPED overlap, HANDLE &pipe);
static void WINAPI CompletedReadCallback(DWORD err, DWORD bytesRead, LPOVERLAPPED overlap);
static void WINAPI CompletedWriteCallback(DWORD err, DWORD bytesWritten, LPOVERLAPPED overlap);
std::thread mainThread;
bool running = false;
bool stop = false;
std::set<PipeInstance *> pipes;
HANDLE connectEvent;
ServerTrackedDeviceProvider *driver;
};
@@ -0,0 +1,83 @@
#include "Logging.h"
#include "Hooking.h"
#include "InterfaceHookInjector.h"
#include "ServerTrackedDeviceProvider.h"
static ServerTrackedDeviceProvider *Driver = nullptr;
static Hook<void*(*)(vr::IVRDriverContext *, const char *, vr::EVRInitError *)>
GetGenericInterfaceHook("IVRDriverContext::GetGenericInterface");
static Hook<void(*)(vr::IVRServerDriverHost *, uint32_t, const vr::DriverPose_t &, uint32_t)>
TrackedDevicePoseUpdatedHook005("IVRServerDriverHost005::TrackedDevicePoseUpdated");
static Hook<void(*)(vr::IVRServerDriverHost *, uint32_t, const vr::DriverPose_t &, uint32_t)>
TrackedDevicePoseUpdatedHook006("IVRServerDriverHost006::TrackedDevicePoseUpdated");
static void DetourTrackedDevicePoseUpdated005(vr::IVRServerDriverHost *_this, uint32_t unWhichDevice, const vr::DriverPose_t &newPose, uint32_t unPoseStructSize)
{
//TRACE("ServerTrackedDeviceProvider::DetourTrackedDevicePoseUpdated(%d)", unWhichDevice);
auto pose = newPose;
if (Driver->HandleDevicePoseUpdated(unWhichDevice, pose))
{
TrackedDevicePoseUpdatedHook005.originalFunc(_this, unWhichDevice, pose, unPoseStructSize);
}
}
static void DetourTrackedDevicePoseUpdated006(vr::IVRServerDriverHost *_this, uint32_t unWhichDevice, const vr::DriverPose_t &newPose, uint32_t unPoseStructSize)
{
//TRACE("ServerTrackedDeviceProvider::DetourTrackedDevicePoseUpdated(%d)", unWhichDevice);
auto pose = newPose;
if (Driver->HandleDevicePoseUpdated(unWhichDevice, pose))
{
TrackedDevicePoseUpdatedHook006.originalFunc(_this, unWhichDevice, pose, unPoseStructSize);
}
}
static void *DetourGetGenericInterface(vr::IVRDriverContext *_this, const char *pchInterfaceVersion, vr::EVRInitError *peError)
{
TRACE("ServerTrackedDeviceProvider::DetourGetGenericInterface(%s)", pchInterfaceVersion);
auto originalInterface = GetGenericInterfaceHook.originalFunc(_this, pchInterfaceVersion, peError);
std::string iface(pchInterfaceVersion);
if (iface == "IVRServerDriverHost_005")
{
if (!IHook::Exists(TrackedDevicePoseUpdatedHook005.name))
{
TrackedDevicePoseUpdatedHook005.CreateHookInObjectVTable(originalInterface, 1, &DetourTrackedDevicePoseUpdated005);
IHook::Register(&TrackedDevicePoseUpdatedHook005);
}
}
else if (iface == "IVRServerDriverHost_006")
{
if (!IHook::Exists(TrackedDevicePoseUpdatedHook006.name))
{
TrackedDevicePoseUpdatedHook006.CreateHookInObjectVTable(originalInterface, 1, &DetourTrackedDevicePoseUpdated006);
IHook::Register(&TrackedDevicePoseUpdatedHook006);
}
}
return originalInterface;
}
void InjectHooks(ServerTrackedDeviceProvider *driver, vr::IVRDriverContext *pDriverContext)
{
Driver = driver;
auto err = MH_Initialize();
if (err == MH_OK)
{
GetGenericInterfaceHook.CreateHookInObjectVTable(pDriverContext, 0, &DetourGetGenericInterface);
IHook::Register(&GetGenericInterfaceHook);
}
else
{
LOG("MH_Initialize error: %s", MH_StatusToString(err));
}
}
void DisableHooks()
{
IHook::DestroyAll();
MH_Uninitialize();
}
@@ -0,0 +1,10 @@
#pragma once
#include <openvr_driver.h>
class ServerTrackedDeviceProvider;
static void DetourTrackedDevicePoseUpdated(vr::IVRServerDriverHost * _this, uint32_t unWhichDevice, const vr::DriverPose_t & newPose, uint32_t unPoseStructSize);
void InjectHooks(ServerTrackedDeviceProvider *driver, vr::IVRDriverContext *pDriverContext);
void DisableHooks();
@@ -0,0 +1,50 @@
#pragma once
#define EIGEN_MPL2_ONLY
#include <Eigen/Dense>
/**
* Contains an isometric transformation, represented as the pair of a rotation quaternion and translation vector.
* The translation is applied to the left of the quaternion.
*/
struct IsoTransform {
Eigen::Quaterniond rotation;
Eigen::Vector3d translation;
IsoTransform() : rotation(Eigen::Quaterniond::Identity()), translation(Eigen::Vector3d::Zero()) {}
IsoTransform(const Eigen::Quaterniond &rot) : rotation(rot), translation(Eigen::Vector3d::Zero()) {}
IsoTransform(const Eigen::Vector3d &trans) : rotation(Eigen::Quaterniond::Identity()) {}
IsoTransform(const Eigen::Quaterniond& rot, const Eigen::Vector3d& trans) : rotation(rot), translation(trans) {}
void pretranslate(const Eigen::Vector3d& t) {
translation += t;
}
/**
* Interpolates between this transform and target. The position of localPoint after transformation will smoothly
* lerp between (this * localPoint) and (target * localPoint), despite rotation occurring around it.
*/
IsoTransform interpolateAround(double lerp, const IsoTransform& target, const Eigen::Vector3d& localPoint) const;
};
inline IsoTransform operator*(const IsoTransform& a, const IsoTransform& b) {
// tA * rA * tB * rB = tA * (trans(rA * tB)) * rA * rB
auto rot = a.rotation * b.rotation;
Eigen::Vector3d trans = a.translation + Eigen::Isometry3d(a.rotation) * b.translation;
return IsoTransform(rot, trans);
}
inline Eigen::Vector3d operator*(const IsoTransform& a, const Eigen::Vector3d& p) {
return a.translation + Eigen::Isometry3d(a.rotation) * p;
}
inline IsoTransform IsoTransform::interpolateAround(double lerp, const IsoTransform& target, const Eigen::Vector3d& localPoint) const {
auto initialPos = (*this) * localPoint;
Eigen::Vector3d finalPos = initialPos * (1 - lerp) + (target * localPoint) * lerp;
auto newRotation = rotation.slerp(lerp, target.rotation);
Eigen::Vector3d newTranslation = finalPos - Eigen::Isometry3d(newRotation) * localPoint;
return IsoTransform(newRotation, newTranslation);
}
+28
View File
@@ -0,0 +1,28 @@
#define _CRT_SECURE_NO_DEPRECATE
#include "Logging.h"
#include <chrono>
FILE *LogFile;
void OpenLogFile()
{
LogFile = fopen("space_calibrator_driver.log", "a");
if (LogFile == nullptr)
{
LogFile = stderr;
}
}
tm TimeForLog()
{
auto now = std::chrono::system_clock::now();
auto nowTime = std::chrono::system_clock::to_time_t(now);
tm value;
auto tm = localtime_s(&value, &nowTime);
return value;
}
void LogFlush()
{
fflush(LogFile);
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include <cstdio>
#include <ctime>
extern FILE *LogFile;
void OpenLogFile();
tm TimeForLog();
void LogFlush();
#ifndef LOG
#define LOG(fmt, ...) do { \
tm logNow = TimeForLog(); \
fprintf(LogFile, "[%02d:%02d:%02d] " fmt "\n", logNow.tm_hour, logNow.tm_min, logNow.tm_sec, __VA_ARGS__); \
LogFlush(); \
} while (0)
#endif
#define TRACE(...) {}
#ifndef TRACE
#define TRACE LOG
#endif
@@ -0,0 +1,31 @@
#include "OpenVR-SpaceCalibratorDriver.h"
#include "ServerTrackedDeviceProvider.h"
#include "VRWatchdogProvider.h"
#include "Logging.h"
#include <cstdio>
#include <cstring>
#include <openvr_driver.h>
OPENVRSPACECALIBRATORDRIVER_API void *HmdDriverFactory(const char *pInterfaceName, int *pReturnCode)
{
TRACE("HmdDriverFactory(%s)", pInterfaceName);
static ServerTrackedDeviceProvider server;
static VRWatchdogProvider watchdog;
if (std::strcmp(vr::IServerTrackedDeviceProvider_Version, pInterfaceName) == 0)
{
return &server;
}
else if (std::strcmp(vr::IVRWatchdogProvider_Version, pInterfaceName) == 0)
{
return &watchdog;
}
if (pReturnCode)
{
*pReturnCode = vr::VRInitError_Init_InterfaceNotFound;
}
return nullptr;
}
@@ -0,0 +1,7 @@
#pragma once
#ifdef OPENVRSPACECALIBRATORDRIVER_EXPORTS
#define OPENVRSPACECALIBRATORDRIVER_API extern "C" __declspec(dllexport)
#else
#define OPENVRSPACECALIBRATORDRIVER_API extern "C" __declspec(dllimport)
#endif
@@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{A61324AD-CE32-46D1-A95E-7E28A6D8CCA7}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>OpenVRSpaceCalibratorDriver</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<TargetName>driver_01spacecalibrator</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<TargetName>driver_01spacecalibrator</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_WINDOWS;_USRDLL;OPENVRSPACECALIBRATORDRIVER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>..\lib;..\lib\openvr;..\lib\MinHook\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>..\lib\MinHook\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_WINDOWS;_USRDLL;OPENVRSPACECALIBRATORDRIVER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>..\lib;..\lib\openvr;..\lib\MinHook\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>..\lib\MinHook\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="..\Protocol.h" />
<ClInclude Include="Hooking.h" />
<ClInclude Include="InterfaceHookInjector.h" />
<ClInclude Include="IPCServer.h" />
<ClInclude Include="IsometryTransform.h" />
<ClInclude Include="Logging.h" />
<ClInclude Include="OpenVR-SpaceCalibratorDriver.h" />
<ClInclude Include="ServerTrackedDeviceProvider.h" />
<ClInclude Include="VRWatchdogProvider.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp">
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsManaged>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
</PrecompiledHeader>
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsManaged>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
</PrecompiledHeader>
</ClCompile>
<ClCompile Include="Hooking.cpp" />
<ClCompile Include="InterfaceHookInjector.cpp" />
<ClCompile Include="IPCServer.cpp" />
<ClCompile Include="Logging.cpp" />
<ClCompile Include="OpenVR-SpaceCalibratorDriver.cpp" />
<ClCompile Include="ServerTrackedDeviceProvider.cpp" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\lib\minhook\build\VC16\libMinHook.vcxproj">
<Project>{f142a341-5ee0-442d-a15f-98ae9b48dbae}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="OpenVR-SpaceCalibratorDriver.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Logging.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ServerTrackedDeviceProvider.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="VRWatchdogProvider.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="IPCServer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Protocol.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Hooking.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="InterfaceHookInjector.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="IsometryTransform.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="OpenVR-SpaceCalibratorDriver.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="dllmain.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Logging.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ServerTrackedDeviceProvider.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="IPCServer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Hooking.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="InterfaceHookInjector.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
@@ -0,0 +1,257 @@
#include "ServerTrackedDeviceProvider.h"
#include "Logging.h"
#include "InterfaceHookInjector.h"
#include "IsometryTransform.h"
#include <random>
vr::EVRInitError ServerTrackedDeviceProvider::Init(vr::IVRDriverContext *pDriverContext)
{
TRACE("ServerTrackedDeviceProvider::Init()");
VR_INIT_SERVER_DRIVER_CONTEXT(pDriverContext);
memset(transforms, 0, vr::k_unMaxTrackedDeviceCount * sizeof DeviceTransform);
memset(&alignmentSpeedParams, 0, sizeof alignmentSpeedParams);
alignmentSpeedParams.thr_rot_tiny = 0.1f * (EIGEN_PI / 180.0f);
alignmentSpeedParams.thr_rot_small = 1.0f * (EIGEN_PI / 180.0f);
alignmentSpeedParams.thr_rot_large = 5.0f * (EIGEN_PI / 180.0f);
alignmentSpeedParams.thr_trans_tiny = 0.1f / 1000.0; // mm
alignmentSpeedParams.thr_trans_small = 1.0f / 1000.0; // mm
alignmentSpeedParams.thr_trans_large = 20.0f / 1000.0; // mm
alignmentSpeedParams.align_speed_tiny = 0.05f;
alignmentSpeedParams.align_speed_small = 0.2f;
alignmentSpeedParams.align_speed_large = 2.0f;
InjectHooks(this, pDriverContext);
server.Run();
shmem.Create(OPENVR_SPACECALIBRATOR_SHMEM_NAME);
debugTransform = Eigen::Vector3d::Zero();
debugRotation = Eigen::Quaterniond::Identity();
return vr::VRInitError_None;
}
void ServerTrackedDeviceProvider::Cleanup()
{
TRACE("ServerTrackedDeviceProvider::Cleanup()");
server.Stop();
shmem.Close();
DisableHooks();
VR_CLEANUP_SERVER_DRIVER_CONTEXT();
}
namespace {
vr::HmdQuaternion_t convert(const Eigen::Quaterniond& q) {
vr::HmdQuaternion_t result;
result.w = q.w();
result.x = q.x();
result.y = q.y();
result.z = q.z();
return result;
}
vr::HmdVector3_t convert(const Eigen::Vector3d& v) {
vr::HmdVector3_t result;
result.v[0] = (float) v.x();
result.v[1] = (float) v.y();
result.v[2] = (float) v.z();
return result;
}
Eigen::Quaterniond convert(const vr::HmdQuaternion_t& q) {
return Eigen::Quaterniond(q.w, q.x, q.y, q.z);
}
Eigen::Vector3d convert(const vr::HmdVector3d_t& v) {
return Eigen::Vector3d(v.v[0], v.v[1], v.v[2]);
}
Eigen::Vector3d convert(const double* arr) {
return Eigen::Vector3d(arr[0], arr[1], arr[2]);
}
IsoTransform toIsoWorldTransform(const vr::DriverPose_t& pose) {
Eigen::Quaterniond rot(pose.qWorldFromDriverRotation.w, pose.qWorldFromDriverRotation.x, pose.qWorldFromDriverRotation.y, pose.qWorldFromDriverRotation.z);
Eigen::Vector3d trans(pose.vecWorldFromDriverTranslation[0], pose.vecWorldFromDriverTranslation[1], pose.vecWorldFromDriverTranslation[2]);
return IsoTransform(rot, trans);
}
IsoTransform toIsoPose(const vr::DriverPose_t& pose) {
auto worldXform = toIsoWorldTransform(pose);
Eigen::Quaterniond rot(pose.qRotation.w, pose.qRotation.x, pose.qRotation.y, pose.qRotation.z);
Eigen::Vector3d trans(pose.vecPosition[0], pose.vecPosition[1], pose.vecPosition[2]);
return worldXform * IsoTransform(rot, trans);
}
}
/**
* This function heuristically evaluates the amount of drift between the src and target playspace transforms,
* evaluated centered on the `pose` device transform. This is then used to control the speed of realignment.
*/
ServerTrackedDeviceProvider::DeltaSize ServerTrackedDeviceProvider::GetTransformDeltaSize(
DeltaSize prior_delta,
const IsoTransform& deviceWorldPose,
const IsoTransform& src,
const IsoTransform& target
) const {
const auto src_pose = src * deviceWorldPose;
const auto target_pose = target * deviceWorldPose;
const auto trans_delta = (src_pose.translation - target_pose.translation).squaredNorm();
const auto rot_delta = src_pose.rotation.angularDistance(target_pose.rotation);
DeltaSize trans_level, rot_level;
if (trans_delta > alignmentSpeedParams.thr_trans_large) trans_level = DeltaSize::LARGE;
else if (trans_delta > alignmentSpeedParams.thr_trans_small) trans_level = DeltaSize::SMALL;
else trans_level = DeltaSize::TINY;
if (rot_delta > alignmentSpeedParams.thr_rot_large) rot_level = DeltaSize::LARGE;
else if (rot_delta > alignmentSpeedParams.thr_rot_small) rot_level = DeltaSize::SMALL;
else rot_level = DeltaSize::TINY;
if (trans_level == DeltaSize::TINY && rot_level == DeltaSize::TINY) return DeltaSize::TINY;
else return max(prior_delta, max(trans_level, rot_level));
}
double ServerTrackedDeviceProvider::GetTransformRate(DeltaSize delta) const {
switch (delta) {
case DeltaSize::TINY: return alignmentSpeedParams.align_speed_tiny;
case DeltaSize::SMALL: return alignmentSpeedParams.align_speed_small;
default: return alignmentSpeedParams.align_speed_large;
}
}
/**
* Smoothly interpolates the device active transform towards the target transform.
*/
void ServerTrackedDeviceProvider::BlendTransform(DeviceTransform& device, const IsoTransform &deviceWorldPose) const {
LARGE_INTEGER timestamp, freq;
QueryPerformanceCounter(&timestamp);
QueryPerformanceFrequency(&freq);
double lerp = (timestamp.QuadPart - device.lastPoll.QuadPart) / (double)freq.QuadPart;
device.lastPoll = timestamp;
lerp *= GetTransformRate(device.currentRate);
if (lerp > 1.0)
lerp = 1.0;
if (lerp < 0 || isnan(lerp))
lerp = 0;
device.transform = device.transform.interpolateAround(lerp, device.targetTransform, deviceWorldPose.translation);
}
void ServerTrackedDeviceProvider::ApplyTransform(DeviceTransform& device, vr::DriverPose_t& devicePose) const {
auto deviceWorldTransform = toIsoWorldTransform(devicePose);
deviceWorldTransform = device.transform * deviceWorldTransform;
devicePose.vecWorldFromDriverTranslation[0] = deviceWorldTransform.translation(0);
devicePose.vecWorldFromDriverTranslation[1] = deviceWorldTransform.translation(1);
devicePose.vecWorldFromDriverTranslation[2] = deviceWorldTransform.translation(2);
devicePose.qWorldFromDriverRotation = convert(deviceWorldTransform.rotation);
}
inline vr::HmdQuaternion_t operator*(const vr::HmdQuaternion_t &lhs, const vr::HmdQuaternion_t &rhs) {
return {
(lhs.w * rhs.w) - (lhs.x * rhs.x) - (lhs.y * rhs.y) - (lhs.z * rhs.z),
(lhs.w * rhs.x) + (lhs.x * rhs.w) + (lhs.y * rhs.z) - (lhs.z * rhs.y),
(lhs.w * rhs.y) + (lhs.y * rhs.w) + (lhs.z * rhs.x) - (lhs.x * rhs.z),
(lhs.w * rhs.z) + (lhs.z * rhs.w) + (lhs.x * rhs.y) - (lhs.y * rhs.x)
};
}
inline vr::HmdVector3d_t quaternionRotateVector(const vr::HmdQuaternion_t& quat, const double(&vector)[3]) {
vr::HmdQuaternion_t vectorQuat = { 0.0, vector[0], vector[1] , vector[2] };
vr::HmdQuaternion_t conjugate = { quat.w, -quat.x, -quat.y, -quat.z };
auto rotatedVectorQuat = quat * vectorQuat * conjugate;
return { rotatedVectorQuat.x, rotatedVectorQuat.y, rotatedVectorQuat.z };
}
void ServerTrackedDeviceProvider::SetDeviceTransform(const protocol::SetDeviceTransform& newTransform)
{
auto &tf = transforms[newTransform.openVRID];
tf.enabled = newTransform.enabled;
if (newTransform.updateTranslation) {
tf.targetTransform.translation = convert(newTransform.translation);
if (!newTransform.lerp) {
tf.transform.translation = tf.targetTransform.translation;
}
}
if (newTransform.updateRotation) {
tf.targetTransform.rotation = convert(newTransform.rotation);
if (!newTransform.lerp) {
tf.transform.rotation = tf.targetTransform.rotation;
}
}
if (newTransform.updateScale)
tf.scale = newTransform.scale;
tf.quash = newTransform.quash;
}
bool ServerTrackedDeviceProvider::HandleDevicePoseUpdated(uint32_t openVRID, vr::DriverPose_t &pose)
{
// Apply debug pose before anything else
if (openVRID > 0) {
auto dbgPos = convert(pose.vecPosition) + debugTransform;
auto dbgRot = convert(pose.qRotation) * debugRotation;
pose.qRotation = convert(dbgRot);
pose.vecPosition[0] = dbgPos(0);
pose.vecPosition[1] = dbgPos(1);
pose.vecPosition[2] = dbgPos(2);
}
shmem.SetPose(openVRID, pose);
auto& tf = transforms[openVRID];
if (tf.quash) {
pose.vecPosition[0] = -pose.vecWorldFromDriverTranslation[0];
pose.vecPosition[1] = -pose.vecWorldFromDriverTranslation[1] + 9001; // put it 9001m above the origin
pose.vecPosition[2] = -pose.vecWorldFromDriverTranslation[2];
} else if (tf.enabled)
{
// @TODO: Offset, scale, and re-offset
pose.vecPosition[0] *= tf.scale;
pose.vecPosition[1] *= tf.scale;
pose.vecPosition[2] *= tf.scale;
auto deviceWorldPose = toIsoPose(pose);
tf.currentRate = GetTransformDeltaSize(tf.currentRate, deviceWorldPose, tf.transform, tf.targetTransform);
double lerp = GetTransformRate(tf.currentRate);
BlendTransform(tf, deviceWorldPose);
ApplyTransform(tf, pose);
}
return true;
}
void ServerTrackedDeviceProvider::HandleApplyRandomOffset() {
std::random_device gen;
std::uniform_real_distribution<double> d(-1, 1);
auto init = Eigen::Vector3d(d(gen), d(gen), d(gen));
auto posOffset = init * 0.25f;
debugTransform = posOffset;
debugRotation = Eigen::Quaterniond::Identity();
std::ostringstream oss;
oss << "Applied random offset: " << posOffset << " from init " << init << std::endl;
LOG("%s", oss.str().c_str());
}
@@ -0,0 +1,91 @@
#pragma once
#define EIGEN_MPL2_ONLY
#include "IPCServer.h"
#include "../Protocol.h"
#include "IsometryTransform.h"
#include <Eigen/Dense>
#include <openvr_driver.h>
class ServerTrackedDeviceProvider : public vr::IServerTrackedDeviceProvider
{
public:
////// Start vr::IServerTrackedDeviceProvider functions
/** initializes the driver. This will be called before any other methods are called. */
virtual vr::EVRInitError Init(vr::IVRDriverContext *pDriverContext) override;
/** cleans up the driver right before it is unloaded */
virtual void Cleanup() override;
/** Returns the version of the ITrackedDeviceServerDriver interface used by this driver */
virtual const char * const *GetInterfaceVersions() { return vr::k_InterfaceVersions; }
/** Allows the driver do to some work in the main loop of the server. */
virtual void RunFrame() { }
/** Returns true if the driver wants to block Standby mode. */
virtual bool ShouldBlockStandbyMode() { return false; }
/** Called when the system is entering Standby mode. The driver should switch itself into whatever sort of low-power
* state it has. */
virtual void EnterStandby() { }
/** Called when the system is leaving Standby mode. The driver should switch itself back to
full operation. */
virtual void LeaveStandby() { }
////// End vr::IServerTrackedDeviceProvider functions
ServerTrackedDeviceProvider() : server(this) { }
void SetDeviceTransform(const protocol::SetDeviceTransform &newTransform);
bool HandleDevicePoseUpdated(uint32_t openVRID, vr::DriverPose_t &pose);
void HandleApplyRandomOffset();
void HandleSetAlignmentSpeedParams(const protocol::AlignmentSpeedParams params) {
alignmentSpeedParams = params;
}
private:
IPCServer server;
protocol::DriverPoseShmem shmem;
enum DeltaSize {
TINY,
SMALL,
LARGE
};
struct DeviceTransform
{
bool enabled = false;
bool quash = false;
IsoTransform transform, targetTransform;
double scale;
LARGE_INTEGER lastPoll;
DeltaSize currentRate = DeltaSize::TINY;
};
DeviceTransform transforms[vr::k_unMaxTrackedDeviceCount];
Eigen::Vector3d debugTransform;
Eigen::Quaterniond debugRotation;
DeltaSize currentDeltaSpeed[vr::k_unMaxTrackedDeviceCount];
protocol::AlignmentSpeedParams alignmentSpeedParams;
DeltaSize GetTransformDeltaSize(
DeltaSize prior_delta,
const IsoTransform& deviceWorldPose,
const IsoTransform& src,
const IsoTransform& target
) const;
double GetTransformRate(DeltaSize delta) const;
void BlendTransform(DeviceTransform& device, const IsoTransform& deviceWorldPose) const;
void ApplyTransform(DeviceTransform& device, vr::DriverPose_t& devicePose) const;
};
@@ -0,0 +1,19 @@
#pragma once
#include <openvr_driver.h>
class VRWatchdogProvider : public vr::IVRWatchdogProvider
{
/** initializes the driver in watchdog mode. */
virtual vr::EVRInitError Init(vr::IVRDriverContext *pDriverContext)
{
VR_INIT_WATCHDOG_DRIVER_CONTEXT(pDriverContext);
return vr::VRInitError_None;
}
/** cleans up the driver right before it is unloaded */
virtual void Cleanup()
{
VR_CLEANUP_WATCHDOG_DRIVER_CONTEXT()
}
};
+25
View File
@@ -0,0 +1,25 @@
#include "Logging.h"
#include "../Version.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <cstdio>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
OpenLogFile();
LOG("OpenVR-SpaceCalibratorDriver " SPACECAL_VERSION_STRING " loaded");
break;
case DLL_PROCESS_DETACH:
LOG("OpenVR-SpaceCalibratorDriver unloaded");
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
+362
View File
@@ -0,0 +1,362 @@
#pragma once
#include <windows.h>
#include <cstdint>
#include <atomic>
#include <stdexcept>
#include <functional>
#ifndef _OPENVR_API
#include <openvr_driver.h>
#endif
#define OPENVR_SPACECALIBRATOR_PIPE_NAME "\\\\.\\pipe\\OpenVRSpaceCalibratorDriver"
#define OPENVR_SPACECALIBRATOR_SHMEM_NAME "OpenVRSpaceCalibratorPoseMemoryV1"
#ifdef _OPENVR_API
namespace vr {
// We can't include openvr_driver.h as it will result in multiple definition of some structures.
// However, we need to share driver-specific structures with the client application, so duplicate them
// here.
struct DriverPose_t
{
/* Time offset of this pose, in seconds from the actual time of the pose,
* relative to the time of the PoseUpdated() call made by the driver.
*/
double poseTimeOffset;
/* Generally, the pose maintained by a driver
* is in an inertial coordinate system different
* from the world system of x+ right, y+ up, z+ back.
* Also, the driver is not usually tracking the "head" position,
* but instead an internal IMU or another reference point in the HMD.
* The following two transforms transform positions and orientations
* to app world space from driver world space,
* and to HMD head space from driver local body space.
*
* We maintain the driver pose state in its internal coordinate system,
* so we can do the pose prediction math without having to
* use angular acceleration. A driver's angular acceleration is generally not measured,
* and is instead calculated from successive samples of angular velocity.
* This leads to a noisy angular acceleration values, which are also
* lagged due to the filtering required to reduce noise to an acceptable level.
*/
vr::HmdQuaternion_t qWorldFromDriverRotation;
double vecWorldFromDriverTranslation[3];
vr::HmdQuaternion_t qDriverFromHeadRotation;
double vecDriverFromHeadTranslation[3];
/* State of driver pose, in meters and radians. */
/* Position of the driver tracking reference in driver world space
* +[0] (x) is right
* +[1] (y) is up
* -[2] (z) is forward
*/
double vecPosition[3];
/* Velocity of the pose in meters/second */
double vecVelocity[3];
/* Acceleration of the pose in meters/second */
double vecAcceleration[3];
/* Orientation of the tracker, represented as a quaternion */
vr::HmdQuaternion_t qRotation;
/* Angular velocity of the pose in axis-angle
* representation. The direction is the angle of
* rotation and the magnitude is the angle around
* that axis in radians/second. */
double vecAngularVelocity[3];
/* Angular acceleration of the pose in axis-angle
* representation. The direction is the angle of
* rotation and the magnitude is the angle around
* that axis in radians/second^2. */
double vecAngularAcceleration[3];
ETrackingResult result;
bool poseIsValid;
bool willDriftInYaw;
bool shouldApplyHeadModel;
bool deviceIsConnected;
};
}
#endif
namespace protocol
{
const uint32_t Version = 4;
enum RequestType
{
RequestInvalid,
RequestHandshake,
RequestSetDeviceTransform,
RequestSetAlignmentSpeedParams,
RequestDebugOffset
};
enum ResponseType
{
ResponseInvalid,
ResponseHandshake,
ResponseSuccess,
};
struct Protocol
{
uint32_t version = Version;
};
struct AlignmentSpeedParams
{
/**
* The threshold at which we adjust the alignment speed based on the position offset
* between current and target calibrations. Generally, we increase the speed if we go
* above small/large, and decrease it only once it's under tiny.
*
* These values are expressed as distance squared
*/
double thr_trans_tiny, thr_trans_small, thr_trans_large;
/**
* Similar thresholds for rotation offsets, in radians
*/
double thr_rot_tiny, thr_rot_small, thr_rot_large;
/**
* The speed of alignment, expressed as a lerp/slerp factor. 1 will blend most of the way in <1 second.
* (We actually do a lerp(s * delta_t) where s is the speed factor here)
*/
double align_speed_tiny, align_speed_small, align_speed_large;
};
struct SetDeviceTransform
{
uint32_t openVRID;
bool enabled;
bool updateTranslation;
bool updateRotation;
bool updateScale;
vr::HmdVector3d_t translation;
vr::HmdQuaternion_t rotation;
double scale;
bool lerp;
bool quash;
SetDeviceTransform(uint32_t id, bool enabled) :
openVRID(id), enabled(enabled), updateTranslation(false), updateRotation(false), updateScale(false), lerp(false), quash(false) { }
SetDeviceTransform(uint32_t id, bool enabled, vr::HmdVector3d_t translation) :
openVRID(id), enabled(enabled), updateTranslation(true), updateRotation(false), updateScale(false), translation(translation), lerp(false), quash(false) { }
SetDeviceTransform(uint32_t id, bool enabled, vr::HmdQuaternion_t rotation) :
openVRID(id), enabled(enabled), updateTranslation(false), updateRotation(true), updateScale(false), rotation(rotation), lerp(false), quash(false) { }
SetDeviceTransform(uint32_t id, bool enabled, double scale) :
openVRID(id), enabled(enabled), updateTranslation(false), updateRotation(false), updateScale(true), scale(scale), lerp(false), quash(false) { }
SetDeviceTransform(uint32_t id, bool enabled, vr::HmdVector3d_t translation, vr::HmdQuaternion_t rotation) :
openVRID(id), enabled(enabled), updateTranslation(true), updateRotation(true), updateScale(false), translation(translation), rotation(rotation), lerp(false), quash(false) { }
SetDeviceTransform(uint32_t id, bool enabled, vr::HmdVector3d_t translation, vr::HmdQuaternion_t rotation, double scale) :
openVRID(id), enabled(enabled), updateTranslation(true), updateRotation(true), updateScale(true), translation(translation), rotation(rotation), scale(scale), lerp(false), quash(false) { }
};
struct Request
{
RequestType type;
union {
SetDeviceTransform setDeviceTransform;
AlignmentSpeedParams setAlignmentSpeedParams;
};
Request() : type(RequestInvalid) { }
Request(RequestType type) : type(type) { }
Request(AlignmentSpeedParams params) : type(RequestType::RequestSetAlignmentSpeedParams), setAlignmentSpeedParams(params) {}
};
struct Response
{
ResponseType type;
union {
Protocol protocol;
};
Response() : type(ResponseInvalid) { }
Response(ResponseType type) : type(type) { }
};
class DriverPoseShmem {
public:
struct AugmentedPose {
LARGE_INTEGER sample_time;
int deviceId;
vr::DriverPose_t pose;
};
private:
static const uint32_t SYNC_ACTIVE_POSE_B = 0x80000000;
static const uint32_t BUFFERED_SAMPLES = 64 * 1024;
struct ShmemData {
std::atomic<uint64_t> index;
AugmentedPose poses[BUFFERED_SAMPLES];
};
private:
HANDLE hMapFile;
ShmemData* pData;
uint64_t cursor;
AugmentedPose lastPose[vr::k_unMaxTrackedDeviceCount];
std::string LastErrorString(DWORD lastError)
{
LPSTR buffer = nullptr;
size_t size = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buffer, 0, NULL
);
std::string message(buffer, size);
LocalFree(buffer);
return message;
}
public:
operator bool() const {
return pData != nullptr;
}
bool operator!() const {
return pData == nullptr;
}
DriverPoseShmem() {
hMapFile = INVALID_HANDLE_VALUE;
pData = nullptr;
cursor = 0;
}
~DriverPoseShmem() {
Close();
}
void Close() {
if (pData) UnmapViewOfFile(pData);
if (hMapFile) CloseHandle(hMapFile);
}
bool Create(LPCSTR segment_name) {
Close();
hMapFile = CreateFileMappingA(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
sizeof(ShmemData),
segment_name
);
if (!hMapFile) return false;
pData = reinterpret_cast<ShmemData*>(MapViewOfFile(
hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
sizeof(ShmemData)
));
return !!pData;
}
void Open(LPCSTR segment_name) {
Close();
hMapFile = OpenFileMappingA(
FILE_MAP_ALL_ACCESS,
FALSE,
segment_name
);
if (!hMapFile) {
throw std::runtime_error("Failed to open pose data shared memory segment: " + LastErrorString(GetLastError()));
}
pData = reinterpret_cast<ShmemData*>(MapViewOfFile(
hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
sizeof(ShmemData)
));
if (!pData) {
throw std::runtime_error("Failed to map pose data shared memory segment: " + LastErrorString(GetLastError()));
}
char tmp[256];
snprintf(tmp, sizeof tmp, "Opened shmem segment: %p\n", pData);
OutputDebugStringA(tmp);
}
void ReadNewPoses(std::function<void(AugmentedPose const&)> cb) {
if (!pData) throw std::runtime_error("Not open");
uint64_t cur_index = pData->index.load(std::memory_order_acquire);
if (cur_index < cursor || cur_index - cursor > BUFFERED_SAMPLES / 2) {
if (cur_index < BUFFERED_SAMPLES / 2)
cursor = cur_index;
else
cursor = cur_index - BUFFERED_SAMPLES / 2;
}
while (cursor < cur_index) {
cb(pData->poses[cursor % BUFFERED_SAMPLES]);
cursor++;
}
std::atomic_thread_fence(std::memory_order_release);
}
bool GetPose(int index, vr::DriverPose_t& pose, LARGE_INTEGER *pSampleTime = NULL) {
ReadNewPoses([this](AugmentedPose const& pose) {
if (pose.pose.poseIsValid) {
this->lastPose[pose.deviceId] = pose;
}
});
if (index >= 0 && index < vr::k_unMaxTrackedDeviceCount) {
pose = lastPose[index].pose;
if (pSampleTime) *pSampleTime = lastPose[index].sample_time;
return true;
}
}
void SetPose(int index, const vr::DriverPose_t& pose) {
if (index >= vr::k_unMaxTrackedDeviceCount) return;
if (pData == nullptr) return;
AugmentedPose augPose;
augPose.deviceId = index;
augPose.pose = pose;
QueryPerformanceCounter(&augPose.sample_time);
uint64_t cur_index = pData->index.load(std::memory_order_relaxed) + 1;
pData->poses[cur_index % BUFFERED_SAMPLES] = augPose;
pData->index.store(cur_index, std::memory_order_release);
}
};
}
+55 -31
View File
@@ -1,52 +1,76 @@
# OpenVR-SpaceCalibrator
# OpenVR Space Calibrator
Use VR devices from one company with any other.
This helps you use tracked VR devices from one company with any other. It aligns multiple tracking systems with a quick calibration step. It may not work for your setup, but there are many cases that work to a degree, and some work very well.
This is **beta software** and may not work for you. A quick video walkthrough of the calibration process is available at https://www.youtube.com/watch?v=W3TnQd9JMl4
- Rift CV1 x Vive devices: works very well with the v2 (blue logo) trackers, v1 trackers (grey logo, not in production) have major interference issues in the IR spectrum, controller wands (both gen) and Index controllers work very well.
- Rift S, Quest, Windows MR, other SLAM inside-out tracked HMDs x Vive devices: works very well when you aren't moving around the room far (e.g. Beat Saber) but a lot of walking around causes a nontrivial amount of drift between systems. Your results may vary depending on your space. It's possible some of this can be fixed in software with a better calibration algorithm.
- Quest wireless streaming is particularly bad right now and requires frequent recalibration, but it does work for a short time until one of many factors causes it to drift. With wireless devices, moving slowly when calibrating and using the Slow or Very Slow calibration modes is effective at reducing the initial error.
- Any non-Rift HMD x Touch controllers: does not work, the Oculus driver requires the HMD is a Rift. It's theoretically possible to work around this in software but as far as I know it hasn't been done as it would require a fair amount of reverse engineering effort.
## Usage
There is a community of a few thousand on [**Discord**](https://discord.gg/m7g2Wyj) and a newer community on [**Reddit**](https://www.reddit.com/r/MixedVR/). You may find the answer to your question in [the **wiki**](https://github.com/pushrax/OpenVR-SpaceCalibrator/wiki).
A quick video of how this works using an old version (~v0.3) is available at https://www.youtube.com/watch?v=W3TnQd9JMl4. The user interface has been upgraded since then; the calibration is now done via a SteamVR dashboard menu, and there's much more configurability.
### Install
Before following the directions below, download and run the installer for the [latest release](https://github.com/hyblocker/OpenVR-SpaceCalibrator/releases/latest). This will automatically set up SteamVR for use with multiple tracking systems (`activateMultipleDrivers: true`). There are many guides that say you need to edit the SteamVR config manually. You do not.
### Usage
Once Space Calibrator has a calibration, it works in the background to keep your devices configured correctly. Since v0.8, everything aside from creating the calibration is automated.
### Calibration
If you don't already run a setup with multiple device types, see [Setting up SteamVR](#setting-up-steamvr).
This fork supports continuous calibration. This means that there are two ways to calibrate:
0. Install [OpenVR-InputEmulator](https://github.com/matzman666/OpenVR-InputEmulator).
1. Download and unzip the [latest release](https://github.com/pushrax/OpenVR-SpaceCalibrator/releases) of OpenVR-SpaceCalibrator.
2. Run SteamVR, and turn on your Touch controllers and only one Vive device to use for calibration.
3. Run OpenVR-SpaceCalibrator.
4. Hold the left Touch controller and your Vive device in your left hand securely, like they're glued together.
5. Click "Start Calibration"
6. Wave your left hand around, like you're calibrating the compass on your phone. You want to get as many orientations as possible.
7. Done! A profile will be saved automatically. You can turn on the rest of your Vive devices now.
#### 1. Normal Calibration
Next time you run SteamVR and OpenVR-InputEmulator it will load the calibration automatically and apply it to any Vive devices you turn on.
> Use this if you do not have a tracker on your VR headset.
### Setting up SteamVR
As part of first time setup, or when you make a change to your space (e.g. move a sensor), and occasionally as the calibration drifts over time (consumer VR tracking isn't perfectly stable), you'll need to run a calibration:
Every hardware designer with their own tracking system needs to make a "driver"
so SteamVR can see their tracking data. SteamVR by default will load only one driver at a time,
but we can tell it to load all of them by editing the vrsettings config file.
1. Copy the chaperone/guardian bounds from your HMD's play space. This doesn't need to be run if your HMD's play space hasn't changed since last time you copied it. __Example:__ if you're using the Rift with Vive trackers and you bump a Vive lighthouse, or if the calibration has just drifted a little, you likely don't need to run this step, but if you bump an Oculus sensor you will (after running Oculus guardian setup again).
1. Run SteamVR, with only devices from your HMD's tracking system powered on. __Example:__ for Rift with Vive trackers, don't turn on the trackers yet.
2. Confirm your chaperone/guardian is set up with the walls in the right place. If you change it later, you need to run step again.
3. Open SPACE CAL in the SteamVR dashboard overlay.
4. Click `Copy Chaperone Bounds to profile`
Open `Steam\steamapps\common\SteamVR\resources\settings\default.vrsettings` in a text editor,
look for the line that has `"activateMultipleDrivers": false` and change the `false` to `true`.
In some guides online you may also see references to `requireHmd`, this does _not_ need to be changed
unless you truly want to be able to run without any kind of HMD.
2. Calibrate devices.
1. Open SteamVR if you haven't already. Turn on some or all your devices.
2. Open SPACE CAL in the SteamVR dashboard overlay.
3. Select one device from the reference space on the left and one device from the target space on the right. If you turned on multiple devices from one space and can't tell which one is selected, click "Identify selected devices" to blink an LED or vibrate it. __Example:__ for Rift with Vive trackers, you'll see the Touch controllers on the left, and Vive trackers on the right. __Pro tip:__ if you turn on just one Vive tracker, you don't have to figure out which one is selected.
4. Hold these two devices in one hand, like they're glued together. If they slip, calibration won't work as well.
5. Click `Start Calibration`
6. Move and rotate your hand around slowly a few times, like you're calibrating the compass on your phone. You want to sample as many orientations as possible.
7. Done! A profile will be saved automatically. If you haven't already, turn on all your devices. Space Calibrator will automatically apply the calibration to devices as they turn on.
Sometimes when SteamVR updates this file seems to get wiped, if your setup stops working you might
have to edit the config again.
#### 2. Continuous Calibration
### Manually editing the calibration
> Use this only if you have a tracker on your VR headset.
If you'd like to make a manual change to the calibration, the values are in `openvr_space_calibration.txt` in the same folder as the exe.
The first 3 numbers are the rotation (yaw, pitch, roll) in degrees, and the next 3 numbers are the translation (x, y, z) in centimeters.
Continuous calibration allows you to calibrate playspaces continuously, eliminating the need to do any of the work above.
1. Start SteamVR with the VR headset you wish to use.
2. Turn on **ONLY** the tracker which is attached on the VR headset.
3. Select the VR headset and tracker and calibrate.
4. Turn on your other devices.
5. You should see them line up with you as you after moving around your playspace for a bit for an initial calibration.
### Calibration outside VR
You can calibrate without using the dashboard overlay by unminimizing Space Calibrator after opening SteamVR (it starts minimized). This is required if you're calibrating for a lone HMD without any devices in its tracking system.
### Compiling your own build
1. Install boost 1.63 to `lib/boost_1_63_0` (required for IPC to OpenVR-InputEmulator). https://sourceforge.net/projects/boost/files/boost-binaries/1.63.0/
2. Open `OpenVR-SpaceCalibrator.sln` in Visual Studio 2015 and build.
Open `OpenVR-SpaceCalibrator.sln` in Visual Studio 2017 and build. There are no external dependencies.
## The math
### The math
See [math.pdf](https://github.com/pushrax/OpenVR-SpaceCalibrator/blob/master/math.pdf) for details.
If you have some ideas for how to improve the calibration process, let me know!
+3
View File
@@ -0,0 +1,3 @@
#pragma once
#define SPACECAL_VERSION_STRING "1.4-contcal-r8"
+192
View File
@@ -0,0 +1,192 @@
;--------------------------------
;Include Modern UI
!include "MUI2.nsh"
;--------------------------------
;General
!define OVERLAY_BASEDIR "..\client_overlay\bin\win64"
!define DRIVER_RESDIR "..\OpenVR-SpaceCalibratorDriver\01spacecalibrator"
Name "OpenVR-SpaceCalibrator"
OutFile "OpenVR-SpaceCalibrator.exe"
InstallDir "$PROGRAMFILES64\OpenVR-SpaceCalibrator"
InstallDirRegKey HKLM "Software\OpenVR-SpaceCalibrator\Main" ""
RequestExecutionLevel admin
ShowInstDetails show
;--------------------------------
;Variables
VAR upgradeInstallation
;--------------------------------
;Interface Settings
!define MUI_ABORTWARNING
;--------------------------------
;Pages
!insertmacro MUI_PAGE_LICENSE "..\LICENSE"
!define MUI_PAGE_CUSTOMFUNCTION_PRE dirPre
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
;--------------------------------
;Languages
!insertmacro MUI_LANGUAGE "English"
;--------------------------------
;Macros
;--------------------------------
;Functions
Function dirPre
StrCmp $upgradeInstallation "true" 0 +2
Abort
FunctionEnd
Function .onInit
StrCpy $upgradeInstallation "false"
ReadRegStr $R0 HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\OpenVRSpaceCalibrator" "UninstallString"
StrCmp $R0 "" done
; If SteamVR is already running, display a warning message and exit
FindWindow $0 "Qt5QWindowIcon" "SteamVR Status"
StrCmp $0 0 +3
MessageBox MB_OK|MB_ICONEXCLAMATION \
"SteamVR is still running. Cannot install this software.$\nPlease close SteamVR and try again."
Abort
MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION \
"OpenVR-SpaceCalibrator is already installed. $\n$\nClick `OK` to upgrade the \
existing installation or `Cancel` to cancel this upgrade." \
IDOK upgrade
Abort
upgrade:
StrCpy $upgradeInstallation "true"
done:
FunctionEnd
;--------------------------------
;Installer Sections
Section "Install" SecInstall
StrCmp $upgradeInstallation "true" 0 noupgrade
DetailPrint "Uninstall previous version..."
ExecWait '"$INSTDIR\Uninstall.exe" /S _?=$INSTDIR'
Delete $INSTDIR\Uninstall.exe
Goto afterupgrade
noupgrade:
afterupgrade:
SetOutPath "$INSTDIR"
File "..\LICENSE"
File "..\x64\Release\OpenVR-SpaceCalibrator.exe"
File "..\lib\openvr\lib\win64\openvr_api.dll"
File "..\OpenVR-SpaceCalibrator\manifest.vrmanifest"
File "..\OpenVR-SpaceCalibrator\icon.png"
ExecWait '"$INSTDIR\vcredist_x64.exe" /install /quiet'
Var /GLOBAL vrRuntimePath
nsExec::ExecToStack '"$INSTDIR\OpenVR-SpaceCalibrator.exe" -openvrpath'
Pop $0
Pop $vrRuntimePath
DetailPrint "VR runtime path: $vrRuntimePath"
; Old beta driver
StrCmp $upgradeInstallation "true" 0 nocleanupbeta
Delete "$vrRuntimePath\drivers\000spacecalibrator\driver.vrdrivermanifest"
Delete "$vrRuntimePath\drivers\000spacecalibrator\resources\driver.vrresources"
Delete "$vrRuntimePath\drivers\000spacecalibrator\resources\settings\default.vrsettings"
Delete "$vrRuntimePath\drivers\000spacecalibrator\bin\win64\driver_000spacecalibrator.dll"
Delete "$vrRuntimePath\drivers\000spacecalibrator\bin\win64\space_calibrator_driver.log"
RMdir "$vrRuntimePath\drivers\000spacecalibrator\resources\settings"
RMdir "$vrRuntimePath\drivers\000spacecalibrator\resources\"
RMdir "$vrRuntimePath\drivers\000spacecalibrator\bin\win64\"
RMdir "$vrRuntimePath\drivers\000spacecalibrator\bin\"
RMdir "$vrRuntimePath\drivers\000spacecalibrator\"
nocleanupbeta:
SetOutPath "$vrRuntimePath\drivers\01spacecalibrator"
File "${DRIVER_RESDIR}\driver.vrdrivermanifest"
SetOutPath "$vrRuntimePath\drivers\01spacecalibrator\resources"
File "${DRIVER_RESDIR}\resources\driver.vrresources"
SetOutPath "$vrRuntimePath\drivers\01spacecalibrator\resources\settings"
File "${DRIVER_RESDIR}\resources\settings\default.vrsettings"
SetOutPath "$vrRuntimePath\drivers\01spacecalibrator\bin\win64"
File "..\x64\Release\driver_01spacecalibrator.dll"
WriteRegStr HKLM "Software\OpenVR-SpaceCalibrator\Main" "" $INSTDIR
WriteRegStr HKLM "Software\OpenVR-SpaceCalibrator\Driver" "" $vrRuntimePath
WriteUninstaller "$INSTDIR\Uninstall.exe"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\OpenVRSpaceCalibrator" "DisplayName" "OpenVR-SpaceCalibrator"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\OpenVRSpaceCalibrator" "UninstallString" "$\"$INSTDIR\Uninstall.exe$\""
CreateShortCut "$SMPROGRAMS\OpenVR-SpaceCalibrator.lnk" "$INSTDIR\OpenVR-SpaceCalibrator.exe"
SetOutPath "$INSTDIR"
nsExec::ExecToLog '"$INSTDIR\OpenVR-SpaceCalibrator.exe" -installmanifest'
nsExec::ExecToLog '"$INSTDIR\OpenVR-SpaceCalibrator.exe" -activatemultipledrivers'
SectionEnd
;--------------------------------
;Uninstaller Section
Section "Uninstall"
; If SteamVR is already running, display a warning message and exit
FindWindow $0 "Qt5QWindowIcon" "SteamVR Status"
StrCmp $0 0 +3
MessageBox MB_OK|MB_ICONEXCLAMATION \
"SteamVR is still running. Cannot uninstall this software.$\nPlease close SteamVR and try again."
Abort
SetOutPath "$INSTDIR"
nsExec::ExecToLog '"$INSTDIR\OpenVR-SpaceCalibrator.exe" -removemanifest'
Var /GLOBAL vrRuntimePath2
ReadRegStr $vrRuntimePath2 HKLM "Software\OpenVR-SpaceCalibrator\Driver" ""
DetailPrint "VR runtime path: $vrRuntimePath2"
Delete "$vrRuntimePath2\drivers\01spacecalibrator\driver.vrdrivermanifest"
Delete "$vrRuntimePath2\drivers\01spacecalibrator\resources\driver.vrresources"
Delete "$vrRuntimePath2\drivers\01spacecalibrator\resources\settings\default.vrsettings"
Delete "$vrRuntimePath2\drivers\01spacecalibrator\bin\win64\driver_01spacecalibrator.dll"
Delete "$vrRuntimePath2\drivers\01spacecalibrator\bin\win64\space_calibrator_driver.log"
RMdir "$vrRuntimePath2\drivers\01spacecalibrator\resources\settings"
RMdir "$vrRuntimePath2\drivers\01spacecalibrator\resources\"
RMdir "$vrRuntimePath2\drivers\01spacecalibrator\bin\win64\"
RMdir "$vrRuntimePath2\drivers\01spacecalibrator\bin\"
RMdir "$vrRuntimePath2\drivers\01spacecalibrator\"
Delete "$INSTDIR\LICENSE"
Delete "$INSTDIR\OpenVR-SpaceCalibrator.exe"
Delete "$INSTDIR\openvr_api.dll"
Delete "$INSTDIR\manifest.vrmanifest"
Delete "$INSTDIR\icon.png"
DeleteRegKey HKLM "Software\OpenVR-SpaceCalibrator\Main"
DeleteRegKey HKLM "Software\OpenVR-SpaceCalibrator\Driver"
DeleteRegKey HKLM "Software\OpenVR-SpaceCalibrator"
DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\OpenVRSpaceCalibrator"
Delete "$SMPROGRAMS\OpenVR-SpaceCalibrator.lnk"
SectionEnd
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+282
View File
@@ -0,0 +1,282 @@
#ifndef __khrplatform_h_
#define __khrplatform_h_
/*
** Copyright (c) 2008-2018 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Khronos platform-specific types and definitions.
*
* The master copy of khrplatform.h is maintained in the Khronos EGL
* Registry repository at https://github.com/KhronosGroup/EGL-Registry
* The last semantic modification to khrplatform.h was at commit ID:
* 67a3e0864c2d75ea5287b9f3d2eb74a745936692
*
* Adopters may modify this file to suit their platform. Adopters are
* encouraged to submit platform specific modifications to the Khronos
* group so that they can be included in future versions of this file.
* Please submit changes by filing pull requests or issues on
* the EGL Registry repository linked above.
*
*
* See the Implementer's Guidelines for information about where this file
* should be located on your system and for more details of its use:
* http://www.khronos.org/registry/implementers_guide.pdf
*
* This file should be included as
* #include <KHR/khrplatform.h>
* by Khronos client API header files that use its types and defines.
*
* The types in khrplatform.h should only be used to define API-specific types.
*
* Types defined in khrplatform.h:
* khronos_int8_t signed 8 bit
* khronos_uint8_t unsigned 8 bit
* khronos_int16_t signed 16 bit
* khronos_uint16_t unsigned 16 bit
* khronos_int32_t signed 32 bit
* khronos_uint32_t unsigned 32 bit
* khronos_int64_t signed 64 bit
* khronos_uint64_t unsigned 64 bit
* khronos_intptr_t signed same number of bits as a pointer
* khronos_uintptr_t unsigned same number of bits as a pointer
* khronos_ssize_t signed size
* khronos_usize_t unsigned size
* khronos_float_t signed 32 bit floating point
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
* nanoseconds
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
* khronos_boolean_enum_t enumerated boolean type. This should
* only be used as a base type when a client API's boolean type is
* an enum. Client APIs which use an integer or other type for
* booleans cannot use this as the base type for their boolean.
*
* Tokens defined in khrplatform.h:
*
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
*
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
*
* Calling convention macros defined in this file:
* KHRONOS_APICALL
* KHRONOS_APIENTRY
* KHRONOS_APIATTRIBUTES
*
* These may be used in function prototypes as:
*
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
* int arg1,
* int arg2) KHRONOS_APIATTRIBUTES;
*/
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APICALL
*-------------------------------------------------------------------------
* This precedes the return type of the function in the function prototype.
*/
#if defined(_WIN32) && !defined(__SCITECH_SNAP__)
# define KHRONOS_APICALL __declspec(dllimport)
#elif defined (__SYMBIAN32__)
# define KHRONOS_APICALL IMPORT_C
#elif defined(__ANDROID__)
# define KHRONOS_APICALL __attribute__((visibility("default")))
#else
# define KHRONOS_APICALL
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIENTRY
*-------------------------------------------------------------------------
* This follows the return type of the function and precedes the function
* name in the function prototype.
*/
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
/* Win32 but not WinCE */
# define KHRONOS_APIENTRY __stdcall
#else
# define KHRONOS_APIENTRY
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIATTRIBUTES
*-------------------------------------------------------------------------
* This follows the closing parenthesis of the function prototype arguments.
*/
#if defined (__ARMCC_2__)
#define KHRONOS_APIATTRIBUTES __softfp
#else
#define KHRONOS_APIATTRIBUTES
#endif
/*-------------------------------------------------------------------------
* basic type definitions
*-----------------------------------------------------------------------*/
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
/*
* Using <stdint.h>
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__VMS ) || defined(__sgi)
/*
* Using <inttypes.h>
*/
#include <inttypes.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
/*
* Win32
*/
typedef __int32 khronos_int32_t;
typedef unsigned __int32 khronos_uint32_t;
typedef __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__sun__) || defined(__digital__)
/*
* Sun or Digital
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#if defined(__arch64__) || defined(_LP64)
typedef long int khronos_int64_t;
typedef unsigned long int khronos_uint64_t;
#else
typedef long long int khronos_int64_t;
typedef unsigned long long int khronos_uint64_t;
#endif /* __arch64__ */
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif 0
/*
* Hypothetical platform with no float or int64 support
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#define KHRONOS_SUPPORT_INT64 0
#define KHRONOS_SUPPORT_FLOAT 0
#else
/*
* Generic fallback
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#endif
/*
* Types that are (so far) the same on all platforms
*/
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
/*
* Types that differ between LLP64 and LP64 architectures - in LLP64,
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
* to be the only LLP64 architecture in current use.
*/
#ifdef _WIN64
typedef signed long long int khronos_intptr_t;
typedef unsigned long long int khronos_uintptr_t;
typedef signed long long int khronos_ssize_t;
typedef unsigned long long int khronos_usize_t;
#else
typedef signed long int khronos_intptr_t;
typedef unsigned long int khronos_uintptr_t;
typedef signed long int khronos_ssize_t;
typedef unsigned long int khronos_usize_t;
#endif
#if KHRONOS_SUPPORT_FLOAT
/*
* Float type
*/
typedef float khronos_float_t;
#endif
#if KHRONOS_SUPPORT_INT64
/* Time types
*
* These types can be used to represent a time interval in nanoseconds or
* an absolute Unadjusted System Time. Unadjusted System Time is the number
* of nanoseconds since some arbitrary system event (e.g. since the last
* time the system booted). The Unadjusted System Time is an unsigned
* 64 bit value that wraps back to 0 every 584 years. Time intervals
* may be either signed or unsigned.
*/
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
typedef khronos_int64_t khronos_stime_nanoseconds_t;
#endif
/*
* Dummy value used to pad enum types to 32 bits.
*/
#ifndef KHRONOS_MAX_ENUM
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
#endif
/*
* Enumerated boolean type
*
* Values other than zero should be considered to be true. Therefore
* comparisons should not be made against KHRONOS_TRUE.
*/
typedef enum {
KHRONOS_FALSE = 0,
KHRONOS_TRUE = 1,
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
} khronos_boolean_enum_t;
#endif /* __khrplatform_h_ */
+841
View File
@@ -0,0 +1,841 @@
/*
This file was generated with gl3w_gen.py, part of gl3w
(hosted at https://github.com/skaslev/gl3w)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include <GL/gl3w.h>
#include <stdlib.h>
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
static HMODULE libgl;
static PROC (__stdcall *wgl_get_proc_address)(LPCSTR);
static int open_libgl(void)
{
libgl = LoadLibraryA("opengl32.dll");
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
*(void **)(&wgl_get_proc_address) = GetProcAddress(libgl, "wglGetProcAddress");
return GL3W_OK;
}
static void close_libgl(void)
{
FreeLibrary(libgl);
}
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
res = (GL3WglProc)wgl_get_proc_address(proc);
if (!res)
res = (GL3WglProc)GetProcAddress(libgl, proc);
return res;
}
#elif defined(__APPLE__)
#include <dlfcn.h>
static void *libgl;
static int open_libgl(void)
{
libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
return GL3W_OK;
}
static void close_libgl(void)
{
dlclose(libgl);
}
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
*(void **)(&res) = dlsym(libgl, proc);
return res;
}
#else
#include <dlfcn.h>
static void *libgl;
static GL3WglProc (*glx_get_proc_address)(const GLubyte *);
static int open_libgl(void)
{
libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
*(void **)(&glx_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB");
return GL3W_OK;
}
static void close_libgl(void)
{
dlclose(libgl);
}
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
res = glx_get_proc_address((const GLubyte *)proc);
if (!res)
*(void **)(&res) = dlsym(libgl, proc);
return res;
}
#endif
static struct {
int major, minor;
} version;
static int parse_version(void)
{
if (!glGetIntegerv)
return GL3W_ERROR_INIT;
glGetIntegerv(GL_MAJOR_VERSION, &version.major);
glGetIntegerv(GL_MINOR_VERSION, &version.minor);
if (version.major < 3)
return GL3W_ERROR_OPENGL_VERSION;
return GL3W_OK;
}
static void load_procs(GL3WGetProcAddressProc proc);
int gl3wInit(void)
{
int res = open_libgl();
if (res)
return res;
atexit(close_libgl);
return gl3wInit2(get_proc);
}
int gl3wInit2(GL3WGetProcAddressProc proc)
{
load_procs(proc);
return parse_version();
}
int gl3wIsSupported(int major, int minor)
{
if (major < 3)
return 0;
if (version.major == major)
return version.minor >= minor;
return version.major >= major;
}
GL3WglProc gl3wGetProcAddress(const char *proc)
{
return get_proc(proc);
}
static const char *proc_names[] = {
"glActiveShaderProgram",
"glActiveTexture",
"glAttachShader",
"glBeginConditionalRender",
"glBeginQuery",
"glBeginQueryIndexed",
"glBeginTransformFeedback",
"glBindAttribLocation",
"glBindBuffer",
"glBindBufferBase",
"glBindBufferRange",
"glBindBuffersBase",
"glBindBuffersRange",
"glBindFragDataLocation",
"glBindFragDataLocationIndexed",
"glBindFramebuffer",
"glBindImageTexture",
"glBindImageTextures",
"glBindProgramPipeline",
"glBindRenderbuffer",
"glBindSampler",
"glBindSamplers",
"glBindTexture",
"glBindTextureUnit",
"glBindTextures",
"glBindTransformFeedback",
"glBindVertexArray",
"glBindVertexBuffer",
"glBindVertexBuffers",
"glBlendColor",
"glBlendEquation",
"glBlendEquationSeparate",
"glBlendEquationSeparatei",
"glBlendEquationi",
"glBlendFunc",
"glBlendFuncSeparate",
"glBlendFuncSeparatei",
"glBlendFunci",
"glBlitFramebuffer",
"glBlitNamedFramebuffer",
"glBufferData",
"glBufferStorage",
"glBufferSubData",
"glCheckFramebufferStatus",
"glCheckNamedFramebufferStatus",
"glClampColor",
"glClear",
"glClearBufferData",
"glClearBufferSubData",
"glClearBufferfi",
"glClearBufferfv",
"glClearBufferiv",
"glClearBufferuiv",
"glClearColor",
"glClearDepth",
"glClearDepthf",
"glClearNamedBufferData",
"glClearNamedBufferSubData",
"glClearNamedFramebufferfi",
"glClearNamedFramebufferfv",
"glClearNamedFramebufferiv",
"glClearNamedFramebufferuiv",
"glClearStencil",
"glClearTexImage",
"glClearTexSubImage",
"glClientWaitSync",
"glClipControl",
"glColorMask",
"glColorMaski",
"glCompileShader",
"glCompressedTexImage1D",
"glCompressedTexImage2D",
"glCompressedTexImage3D",
"glCompressedTexSubImage1D",
"glCompressedTexSubImage2D",
"glCompressedTexSubImage3D",
"glCompressedTextureSubImage1D",
"glCompressedTextureSubImage2D",
"glCompressedTextureSubImage3D",
"glCopyBufferSubData",
"glCopyImageSubData",
"glCopyNamedBufferSubData",
"glCopyTexImage1D",
"glCopyTexImage2D",
"glCopyTexSubImage1D",
"glCopyTexSubImage2D",
"glCopyTexSubImage3D",
"glCopyTextureSubImage1D",
"glCopyTextureSubImage2D",
"glCopyTextureSubImage3D",
"glCreateBuffers",
"glCreateFramebuffers",
"glCreateProgram",
"glCreateProgramPipelines",
"glCreateQueries",
"glCreateRenderbuffers",
"glCreateSamplers",
"glCreateShader",
"glCreateShaderProgramv",
"glCreateTextures",
"glCreateTransformFeedbacks",
"glCreateVertexArrays",
"glCullFace",
"glDebugMessageCallback",
"glDebugMessageControl",
"glDebugMessageInsert",
"glDeleteBuffers",
"glDeleteFramebuffers",
"glDeleteProgram",
"glDeleteProgramPipelines",
"glDeleteQueries",
"glDeleteRenderbuffers",
"glDeleteSamplers",
"glDeleteShader",
"glDeleteSync",
"glDeleteTextures",
"glDeleteTransformFeedbacks",
"glDeleteVertexArrays",
"glDepthFunc",
"glDepthMask",
"glDepthRange",
"glDepthRangeArrayv",
"glDepthRangeIndexed",
"glDepthRangef",
"glDetachShader",
"glDisable",
"glDisableVertexArrayAttrib",
"glDisableVertexAttribArray",
"glDisablei",
"glDispatchCompute",
"glDispatchComputeIndirect",
"glDrawArrays",
"glDrawArraysIndirect",
"glDrawArraysInstanced",
"glDrawArraysInstancedBaseInstance",
"glDrawBuffer",
"glDrawBuffers",
"glDrawElements",
"glDrawElementsBaseVertex",
"glDrawElementsIndirect",
"glDrawElementsInstanced",
"glDrawElementsInstancedBaseInstance",
"glDrawElementsInstancedBaseVertex",
"glDrawElementsInstancedBaseVertexBaseInstance",
"glDrawRangeElements",
"glDrawRangeElementsBaseVertex",
"glDrawTransformFeedback",
"glDrawTransformFeedbackInstanced",
"glDrawTransformFeedbackStream",
"glDrawTransformFeedbackStreamInstanced",
"glEnable",
"glEnableVertexArrayAttrib",
"glEnableVertexAttribArray",
"glEnablei",
"glEndConditionalRender",
"glEndQuery",
"glEndQueryIndexed",
"glEndTransformFeedback",
"glFenceSync",
"glFinish",
"glFlush",
"glFlushMappedBufferRange",
"glFlushMappedNamedBufferRange",
"glFramebufferParameteri",
"glFramebufferRenderbuffer",
"glFramebufferTexture",
"glFramebufferTexture1D",
"glFramebufferTexture2D",
"glFramebufferTexture3D",
"glFramebufferTextureLayer",
"glFrontFace",
"glGenBuffers",
"glGenFramebuffers",
"glGenProgramPipelines",
"glGenQueries",
"glGenRenderbuffers",
"glGenSamplers",
"glGenTextures",
"glGenTransformFeedbacks",
"glGenVertexArrays",
"glGenerateMipmap",
"glGenerateTextureMipmap",
"glGetActiveAtomicCounterBufferiv",
"glGetActiveAttrib",
"glGetActiveSubroutineName",
"glGetActiveSubroutineUniformName",
"glGetActiveSubroutineUniformiv",
"glGetActiveUniform",
"glGetActiveUniformBlockName",
"glGetActiveUniformBlockiv",
"glGetActiveUniformName",
"glGetActiveUniformsiv",
"glGetAttachedShaders",
"glGetAttribLocation",
"glGetBooleani_v",
"glGetBooleanv",
"glGetBufferParameteri64v",
"glGetBufferParameteriv",
"glGetBufferPointerv",
"glGetBufferSubData",
"glGetCompressedTexImage",
"glGetCompressedTextureImage",
"glGetCompressedTextureSubImage",
"glGetDebugMessageLog",
"glGetDoublei_v",
"glGetDoublev",
"glGetError",
"glGetFloati_v",
"glGetFloatv",
"glGetFragDataIndex",
"glGetFragDataLocation",
"glGetFramebufferAttachmentParameteriv",
"glGetFramebufferParameteriv",
"glGetGraphicsResetStatus",
"glGetInteger64i_v",
"glGetInteger64v",
"glGetIntegeri_v",
"glGetIntegerv",
"glGetInternalformati64v",
"glGetInternalformativ",
"glGetMultisamplefv",
"glGetNamedBufferParameteri64v",
"glGetNamedBufferParameteriv",
"glGetNamedBufferPointerv",
"glGetNamedBufferSubData",
"glGetNamedFramebufferAttachmentParameteriv",
"glGetNamedFramebufferParameteriv",
"glGetNamedRenderbufferParameteriv",
"glGetObjectLabel",
"glGetObjectPtrLabel",
"glGetPointerv",
"glGetProgramBinary",
"glGetProgramInfoLog",
"glGetProgramInterfaceiv",
"glGetProgramPipelineInfoLog",
"glGetProgramPipelineiv",
"glGetProgramResourceIndex",
"glGetProgramResourceLocation",
"glGetProgramResourceLocationIndex",
"glGetProgramResourceName",
"glGetProgramResourceiv",
"glGetProgramStageiv",
"glGetProgramiv",
"glGetQueryBufferObjecti64v",
"glGetQueryBufferObjectiv",
"glGetQueryBufferObjectui64v",
"glGetQueryBufferObjectuiv",
"glGetQueryIndexediv",
"glGetQueryObjecti64v",
"glGetQueryObjectiv",
"glGetQueryObjectui64v",
"glGetQueryObjectuiv",
"glGetQueryiv",
"glGetRenderbufferParameteriv",
"glGetSamplerParameterIiv",
"glGetSamplerParameterIuiv",
"glGetSamplerParameterfv",
"glGetSamplerParameteriv",
"glGetShaderInfoLog",
"glGetShaderPrecisionFormat",
"glGetShaderSource",
"glGetShaderiv",
"glGetString",
"glGetStringi",
"glGetSubroutineIndex",
"glGetSubroutineUniformLocation",
"glGetSynciv",
"glGetTexImage",
"glGetTexLevelParameterfv",
"glGetTexLevelParameteriv",
"glGetTexParameterIiv",
"glGetTexParameterIuiv",
"glGetTexParameterfv",
"glGetTexParameteriv",
"glGetTextureImage",
"glGetTextureLevelParameterfv",
"glGetTextureLevelParameteriv",
"glGetTextureParameterIiv",
"glGetTextureParameterIuiv",
"glGetTextureParameterfv",
"glGetTextureParameteriv",
"glGetTextureSubImage",
"glGetTransformFeedbackVarying",
"glGetTransformFeedbacki64_v",
"glGetTransformFeedbacki_v",
"glGetTransformFeedbackiv",
"glGetUniformBlockIndex",
"glGetUniformIndices",
"glGetUniformLocation",
"glGetUniformSubroutineuiv",
"glGetUniformdv",
"glGetUniformfv",
"glGetUniformiv",
"glGetUniformuiv",
"glGetVertexArrayIndexed64iv",
"glGetVertexArrayIndexediv",
"glGetVertexArrayiv",
"glGetVertexAttribIiv",
"glGetVertexAttribIuiv",
"glGetVertexAttribLdv",
"glGetVertexAttribPointerv",
"glGetVertexAttribdv",
"glGetVertexAttribfv",
"glGetVertexAttribiv",
"glGetnCompressedTexImage",
"glGetnTexImage",
"glGetnUniformdv",
"glGetnUniformfv",
"glGetnUniformiv",
"glGetnUniformuiv",
"glHint",
"glInvalidateBufferData",
"glInvalidateBufferSubData",
"glInvalidateFramebuffer",
"glInvalidateNamedFramebufferData",
"glInvalidateNamedFramebufferSubData",
"glInvalidateSubFramebuffer",
"glInvalidateTexImage",
"glInvalidateTexSubImage",
"glIsBuffer",
"glIsEnabled",
"glIsEnabledi",
"glIsFramebuffer",
"glIsProgram",
"glIsProgramPipeline",
"glIsQuery",
"glIsRenderbuffer",
"glIsSampler",
"glIsShader",
"glIsSync",
"glIsTexture",
"glIsTransformFeedback",
"glIsVertexArray",
"glLineWidth",
"glLinkProgram",
"glLogicOp",
"glMapBuffer",
"glMapBufferRange",
"glMapNamedBuffer",
"glMapNamedBufferRange",
"glMemoryBarrier",
"glMemoryBarrierByRegion",
"glMinSampleShading",
"glMultiDrawArrays",
"glMultiDrawArraysIndirect",
"glMultiDrawArraysIndirectCount",
"glMultiDrawElements",
"glMultiDrawElementsBaseVertex",
"glMultiDrawElementsIndirect",
"glMultiDrawElementsIndirectCount",
"glNamedBufferData",
"glNamedBufferStorage",
"glNamedBufferSubData",
"glNamedFramebufferDrawBuffer",
"glNamedFramebufferDrawBuffers",
"glNamedFramebufferParameteri",
"glNamedFramebufferReadBuffer",
"glNamedFramebufferRenderbuffer",
"glNamedFramebufferTexture",
"glNamedFramebufferTextureLayer",
"glNamedRenderbufferStorage",
"glNamedRenderbufferStorageMultisample",
"glObjectLabel",
"glObjectPtrLabel",
"glPatchParameterfv",
"glPatchParameteri",
"glPauseTransformFeedback",
"glPixelStoref",
"glPixelStorei",
"glPointParameterf",
"glPointParameterfv",
"glPointParameteri",
"glPointParameteriv",
"glPointSize",
"glPolygonMode",
"glPolygonOffset",
"glPolygonOffsetClamp",
"glPopDebugGroup",
"glPrimitiveRestartIndex",
"glProgramBinary",
"glProgramParameteri",
"glProgramUniform1d",
"glProgramUniform1dv",
"glProgramUniform1f",
"glProgramUniform1fv",
"glProgramUniform1i",
"glProgramUniform1iv",
"glProgramUniform1ui",
"glProgramUniform1uiv",
"glProgramUniform2d",
"glProgramUniform2dv",
"glProgramUniform2f",
"glProgramUniform2fv",
"glProgramUniform2i",
"glProgramUniform2iv",
"glProgramUniform2ui",
"glProgramUniform2uiv",
"glProgramUniform3d",
"glProgramUniform3dv",
"glProgramUniform3f",
"glProgramUniform3fv",
"glProgramUniform3i",
"glProgramUniform3iv",
"glProgramUniform3ui",
"glProgramUniform3uiv",
"glProgramUniform4d",
"glProgramUniform4dv",
"glProgramUniform4f",
"glProgramUniform4fv",
"glProgramUniform4i",
"glProgramUniform4iv",
"glProgramUniform4ui",
"glProgramUniform4uiv",
"glProgramUniformMatrix2dv",
"glProgramUniformMatrix2fv",
"glProgramUniformMatrix2x3dv",
"glProgramUniformMatrix2x3fv",
"glProgramUniformMatrix2x4dv",
"glProgramUniformMatrix2x4fv",
"glProgramUniformMatrix3dv",
"glProgramUniformMatrix3fv",
"glProgramUniformMatrix3x2dv",
"glProgramUniformMatrix3x2fv",
"glProgramUniformMatrix3x4dv",
"glProgramUniformMatrix3x4fv",
"glProgramUniformMatrix4dv",
"glProgramUniformMatrix4fv",
"glProgramUniformMatrix4x2dv",
"glProgramUniformMatrix4x2fv",
"glProgramUniformMatrix4x3dv",
"glProgramUniformMatrix4x3fv",
"glProvokingVertex",
"glPushDebugGroup",
"glQueryCounter",
"glReadBuffer",
"glReadPixels",
"glReadnPixels",
"glReleaseShaderCompiler",
"glRenderbufferStorage",
"glRenderbufferStorageMultisample",
"glResumeTransformFeedback",
"glSampleCoverage",
"glSampleMaski",
"glSamplerParameterIiv",
"glSamplerParameterIuiv",
"glSamplerParameterf",
"glSamplerParameterfv",
"glSamplerParameteri",
"glSamplerParameteriv",
"glScissor",
"glScissorArrayv",
"glScissorIndexed",
"glScissorIndexedv",
"glShaderBinary",
"glShaderSource",
"glShaderStorageBlockBinding",
"glSpecializeShader",
"glStencilFunc",
"glStencilFuncSeparate",
"glStencilMask",
"glStencilMaskSeparate",
"glStencilOp",
"glStencilOpSeparate",
"glTexBuffer",
"glTexBufferRange",
"glTexImage1D",
"glTexImage2D",
"glTexImage2DMultisample",
"glTexImage3D",
"glTexImage3DMultisample",
"glTexParameterIiv",
"glTexParameterIuiv",
"glTexParameterf",
"glTexParameterfv",
"glTexParameteri",
"glTexParameteriv",
"glTexStorage1D",
"glTexStorage2D",
"glTexStorage2DMultisample",
"glTexStorage3D",
"glTexStorage3DMultisample",
"glTexSubImage1D",
"glTexSubImage2D",
"glTexSubImage3D",
"glTextureBarrier",
"glTextureBuffer",
"glTextureBufferRange",
"glTextureParameterIiv",
"glTextureParameterIuiv",
"glTextureParameterf",
"glTextureParameterfv",
"glTextureParameteri",
"glTextureParameteriv",
"glTextureStorage1D",
"glTextureStorage2D",
"glTextureStorage2DMultisample",
"glTextureStorage3D",
"glTextureStorage3DMultisample",
"glTextureSubImage1D",
"glTextureSubImage2D",
"glTextureSubImage3D",
"glTextureView",
"glTransformFeedbackBufferBase",
"glTransformFeedbackBufferRange",
"glTransformFeedbackVaryings",
"glUniform1d",
"glUniform1dv",
"glUniform1f",
"glUniform1fv",
"glUniform1i",
"glUniform1iv",
"glUniform1ui",
"glUniform1uiv",
"glUniform2d",
"glUniform2dv",
"glUniform2f",
"glUniform2fv",
"glUniform2i",
"glUniform2iv",
"glUniform2ui",
"glUniform2uiv",
"glUniform3d",
"glUniform3dv",
"glUniform3f",
"glUniform3fv",
"glUniform3i",
"glUniform3iv",
"glUniform3ui",
"glUniform3uiv",
"glUniform4d",
"glUniform4dv",
"glUniform4f",
"glUniform4fv",
"glUniform4i",
"glUniform4iv",
"glUniform4ui",
"glUniform4uiv",
"glUniformBlockBinding",
"glUniformMatrix2dv",
"glUniformMatrix2fv",
"glUniformMatrix2x3dv",
"glUniformMatrix2x3fv",
"glUniformMatrix2x4dv",
"glUniformMatrix2x4fv",
"glUniformMatrix3dv",
"glUniformMatrix3fv",
"glUniformMatrix3x2dv",
"glUniformMatrix3x2fv",
"glUniformMatrix3x4dv",
"glUniformMatrix3x4fv",
"glUniformMatrix4dv",
"glUniformMatrix4fv",
"glUniformMatrix4x2dv",
"glUniformMatrix4x2fv",
"glUniformMatrix4x3dv",
"glUniformMatrix4x3fv",
"glUniformSubroutinesuiv",
"glUnmapBuffer",
"glUnmapNamedBuffer",
"glUseProgram",
"glUseProgramStages",
"glValidateProgram",
"glValidateProgramPipeline",
"glVertexArrayAttribBinding",
"glVertexArrayAttribFormat",
"glVertexArrayAttribIFormat",
"glVertexArrayAttribLFormat",
"glVertexArrayBindingDivisor",
"glVertexArrayElementBuffer",
"glVertexArrayVertexBuffer",
"glVertexArrayVertexBuffers",
"glVertexAttrib1d",
"glVertexAttrib1dv",
"glVertexAttrib1f",
"glVertexAttrib1fv",
"glVertexAttrib1s",
"glVertexAttrib1sv",
"glVertexAttrib2d",
"glVertexAttrib2dv",
"glVertexAttrib2f",
"glVertexAttrib2fv",
"glVertexAttrib2s",
"glVertexAttrib2sv",
"glVertexAttrib3d",
"glVertexAttrib3dv",
"glVertexAttrib3f",
"glVertexAttrib3fv",
"glVertexAttrib3s",
"glVertexAttrib3sv",
"glVertexAttrib4Nbv",
"glVertexAttrib4Niv",
"glVertexAttrib4Nsv",
"glVertexAttrib4Nub",
"glVertexAttrib4Nubv",
"glVertexAttrib4Nuiv",
"glVertexAttrib4Nusv",
"glVertexAttrib4bv",
"glVertexAttrib4d",
"glVertexAttrib4dv",
"glVertexAttrib4f",
"glVertexAttrib4fv",
"glVertexAttrib4iv",
"glVertexAttrib4s",
"glVertexAttrib4sv",
"glVertexAttrib4ubv",
"glVertexAttrib4uiv",
"glVertexAttrib4usv",
"glVertexAttribBinding",
"glVertexAttribDivisor",
"glVertexAttribFormat",
"glVertexAttribI1i",
"glVertexAttribI1iv",
"glVertexAttribI1ui",
"glVertexAttribI1uiv",
"glVertexAttribI2i",
"glVertexAttribI2iv",
"glVertexAttribI2ui",
"glVertexAttribI2uiv",
"glVertexAttribI3i",
"glVertexAttribI3iv",
"glVertexAttribI3ui",
"glVertexAttribI3uiv",
"glVertexAttribI4bv",
"glVertexAttribI4i",
"glVertexAttribI4iv",
"glVertexAttribI4sv",
"glVertexAttribI4ubv",
"glVertexAttribI4ui",
"glVertexAttribI4uiv",
"glVertexAttribI4usv",
"glVertexAttribIFormat",
"glVertexAttribIPointer",
"glVertexAttribL1d",
"glVertexAttribL1dv",
"glVertexAttribL2d",
"glVertexAttribL2dv",
"glVertexAttribL3d",
"glVertexAttribL3dv",
"glVertexAttribL4d",
"glVertexAttribL4dv",
"glVertexAttribLFormat",
"glVertexAttribLPointer",
"glVertexAttribP1ui",
"glVertexAttribP1uiv",
"glVertexAttribP2ui",
"glVertexAttribP2uiv",
"glVertexAttribP3ui",
"glVertexAttribP3uiv",
"glVertexAttribP4ui",
"glVertexAttribP4uiv",
"glVertexAttribPointer",
"glVertexBindingDivisor",
"glViewport",
"glViewportArrayv",
"glViewportIndexedf",
"glViewportIndexedfv",
"glWaitSync",
};
union GL3WProcs gl3wProcs;
static void load_procs(GL3WGetProcAddressProc proc)
{
size_t i;
for (i = 0; i < ARRAY_SIZE(proc_names); i++)
gl3wProcs.ptr[i] = proc(proc_names[i]);
}
+22
View File
@@ -0,0 +1,22 @@
Copyright (c) 2002-2006 Marcus Geelnard
Copyright (c) 2006-2016 Camilla Berglund <elmindreda@glfw.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would
be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not
be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
File diff suppressed because it is too large. Load diff
+456
View File
@@ -0,0 +1,456 @@
/*************************************************************************
* GLFW 3.2 - www.glfw.org
* A library for OpenGL, window and input
*------------------------------------------------------------------------
* Copyright (c) 2002-2006 Marcus Geelnard
* Copyright (c) 2006-2016 Camilla Berglund <elmindreda@glfw.org>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*************************************************************************/
#ifndef _glfw3_native_h_
#define _glfw3_native_h_
#ifdef __cplusplus
extern "C" {
#endif
/*************************************************************************
* Doxygen documentation
*************************************************************************/
/*! @file glfw3native.h
* @brief The header of the native access functions.
*
* This is the header file of the native access functions. See @ref native for
* more information.
*/
/*! @defgroup native Native access
*
* **By using the native access functions you assert that you know what you're
* doing and how to fix problems caused by using them. If you don't, you
* shouldn't be using them.**
*
* Before the inclusion of @ref glfw3native.h, you may define exactly one
* window system API macro and zero or more context creation API macros.
*
* The chosen backends must match those the library was compiled for. Failure
* to do this will cause a link-time error.
*
* The available window API macros are:
* * `GLFW_EXPOSE_NATIVE_WIN32`
* * `GLFW_EXPOSE_NATIVE_COCOA`
* * `GLFW_EXPOSE_NATIVE_X11`
* * `GLFW_EXPOSE_NATIVE_WAYLAND`
* * `GLFW_EXPOSE_NATIVE_MIR`
*
* The available context API macros are:
* * `GLFW_EXPOSE_NATIVE_WGL`
* * `GLFW_EXPOSE_NATIVE_NSGL`
* * `GLFW_EXPOSE_NATIVE_GLX`
* * `GLFW_EXPOSE_NATIVE_EGL`
*
* These macros select which of the native access functions that are declared
* and which platform-specific headers to include. It is then up your (by
* definition platform-specific) code to handle which of these should be
* defined.
*/
/*************************************************************************
* System headers and types
*************************************************************************/
#if defined(GLFW_EXPOSE_NATIVE_WIN32)
// This is a workaround for the fact that glfw3.h needs to export APIENTRY (for
// example to allow applications to correctly declare a GL_ARB_debug_output
// callback) but windows.h assumes no one will define APIENTRY before it does
#undef APIENTRY
#include <windows.h>
#elif defined(GLFW_EXPOSE_NATIVE_COCOA)
#include <ApplicationServices/ApplicationServices.h>
#if defined(__OBJC__)
#import <Cocoa/Cocoa.h>
#else
typedef void* id;
#endif
#elif defined(GLFW_EXPOSE_NATIVE_X11)
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
#elif defined(GLFW_EXPOSE_NATIVE_WAYLAND)
#include <wayland-client.h>
#elif defined(GLFW_EXPOSE_NATIVE_MIR)
#include <mir_toolkit/mir_client_library.h>
#endif
#if defined(GLFW_EXPOSE_NATIVE_WGL)
/* WGL is declared by windows.h */
#endif
#if defined(GLFW_EXPOSE_NATIVE_NSGL)
/* NSGL is declared by Cocoa.h */
#endif
#if defined(GLFW_EXPOSE_NATIVE_GLX)
#include <GL/glx.h>
#endif
#if defined(GLFW_EXPOSE_NATIVE_EGL)
#include <EGL/egl.h>
#endif
/*************************************************************************
* Functions
*************************************************************************/
#if defined(GLFW_EXPOSE_NATIVE_WIN32)
/*! @brief Returns the adapter device name of the specified monitor.
*
* @return The UTF-8 encoded adapter device name (for example `\\.\DISPLAY1`)
* of the specified monitor, or `NULL` if an [error](@ref error_handling)
* occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI const char* glfwGetWin32Adapter(GLFWmonitor* monitor);
/*! @brief Returns the display device name of the specified monitor.
*
* @return The UTF-8 encoded display device name (for example
* `\\.\DISPLAY1\Monitor0`) of the specified monitor, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI const char* glfwGetWin32Monitor(GLFWmonitor* monitor);
/*! @brief Returns the `HWND` of the specified window.
*
* @return The `HWND` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI HWND glfwGetWin32Window(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_WGL)
/*! @brief Returns the `HGLRC` of the specified window.
*
* @return The `HGLRC` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI HGLRC glfwGetWGLContext(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_COCOA)
/*! @brief Returns the `CGDirectDisplayID` of the specified monitor.
*
* @return The `CGDirectDisplayID` of the specified monitor, or
* `kCGNullDirectDisplay` if an [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI CGDirectDisplayID glfwGetCocoaMonitor(GLFWmonitor* monitor);
/*! @brief Returns the `NSWindow` of the specified window.
*
* @return The `NSWindow` of the specified window, or `nil` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI id glfwGetCocoaWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_NSGL)
/*! @brief Returns the `NSOpenGLContext` of the specified window.
*
* @return The `NSOpenGLContext` of the specified window, or `nil` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI id glfwGetNSGLContext(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_X11)
/*! @brief Returns the `Display` used by GLFW.
*
* @return The `Display` used by GLFW, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI Display* glfwGetX11Display(void);
/*! @brief Returns the `RRCrtc` of the specified monitor.
*
* @return The `RRCrtc` of the specified monitor, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI RRCrtc glfwGetX11Adapter(GLFWmonitor* monitor);
/*! @brief Returns the `RROutput` of the specified monitor.
*
* @return The `RROutput` of the specified monitor, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI RROutput glfwGetX11Monitor(GLFWmonitor* monitor);
/*! @brief Returns the `Window` of the specified window.
*
* @return The `Window` of the specified window, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI Window glfwGetX11Window(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_GLX)
/*! @brief Returns the `GLXContext` of the specified window.
*
* @return The `GLXContext` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI GLXContext glfwGetGLXContext(GLFWwindow* window);
/*! @brief Returns the `GLXWindow` of the specified window.
*
* @return The `GLXWindow` of the specified window, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI GLXWindow glfwGetGLXWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_WAYLAND)
/*! @brief Returns the `struct wl_display*` used by GLFW.
*
* @return The `struct wl_display*` used by GLFW, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI struct wl_display* glfwGetWaylandDisplay(void);
/*! @brief Returns the `struct wl_output*` of the specified monitor.
*
* @return The `struct wl_output*` of the specified monitor, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI struct wl_output* glfwGetWaylandMonitor(GLFWmonitor* monitor);
/*! @brief Returns the main `struct wl_surface*` of the specified window.
*
* @return The main `struct wl_surface*` of the specified window, or `NULL` if
* an [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI struct wl_surface* glfwGetWaylandWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_MIR)
/*! @brief Returns the `MirConnection*` used by GLFW.
*
* @return The `MirConnection*` used by GLFW, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI MirConnection* glfwGetMirDisplay(void);
/*! @brief Returns the Mir output ID of the specified monitor.
*
* @return The Mir output ID of the specified monitor, or zero if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI int glfwGetMirMonitor(GLFWmonitor* monitor);
/*! @brief Returns the `MirSurface*` of the specified window.
*
* @return The `MirSurface*` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI MirSurface* glfwGetMirWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_EGL)
/*! @brief Returns the `EGLDisplay` used by GLFW.
*
* @return The `EGLDisplay` used by GLFW, or `EGL_NO_DISPLAY` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI EGLDisplay glfwGetEGLDisplay(void);
/*! @brief Returns the `EGLContext` of the specified window.
*
* @return The `EGLContext` of the specified window, or `EGL_NO_CONTEXT` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI EGLContext glfwGetEGLContext(GLFWwindow* window);
/*! @brief Returns the `EGLSurface` of the specified window.
*
* @return The `EGLSurface` of the specified window, or `EGL_NO_SURFACE` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI EGLSurface glfwGetEGLSurface(GLFWwindow* window);
#endif
#ifdef __cplusplus
}
#endif
#endif /* _glfw3_native_h_ */
Binary file not shown.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2022 Omar Cornut
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+125
View File
@@ -0,0 +1,125 @@
//-----------------------------------------------------------------------------
// COMPILE-TIME OPTIONS FOR DEAR IMGUI
// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
//-----------------------------------------------------------------------------
// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it)
// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template.
//-----------------------------------------------------------------------------
// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp
// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
// Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using.
//-----------------------------------------------------------------------------
#pragma once
//---- Define assertion handler. Defaults to calling assert().
// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows
// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
// DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names.
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87: disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This will be folded into IMGUI_DISABLE_OBSOLETE_FUNCTIONS in a few versions.
//---- Disable all of Dear ImGui or don't implement standard windows/tools.
// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp.
//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty.
//#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowStackToolWindow() will be empty (this was called IMGUI_DISABLE_METRICS_WINDOW before 1.88).
//---- Don't implement some functions to reduce linkage requirements.
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a)
//#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW)
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a)
//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime).
//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).
//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)
//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
//---- Include imgui_user.h at the end of imgui.h as a convenience
//#define IMGUI_INCLUDE_IMGUI_USER_H
//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
//#define IMGUI_USE_BGRA_PACKED_COLOR
//---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
//#define IMGUI_USE_WCHAR32
//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files.
//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
//#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if enabled
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
//---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)
// Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h.
//#define IMGUI_USE_STB_SPRINTF
//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui)
// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided).
// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.
//#define IMGUI_ENABLE_FREETYPE
//---- Use stb_truetype to build and rasterize the font atlas (default)
// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.
//#define IMGUI_ENABLE_STB_TRUETYPE
//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
// This will be inlined as part of ImVec2 and ImVec4 class declarations.
/*
#define IM_VEC2_CLASS_EXTRA \
constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \
operator MyVec2() const { return MyVec2(x,y); }
#define IM_VEC4_CLASS_EXTRA \
constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices.
// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices).
// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer.
// Read about ImGuiBackendFlags_RendererHasVtxOffset for details.
//#define ImDrawIdx unsigned int
//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly)
//struct ImDrawList;
//struct ImDrawCmd;
//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);
//#define ImDrawCallback MyImDrawCallback
//---- Debug Tools: Macro to break in Debugger
// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)
//#define IM_DEBUG_BREAK IM_ASSERT(0)
//#define IM_DEBUG_BREAK __debugbreak()
//---- Debug Tools: Have the Item Picker break in the ItemAdd() function instead of ItemHoverable(),
// (which comes earlier in the code, will catch a few extra items, allow picking items other than Hovered one.)
// This adds a small runtime cost which is why it is not enabled by default.
//#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
//---- Debug Tools: Enable slower asserts
//#define IMGUI_DEBUG_PARANOID
//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
/*
namespace ImGui
{
void MyFunction(const char* name, const MyMatrix44& v);
}
*/
+13444
View File
File diff suppressed because it is too large. Load diff
+3065
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+664
View File
@@ -0,0 +1,664 @@
// dear imgui: Platform Backend for GLFW
// This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..)
// (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
// (Requires: GLFW 3.1+)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
// [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+).
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2022-04-30: Inputs: Fixed ImGui_ImplGlfw_TranslateUntranslatedKey() for lower case letters on OSX.
// 2022-03-23: Inputs: Fixed a regression in 1.87 which resulted in keyboard modifiers events being reported incorrectly on Linux/X11.
// 2022-02-07: Added ImGui_ImplGlfw_InstallCallbacks()/ImGui_ImplGlfw_RestoreCallbacks() helpers to facilitate user installing callbacks after initializing backend.
// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago)with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
// 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
// 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates.
// 2022-01-12: *BREAKING CHANGE*: Now using glfwSetCursorPosCallback(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetCursorPosCallback() and forward it to the backend via ImGui_ImplGlfw_CursorPosCallback().
// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
// 2022-01-05: Inputs: Converting GLFW untranslated keycodes back to translated keycodes (in the ImGui_ImplGlfw_KeyCallback() function) in order to match the behavior of every other backend, and facilitate the use of GLFW with lettered-shortcuts API.
// 2021-08-17: *BREAKING CHANGE*: Now using glfwSetWindowFocusCallback() to calling io.AddFocusEvent(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() and forward it to the backend via ImGui_ImplGlfw_WindowFocusCallback().
// 2021-07-29: *BREAKING CHANGE*: Now using glfwSetCursorEnterCallback(). MousePos is correctly reported when the host platform window is hovered but not focused. If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() callback and forward it to the backend via ImGui_ImplGlfw_CursorEnterCallback().
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
// 2020-01-17: Inputs: Disable error callback while assigning mouse cursors because some X11 setup don't have them and it generates errors.
// 2019-12-05: Inputs: Added support for new mouse cursors added in GLFW 3.4+ (resizing cursors, not allowed cursor).
// 2019-10-18: Misc: Previously installed user callbacks are now restored on shutdown.
// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
// 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter().
// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
// 2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them.
// 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
// 2018-06-08: Misc: Extracted imgui_impl_glfw.cpp/.h away from the old combined GLFW+OpenGL/Vulkan examples.
// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
// 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()).
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
// 2018-01-25: Inputs: Added gamepad support if ImGuiConfigFlags_NavEnableGamepad is set.
// 2018-01-25: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
// 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
// 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
#include "imgui.h"
#include "imgui_impl_glfw.h"
// Clang warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#endif
// GLFW
#include <GLFW/glfw3.h>
#ifdef _WIN32
#undef APIENTRY
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h> // for glfwGetWin32Window
#endif
#ifdef GLFW_RESIZE_NESW_CURSOR // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released?
#define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR
#else
#define GLFW_HAS_NEW_CURSORS (0)
#endif
#define GLFW_HAS_GAMEPAD_API (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetGamepadState() new api
#define GLFW_HAS_GET_KEY_NAME (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwGetKeyName()
// GLFW data
enum GlfwClientApi
{
GlfwClientApi_Unknown,
GlfwClientApi_OpenGL,
GlfwClientApi_Vulkan
};
struct ImGui_ImplGlfw_Data
{
GLFWwindow* Window;
GlfwClientApi ClientApi;
double Time;
GLFWwindow* MouseWindow;
GLFWcursor* MouseCursors[ImGuiMouseCursor_COUNT];
ImVec2 LastValidMousePos;
bool InstalledCallbacks;
// Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
GLFWwindowfocusfun PrevUserCallbackWindowFocus;
GLFWcursorposfun PrevUserCallbackCursorPos;
GLFWcursorenterfun PrevUserCallbackCursorEnter;
GLFWmousebuttonfun PrevUserCallbackMousebutton;
GLFWscrollfun PrevUserCallbackScroll;
GLFWkeyfun PrevUserCallbackKey;
GLFWcharfun PrevUserCallbackChar;
GLFWmonitorfun PrevUserCallbackMonitor;
ImGui_ImplGlfw_Data() { memset((void*)this, 0, sizeof(*this)); }
};
// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
// FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
// - Because glfwPollEvents() process all windows and some events may be called outside of it, you will need to register your own callbacks
// (passing install_callbacks=false in ImGui_ImplGlfw_InitXXX functions), set the current dear imgui context and then call our callbacks.
// - Otherwise we may need to store a GLFWWindow* -> ImGuiContext* map and handle this in the backend, adding a little bit of extra complexity to it.
// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData()
{
return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : NULL;
}
// Functions
static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data)
{
return glfwGetClipboardString((GLFWwindow*)user_data);
}
static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text)
{
glfwSetClipboardString((GLFWwindow*)user_data, text);
}
static ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int key)
{
switch (key)
{
case GLFW_KEY_TAB: return ImGuiKey_Tab;
case GLFW_KEY_LEFT: return ImGuiKey_LeftArrow;
case GLFW_KEY_RIGHT: return ImGuiKey_RightArrow;
case GLFW_KEY_UP: return ImGuiKey_UpArrow;
case GLFW_KEY_DOWN: return ImGuiKey_DownArrow;
case GLFW_KEY_PAGE_UP: return ImGuiKey_PageUp;
case GLFW_KEY_PAGE_DOWN: return ImGuiKey_PageDown;
case GLFW_KEY_HOME: return ImGuiKey_Home;
case GLFW_KEY_END: return ImGuiKey_End;
case GLFW_KEY_INSERT: return ImGuiKey_Insert;
case GLFW_KEY_DELETE: return ImGuiKey_Delete;
case GLFW_KEY_BACKSPACE: return ImGuiKey_Backspace;
case GLFW_KEY_SPACE: return ImGuiKey_Space;
case GLFW_KEY_ENTER: return ImGuiKey_Enter;
case GLFW_KEY_ESCAPE: return ImGuiKey_Escape;
case GLFW_KEY_APOSTROPHE: return ImGuiKey_Apostrophe;
case GLFW_KEY_COMMA: return ImGuiKey_Comma;
case GLFW_KEY_MINUS: return ImGuiKey_Minus;
case GLFW_KEY_PERIOD: return ImGuiKey_Period;
case GLFW_KEY_SLASH: return ImGuiKey_Slash;
case GLFW_KEY_SEMICOLON: return ImGuiKey_Semicolon;
case GLFW_KEY_EQUAL: return ImGuiKey_Equal;
case GLFW_KEY_LEFT_BRACKET: return ImGuiKey_LeftBracket;
case GLFW_KEY_BACKSLASH: return ImGuiKey_Backslash;
case GLFW_KEY_RIGHT_BRACKET: return ImGuiKey_RightBracket;
case GLFW_KEY_GRAVE_ACCENT: return ImGuiKey_GraveAccent;
case GLFW_KEY_CAPS_LOCK: return ImGuiKey_CapsLock;
case GLFW_KEY_SCROLL_LOCK: return ImGuiKey_ScrollLock;
case GLFW_KEY_NUM_LOCK: return ImGuiKey_NumLock;
case GLFW_KEY_PRINT_SCREEN: return ImGuiKey_PrintScreen;
case GLFW_KEY_PAUSE: return ImGuiKey_Pause;
case GLFW_KEY_KP_0: return ImGuiKey_Keypad0;
case GLFW_KEY_KP_1: return ImGuiKey_Keypad1;
case GLFW_KEY_KP_2: return ImGuiKey_Keypad2;
case GLFW_KEY_KP_3: return ImGuiKey_Keypad3;
case GLFW_KEY_KP_4: return ImGuiKey_Keypad4;
case GLFW_KEY_KP_5: return ImGuiKey_Keypad5;
case GLFW_KEY_KP_6: return ImGuiKey_Keypad6;
case GLFW_KEY_KP_7: return ImGuiKey_Keypad7;
case GLFW_KEY_KP_8: return ImGuiKey_Keypad8;
case GLFW_KEY_KP_9: return ImGuiKey_Keypad9;
case GLFW_KEY_KP_DECIMAL: return ImGuiKey_KeypadDecimal;
case GLFW_KEY_KP_DIVIDE: return ImGuiKey_KeypadDivide;
case GLFW_KEY_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
case GLFW_KEY_KP_SUBTRACT: return ImGuiKey_KeypadSubtract;
case GLFW_KEY_KP_ADD: return ImGuiKey_KeypadAdd;
case GLFW_KEY_KP_ENTER: return ImGuiKey_KeypadEnter;
case GLFW_KEY_KP_EQUAL: return ImGuiKey_KeypadEqual;
case GLFW_KEY_LEFT_SHIFT: return ImGuiKey_LeftShift;
case GLFW_KEY_LEFT_CONTROL: return ImGuiKey_LeftCtrl;
case GLFW_KEY_LEFT_ALT: return ImGuiKey_LeftAlt;
case GLFW_KEY_LEFT_SUPER: return ImGuiKey_LeftSuper;
case GLFW_KEY_RIGHT_SHIFT: return ImGuiKey_RightShift;
case GLFW_KEY_RIGHT_CONTROL: return ImGuiKey_RightCtrl;
case GLFW_KEY_RIGHT_ALT: return ImGuiKey_RightAlt;
case GLFW_KEY_RIGHT_SUPER: return ImGuiKey_RightSuper;
case GLFW_KEY_MENU: return ImGuiKey_Menu;
case GLFW_KEY_0: return ImGuiKey_0;
case GLFW_KEY_1: return ImGuiKey_1;
case GLFW_KEY_2: return ImGuiKey_2;
case GLFW_KEY_3: return ImGuiKey_3;
case GLFW_KEY_4: return ImGuiKey_4;
case GLFW_KEY_5: return ImGuiKey_5;
case GLFW_KEY_6: return ImGuiKey_6;
case GLFW_KEY_7: return ImGuiKey_7;
case GLFW_KEY_8: return ImGuiKey_8;
case GLFW_KEY_9: return ImGuiKey_9;
case GLFW_KEY_A: return ImGuiKey_A;
case GLFW_KEY_B: return ImGuiKey_B;
case GLFW_KEY_C: return ImGuiKey_C;
case GLFW_KEY_D: return ImGuiKey_D;
case GLFW_KEY_E: return ImGuiKey_E;
case GLFW_KEY_F: return ImGuiKey_F;
case GLFW_KEY_G: return ImGuiKey_G;
case GLFW_KEY_H: return ImGuiKey_H;
case GLFW_KEY_I: return ImGuiKey_I;
case GLFW_KEY_J: return ImGuiKey_J;
case GLFW_KEY_K: return ImGuiKey_K;
case GLFW_KEY_L: return ImGuiKey_L;
case GLFW_KEY_M: return ImGuiKey_M;
case GLFW_KEY_N: return ImGuiKey_N;
case GLFW_KEY_O: return ImGuiKey_O;
case GLFW_KEY_P: return ImGuiKey_P;
case GLFW_KEY_Q: return ImGuiKey_Q;
case GLFW_KEY_R: return ImGuiKey_R;
case GLFW_KEY_S: return ImGuiKey_S;
case GLFW_KEY_T: return ImGuiKey_T;
case GLFW_KEY_U: return ImGuiKey_U;
case GLFW_KEY_V: return ImGuiKey_V;
case GLFW_KEY_W: return ImGuiKey_W;
case GLFW_KEY_X: return ImGuiKey_X;
case GLFW_KEY_Y: return ImGuiKey_Y;
case GLFW_KEY_Z: return ImGuiKey_Z;
case GLFW_KEY_F1: return ImGuiKey_F1;
case GLFW_KEY_F2: return ImGuiKey_F2;
case GLFW_KEY_F3: return ImGuiKey_F3;
case GLFW_KEY_F4: return ImGuiKey_F4;
case GLFW_KEY_F5: return ImGuiKey_F5;
case GLFW_KEY_F6: return ImGuiKey_F6;
case GLFW_KEY_F7: return ImGuiKey_F7;
case GLFW_KEY_F8: return ImGuiKey_F8;
case GLFW_KEY_F9: return ImGuiKey_F9;
case GLFW_KEY_F10: return ImGuiKey_F10;
case GLFW_KEY_F11: return ImGuiKey_F11;
case GLFW_KEY_F12: return ImGuiKey_F12;
default: return ImGuiKey_None;
}
}
static int ImGui_ImplGlfw_KeyToModifier(int key)
{
if (key == GLFW_KEY_LEFT_CONTROL || key == GLFW_KEY_RIGHT_CONTROL)
return GLFW_MOD_CONTROL;
if (key == GLFW_KEY_LEFT_SHIFT || key == GLFW_KEY_RIGHT_SHIFT)
return GLFW_MOD_SHIFT;
if (key == GLFW_KEY_LEFT_ALT || key == GLFW_KEY_RIGHT_ALT)
return GLFW_MOD_ALT;
if (key == GLFW_KEY_LEFT_SUPER || key == GLFW_KEY_RIGHT_SUPER)
return GLFW_MOD_SUPER;
return 0;
}
static void ImGui_ImplGlfw_UpdateKeyModifiers(int mods)
{
ImGuiIO& io = ImGui::GetIO();
io.AddKeyEvent(ImGuiKey_ModCtrl, (mods & GLFW_MOD_CONTROL) != 0);
io.AddKeyEvent(ImGuiKey_ModShift, (mods & GLFW_MOD_SHIFT) != 0);
io.AddKeyEvent(ImGuiKey_ModAlt, (mods & GLFW_MOD_ALT) != 0);
io.AddKeyEvent(ImGuiKey_ModSuper, (mods & GLFW_MOD_SUPER) != 0);
}
void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackMousebutton != NULL && window == bd->Window)
bd->PrevUserCallbackMousebutton(window, button, action, mods);
ImGui_ImplGlfw_UpdateKeyModifiers(mods);
ImGuiIO& io = ImGui::GetIO();
if (button >= 0 && button < ImGuiMouseButton_COUNT)
io.AddMouseButtonEvent(button, action == GLFW_PRESS);
}
void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackScroll != NULL && window == bd->Window)
bd->PrevUserCallbackScroll(window, xoffset, yoffset);
ImGuiIO& io = ImGui::GetIO();
io.AddMouseWheelEvent((float)xoffset, (float)yoffset);
}
static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode)
{
#if GLFW_HAS_GET_KEY_NAME && !defined(__EMSCRIPTEN__)
// GLFW 3.1+ attempts to "untranslate" keys, which goes the opposite of what every other framework does, making using lettered shortcuts difficult.
// (It had reasons to do so: namely GLFW is/was more likely to be used for WASD-type game controls rather than lettered shortcuts, but IHMO the 3.1 change could have been done differently)
// See https://github.com/glfw/glfw/issues/1502 for details.
// Adding a workaround to undo this (so our keys are translated->untranslated->translated, likely a lossy process).
// This won't cover edge cases but this is at least going to cover common cases.
if (key >= GLFW_KEY_KP_0 && key <= GLFW_KEY_KP_EQUAL)
return key;
const char* key_name = glfwGetKeyName(key, scancode);
if (key_name && key_name[0] != 0 && key_name[1] == 0)
{
const char char_names[] = "`-=[]\\,;\'./";
const int char_keys[] = { GLFW_KEY_GRAVE_ACCENT, GLFW_KEY_MINUS, GLFW_KEY_EQUAL, GLFW_KEY_LEFT_BRACKET, GLFW_KEY_RIGHT_BRACKET, GLFW_KEY_BACKSLASH, GLFW_KEY_COMMA, GLFW_KEY_SEMICOLON, GLFW_KEY_APOSTROPHE, GLFW_KEY_PERIOD, GLFW_KEY_SLASH, 0 };
IM_ASSERT(IM_ARRAYSIZE(char_names) == IM_ARRAYSIZE(char_keys));
if (key_name[0] >= '0' && key_name[0] <= '9') { key = GLFW_KEY_0 + (key_name[0] - '0'); }
else if (key_name[0] >= 'A' && key_name[0] <= 'Z') { key = GLFW_KEY_A + (key_name[0] - 'A'); }
else if (key_name[0] >= 'a' && key_name[0] <= 'z') { key = GLFW_KEY_A + (key_name[0] - 'a'); }
else if (const char* p = strchr(char_names, key_name[0])) { key = char_keys[p - char_names]; }
}
// if (action == GLFW_PRESS) printf("key %d scancode %d name '%s'\n", key, scancode, key_name);
#else
IM_UNUSED(scancode);
#endif
return key;
}
void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, int action, int mods)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackKey != NULL && window == bd->Window)
bd->PrevUserCallbackKey(window, keycode, scancode, action, mods);
if (action != GLFW_PRESS && action != GLFW_RELEASE)
return;
// Workaround: X11 does not include current pressed/released modifier key in 'mods' flags. https://github.com/glfw/glfw/issues/1630
if (int keycode_to_mod = ImGui_ImplGlfw_KeyToModifier(keycode))
mods = (action == GLFW_PRESS) ? (mods | keycode_to_mod) : (mods & ~keycode_to_mod);
ImGui_ImplGlfw_UpdateKeyModifiers(mods);
keycode = ImGui_ImplGlfw_TranslateUntranslatedKey(keycode, scancode);
ImGuiIO& io = ImGui::GetIO();
ImGuiKey imgui_key = ImGui_ImplGlfw_KeyToImGuiKey(keycode);
io.AddKeyEvent(imgui_key, (action == GLFW_PRESS));
io.SetKeyEventNativeData(imgui_key, keycode, scancode); // To support legacy indexing (<1.87 user code)
}
void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackWindowFocus != NULL && window == bd->Window)
bd->PrevUserCallbackWindowFocus(window, focused);
ImGuiIO& io = ImGui::GetIO();
io.AddFocusEvent(focused != 0);
}
void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackCursorPos != NULL && window == bd->Window)
bd->PrevUserCallbackCursorPos(window, x, y);
ImGuiIO& io = ImGui::GetIO();
io.AddMousePosEvent((float)x, (float)y);
bd->LastValidMousePos = ImVec2((float)x, (float)y);
}
// Workaround: X11 seems to send spurious Leave/Enter events which would make us lose our position,
// so we back it up and restore on Leave/Enter (see https://github.com/ocornut/imgui/issues/4984)
void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackCursorEnter != NULL && window == bd->Window)
bd->PrevUserCallbackCursorEnter(window, entered);
ImGuiIO& io = ImGui::GetIO();
if (entered)
{
bd->MouseWindow = window;
io.AddMousePosEvent(bd->LastValidMousePos.x, bd->LastValidMousePos.y);
}
else if (!entered && bd->MouseWindow == window)
{
bd->LastValidMousePos = io.MousePos;
bd->MouseWindow = NULL;
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
}
}
void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackChar != NULL && window == bd->Window)
bd->PrevUserCallbackChar(window, c);
ImGuiIO& io = ImGui::GetIO();
io.AddInputCharacter(c);
}
void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int)
{
// Unused in 'master' branch but 'docking' branch will use this, so we declare it ahead of it so if you have to install callbacks you can install this one too.
}
void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
IM_ASSERT(bd->InstalledCallbacks == false && "Callbacks already installed!");
IM_ASSERT(bd->Window == window);
bd->PrevUserCallbackWindowFocus = glfwSetWindowFocusCallback(window, ImGui_ImplGlfw_WindowFocusCallback);
bd->PrevUserCallbackCursorEnter = glfwSetCursorEnterCallback(window, ImGui_ImplGlfw_CursorEnterCallback);
bd->PrevUserCallbackCursorPos = glfwSetCursorPosCallback(window, ImGui_ImplGlfw_CursorPosCallback);
bd->PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
bd->PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
bd->PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);
bd->PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
bd->PrevUserCallbackMonitor = glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback);
bd->InstalledCallbacks = true;
}
void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
IM_ASSERT(bd->InstalledCallbacks == true && "Callbacks not installed!");
IM_ASSERT(bd->Window == window);
glfwSetWindowFocusCallback(window, bd->PrevUserCallbackWindowFocus);
glfwSetCursorEnterCallback(window, bd->PrevUserCallbackCursorEnter);
glfwSetCursorPosCallback(window, bd->PrevUserCallbackCursorPos);
glfwSetMouseButtonCallback(window, bd->PrevUserCallbackMousebutton);
glfwSetScrollCallback(window, bd->PrevUserCallbackScroll);
glfwSetKeyCallback(window, bd->PrevUserCallbackKey);
glfwSetCharCallback(window, bd->PrevUserCallbackChar);
glfwSetMonitorCallback(bd->PrevUserCallbackMonitor);
bd->InstalledCallbacks = false;
bd->PrevUserCallbackWindowFocus = NULL;
bd->PrevUserCallbackCursorEnter = NULL;
bd->PrevUserCallbackCursorPos = NULL;
bd->PrevUserCallbackMousebutton = NULL;
bd->PrevUserCallbackScroll = NULL;
bd->PrevUserCallbackKey = NULL;
bd->PrevUserCallbackChar = NULL;
bd->PrevUserCallbackMonitor = NULL;
}
static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api)
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.BackendPlatformUserData == NULL && "Already initialized a platform backend!");
// Setup backend capabilities flags
ImGui_ImplGlfw_Data* bd = IM_NEW(ImGui_ImplGlfw_Data)();
io.BackendPlatformUserData = (void*)bd;
io.BackendPlatformName = "imgui_impl_glfw";
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
bd->Window = window;
bd->Time = 0.0;
io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
io.ClipboardUserData = bd->Window;
// Set platform dependent data in viewport
#if defined(_WIN32)
ImGui::GetMainViewport()->PlatformHandleRaw = (void*)glfwGetWin32Window(bd->Window);
#endif
// Create mouse cursors
// (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist,
// GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting.
// Missing cursors will return NULL and our _UpdateMouseCursor() function will use the Arrow cursor instead.)
GLFWerrorfun prev_error_callback = glfwSetErrorCallback(NULL);
bd->MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);
#if GLFW_HAS_NEW_CURSORS
bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);
#else
bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
#endif
glfwSetErrorCallback(prev_error_callback);
// Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
if (install_callbacks)
ImGui_ImplGlfw_InstallCallbacks(window);
bd->ClientApi = client_api;
return true;
}
bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);
}
bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Vulkan);
}
bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Unknown);
}
void ImGui_ImplGlfw_Shutdown()
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
IM_ASSERT(bd != NULL && "No platform backend to shutdown, or already shutdown?");
ImGuiIO& io = ImGui::GetIO();
if (bd->InstalledCallbacks)
ImGui_ImplGlfw_RestoreCallbacks(bd->Window);
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
glfwDestroyCursor(bd->MouseCursors[cursor_n]);
io.BackendPlatformName = NULL;
io.BackendPlatformUserData = NULL;
IM_DELETE(bd);
}
static void ImGui_ImplGlfw_UpdateMouseData()
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
ImGuiIO& io = ImGui::GetIO();
#ifdef __EMSCRIPTEN__
const bool is_app_focused = true;
#else
const bool is_app_focused = glfwGetWindowAttrib(bd->Window, GLFW_FOCUSED) != 0;
#endif
if (is_app_focused)
{
// (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
if (io.WantSetMousePos)
glfwSetCursorPos(bd->Window, (double)io.MousePos.x, (double)io.MousePos.y);
// (Optional) Fallback to provide mouse position when focused (ImGui_ImplGlfw_CursorPosCallback already provides this when hovered or captured)
if (is_app_focused && bd->MouseWindow == NULL)
{
double mouse_x, mouse_y;
glfwGetCursorPos(bd->Window, &mouse_x, &mouse_y);
io.AddMousePosEvent((float)mouse_x, (float)mouse_y);
bd->LastValidMousePos = ImVec2((float)mouse_x, (float)mouse_y);
}
}
}
static void ImGui_ImplGlfw_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(bd->Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
return;
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
{
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
glfwSetInputMode(bd->Window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
}
else
{
// Show OS mouse cursor
// FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
glfwSetCursor(bd->Window, bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]);
glfwSetInputMode(bd->Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
// Update gamepad inputs
static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
static void ImGui_ImplGlfw_UpdateGamepads()
{
ImGuiIO& io = ImGui::GetIO();
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
return;
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
#if GLFW_HAS_GAMEPAD_API
GLFWgamepadstate gamepad;
if (!glfwGetGamepadState(GLFW_JOYSTICK_1, &gamepad))
return;
#define MAP_BUTTON(KEY_NO, BUTTON_NO, _UNUSED) do { io.AddKeyEvent(KEY_NO, gamepad.buttons[BUTTON_NO] != 0); } while (0)
#define MAP_ANALOG(KEY_NO, AXIS_NO, _UNUSED, V0, V1) do { float v = gamepad.axes[AXIS_NO]; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0)
#else
int axes_count = 0, buttons_count = 0;
const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count);
const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count);
if (axes_count == 0 || buttons_count == 0)
return;
#define MAP_BUTTON(KEY_NO, _UNUSED, BUTTON_NO) do { io.AddKeyEvent(KEY_NO, (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS)); } while (0)
#define MAP_ANALOG(KEY_NO, _UNUSED, AXIS_NO, V0, V1) do { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0)
#endif
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
MAP_BUTTON(ImGuiKey_GamepadStart, GLFW_GAMEPAD_BUTTON_START, 7);
MAP_BUTTON(ImGuiKey_GamepadBack, GLFW_GAMEPAD_BUTTON_BACK, 6);
MAP_BUTTON(ImGuiKey_GamepadFaceDown, GLFW_GAMEPAD_BUTTON_A, 0); // Xbox A, PS Cross
MAP_BUTTON(ImGuiKey_GamepadFaceRight, GLFW_GAMEPAD_BUTTON_B, 1); // Xbox B, PS Circle
MAP_BUTTON(ImGuiKey_GamepadFaceLeft, GLFW_GAMEPAD_BUTTON_X, 2); // Xbox X, PS Square
MAP_BUTTON(ImGuiKey_GamepadFaceUp, GLFW_GAMEPAD_BUTTON_Y, 3); // Xbox Y, PS Triangle
MAP_BUTTON(ImGuiKey_GamepadDpadLeft, GLFW_GAMEPAD_BUTTON_DPAD_LEFT, 13);
MAP_BUTTON(ImGuiKey_GamepadDpadRight, GLFW_GAMEPAD_BUTTON_DPAD_RIGHT, 11);
MAP_BUTTON(ImGuiKey_GamepadDpadUp, GLFW_GAMEPAD_BUTTON_DPAD_UP, 10);
MAP_BUTTON(ImGuiKey_GamepadDpadDown, GLFW_GAMEPAD_BUTTON_DPAD_DOWN, 12);
MAP_BUTTON(ImGuiKey_GamepadL1, GLFW_GAMEPAD_BUTTON_LEFT_BUMPER, 4);
MAP_BUTTON(ImGuiKey_GamepadR1, GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER, 5);
MAP_ANALOG(ImGuiKey_GamepadL2, GLFW_GAMEPAD_AXIS_LEFT_TRIGGER, 4, -0.75f, +1.0f);
MAP_ANALOG(ImGuiKey_GamepadR2, GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER, 5, -0.75f, +1.0f);
MAP_BUTTON(ImGuiKey_GamepadL3, GLFW_GAMEPAD_BUTTON_LEFT_THUMB, 8);
MAP_BUTTON(ImGuiKey_GamepadR3, GLFW_GAMEPAD_BUTTON_RIGHT_THUMB, 9);
MAP_ANALOG(ImGuiKey_GamepadLStickLeft, GLFW_GAMEPAD_AXIS_LEFT_X, 0, -0.25f, -1.0f);
MAP_ANALOG(ImGuiKey_GamepadLStickRight, GLFW_GAMEPAD_AXIS_LEFT_X, 0, +0.25f, +1.0f);
MAP_ANALOG(ImGuiKey_GamepadLStickUp, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, -0.25f, -1.0f);
MAP_ANALOG(ImGuiKey_GamepadLStickDown, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, +0.25f, +1.0f);
MAP_ANALOG(ImGuiKey_GamepadRStickLeft, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, -0.25f, -1.0f);
MAP_ANALOG(ImGuiKey_GamepadRStickRight, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, +0.25f, +1.0f);
MAP_ANALOG(ImGuiKey_GamepadRStickUp, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, -0.25f, -1.0f);
MAP_ANALOG(ImGuiKey_GamepadRStickDown, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, +0.25f, +1.0f);
#undef MAP_BUTTON
#undef MAP_ANALOG
}
void ImGui_ImplGlfw_NewFrame()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
IM_ASSERT(bd != NULL && "Did you call ImGui_ImplGlfw_InitForXXX()?");
#if false // Rendering to our own framebuffer
// Setup display size (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
glfwGetWindowSize(bd->Window, &w, &h);
glfwGetFramebufferSize(bd->Window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)w, (float)h);
if (w > 0 && h > 0)
io.DisplayFramebufferScale = ImVec2((float)display_w / (float)w, (float)display_h / (float)h);
#endif
// Setup time step
double current_time = glfwGetTime();
io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f);
bd->Time = current_time;
ImGui_ImplGlfw_UpdateMouseData();
ImGui_ImplGlfw_UpdateMouseCursor();
// Update game controllers (if enabled and available)
ImGui_ImplGlfw_UpdateGamepads();
}
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
+46
View File
@@ -0,0 +1,46 @@
// dear imgui: Platform Backend for GLFW
// This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..)
// (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
// [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+).
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// About GLSL version:
// The 'glsl_version' initialization parameter defaults to "#version 150" if NULL.
// Only override if your GL version doesn't handle this GLSL version. Keep NULL if unsure!
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
struct GLFWwindow;
struct GLFWmonitor;
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks);
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks);
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks);
IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown();
IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame();
// GLFW callbacks (installer)
// - When calling Init with 'install_callbacks=true': ImGui_ImplGlfw_InstallCallbacks() is called. GLFW callbacks will be installed for you. They will chain-call user's previously installed callbacks, if any.
// - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call individual function yourself from your own GLFW callbacks.
IMGUI_IMPL_API void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window);
IMGUI_IMPL_API void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window);
// GLFW callbacks (individual callbacks to call if you didn't install callbacks)
IMGUI_IMPL_API void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused); // Since 1.84
IMGUI_IMPL_API void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered); // Since 1.84
IMGUI_IMPL_API void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y); // Since 1.87
IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c);
IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event);
+871
View File
@@ -0,0 +1,871 @@
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
// [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2022-05-23: OpenGL: Reworking 2021-12-15 "Using buffer orphaning" so it only happens on Intel GPU, seems to cause problems otherwise. (#4468, #4825, #4832, #5127).
// 2022-05-13: OpenGL: Fix state corruption on OpenGL ES 2.0 due to not preserving GL_ELEMENT_ARRAY_BUFFER_BINDING and vertex attribute states.
// 2021-12-15: OpenGL: Using buffer orphaning + glBufferSubData(), seems to fix leaks with multi-viewports with some Intel HD drivers.
// 2021-08-23: OpenGL: Fixed ES 3.0 shader ("#version 300 es") use normal precision floats to avoid wobbly rendering at HD resolutions.
// 2021-08-19: OpenGL: Embed and use our own minimal GL loader (imgui_impl_opengl3_loader.h), removing requirement and support for third-party loader.
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
// 2021-06-25: OpenGL: Use OES_vertex_array extension on Emscripten + backup/restore current state.
// 2021-06-21: OpenGL: Destroy individual vertex/fragment shader objects right after they are linked into the main shader.
// 2021-05-24: OpenGL: Access GL_CLIP_ORIGIN when "GL_ARB_clip_control" extension is detected, inside of just OpenGL 4.5 version.
// 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
// 2021-04-06: OpenGL: Don't try to read GL_CLIP_ORIGIN unless we're OpenGL 4.5 or greater.
// 2021-02-18: OpenGL: Change blending equation to preserve alpha in output buffer.
// 2021-01-03: OpenGL: Backup, setup and restore GL_STENCIL_TEST state.
// 2020-10-23: OpenGL: Backup, setup and restore GL_PRIMITIVE_RESTART state.
// 2020-10-15: OpenGL: Use glGetString(GL_VERSION) instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x)
// 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 context which have the defines set by a loader.
// 2020-07-10: OpenGL: Added support for glad2 OpenGL loader.
// 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX.
// 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix.
// 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset.
// 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader.
// 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader.
// 2019-10-25: OpenGL: Using a combination of GL define and runtime GL version to decide whether to use glDrawElementsBaseVertex(). Fix building with pre-3.2 GL loaders.
// 2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility.
// 2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call.
// 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
// 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
// 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop.
// 2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early.
// 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0).
// 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader.
// 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
// 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450).
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
// 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN.
// 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used.
// 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES".
// 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation.
// 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link.
// 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples.
// 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
// 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state.
// 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a NULL pointer.
// 2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150".
// 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context.
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
// 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
// 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode.
// 2017-05-01: OpenGL: Fixed save and restore of current blend func state.
// 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
// 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
// 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
//----------------------------------------
// OpenGL GLSL GLSL
// version version string
//----------------------------------------
// 2.0 110 "#version 110"
// 2.1 120 "#version 120"
// 3.0 130 "#version 130"
// 3.1 140 "#version 140"
// 3.2 150 "#version 150"
// 3.3 330 "#version 330 core"
// 4.0 400 "#version 400 core"
// 4.1 410 "#version 410 core"
// 4.2 420 "#version 410 core"
// 4.3 430 "#version 430 core"
// ES 2.0 100 "#version 100" = WebGL 1.0
// ES 3.0 300 "#version 300 es" = WebGL 2.0
//----------------------------------------
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#include "imgui_impl_opengl3.h"
#include <stdio.h>
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
// Clang warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#endif
// GL includes
#if defined(IMGUI_IMPL_OPENGL_ES2)
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
#include <OpenGLES/ES2/gl.h> // Use GL ES 2
#else
#include <GLES2/gl2.h> // Use GL ES 2
#endif
#if defined(__EMSCRIPTEN__)
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES
#endif
#include <GLES2/gl2ext.h>
#endif
#elif defined(IMGUI_IMPL_OPENGL_ES3)
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
#include <OpenGLES/ES3/gl.h> // Use GL ES 3
#else
#include <GLES3/gl3.h> // Use GL ES 3
#endif
#elif !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
// Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
// Helper libraries are often used for this purpose! Here we are using our own minimal custom loader based on gl3w.
// In the rest of your app/engine, you can use another loader of your choice (gl3w, glew, glad, glbinding, glext, glLoadGen, etc.).
// If you happen to be developing a new feature for this backend (imgui_impl_opengl3.cpp):
// - You may need to regenerate imgui_impl_opengl3_loader.h to add new symbols. See https://github.com/dearimgui/gl3w_stripped
// - You can temporarily use an unstripped version. See https://github.com/dearimgui/gl3w_stripped/releases
// Changes to this backend using new APIs should be accompanied by a regenerated stripped loader version.
#define IMGL3W_IMPL
#include "imgui_impl_opengl3_loader.h"
#endif
// Vertex arrays are not supported on ES2/WebGL1 unless Emscripten which uses an extension
#ifndef IMGUI_IMPL_OPENGL_ES2
#define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
#elif defined(__EMSCRIPTEN__)
#define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
#define glBindVertexArray glBindVertexArrayOES
#define glGenVertexArrays glGenVertexArraysOES
#define glDeleteVertexArrays glDeleteVertexArraysOES
#define GL_VERTEX_ARRAY_BINDING GL_VERTEX_ARRAY_BINDING_OES
#endif
// Desktop GL 2.0+ has glPolygonMode() which GL ES and WebGL don't have.
#ifdef GL_POLYGON_MODE
#define IMGUI_IMPL_HAS_POLYGON_MODE
#endif
// Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have.
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_2)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
#endif
// Desktop GL 3.3+ has glBindSampler()
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_3)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
#endif
// Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
#endif
// Desktop GL use extension detection
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS
#endif
// OpenGL Data
struct ImGui_ImplOpenGL3_Data
{
GLuint GlVersion; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2)
char GlslVersionString[32]; // Specified by user or detected based on compile time GL settings.
GLuint FontTexture;
GLuint ShaderHandle;
GLint AttribLocationTex; // Uniforms location
GLint AttribLocationProjMtx;
GLuint AttribLocationVtxPos; // Vertex attributes location
GLuint AttribLocationVtxUV;
GLuint AttribLocationVtxColor;
unsigned int VboHandle, ElementsHandle;
GLsizeiptr VertexBufferSize;
GLsizeiptr IndexBufferSize;
bool HasClipOrigin;
bool UseBufferSubData;
ImGui_ImplOpenGL3_Data() { memset((void*)this, 0, sizeof(*this)); }
};
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData()
{
return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : NULL;
}
// OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only)
#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
struct ImGui_ImplOpenGL3_VtxAttribState
{
GLint Enabled, Size, Type, Normalized, Stride;
GLvoid* Ptr;
void GetState(GLint index)
{
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &Enabled);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_SIZE, &Size);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_TYPE, &Type);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &Normalized);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &Stride);
glGetVertexAttribPointerv(index, GL_VERTEX_ATTRIB_ARRAY_POINTER, &Ptr);
}
void SetState(GLint index)
{
glVertexAttribPointer(index, Size, Type, (GLboolean)Normalized, Stride, Ptr);
if (Enabled) glEnableVertexAttribArray(index); else glDisableVertexAttribArray(index);
}
};
#endif
// Functions
bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!");
// Initialize our loader
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
if (imgl3wInit() != 0)
{
fprintf(stderr, "Failed to initialize OpenGL loader!\n");
return false;
}
#endif
// Setup backend capabilities flags
ImGui_ImplOpenGL3_Data* bd = IM_NEW(ImGui_ImplOpenGL3_Data)();
io.BackendRendererUserData = (void*)bd;
io.BackendRendererName = "imgui_impl_opengl3";
// Query for GL version (e.g. 320 for GL 3.2)
#if !defined(IMGUI_IMPL_OPENGL_ES2)
GLint major = 0;
GLint minor = 0;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
if (major == 0 && minor == 0)
{
// Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
const char* gl_version = (const char*)glGetString(GL_VERSION);
sscanf(gl_version, "%d.%d", &major, &minor);
}
bd->GlVersion = (GLuint)(major * 100 + minor * 10);
// Query vendor to enable glBufferSubData kludge
#ifdef _WIN32
if (const char* vendor = (const char*)glGetString(GL_VENDOR))
if (strncmp(vendor, "Intel", 5) == 0)
bd->UseBufferSubData = true;
#endif
//printf("GL_MAJOR_VERSION = %d\nGL_MINOR_VERSION = %d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", major, minor, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG]
#else
bd->GlVersion = 200; // GLES 2
#endif
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (bd->GlVersion >= 320)
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
#endif
// Store GLSL version string so we can refer to it later in case we recreate shaders.
// Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure.
if (glsl_version == NULL)
{
#if defined(IMGUI_IMPL_OPENGL_ES2)
glsl_version = "#version 100";
#elif defined(IMGUI_IMPL_OPENGL_ES3)
glsl_version = "#version 300 es";
#elif defined(__APPLE__)
glsl_version = "#version 150";
#else
glsl_version = "#version 130";
#endif
}
IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(bd->GlslVersionString));
strcpy(bd->GlslVersionString, glsl_version);
strcat(bd->GlslVersionString, "\n");
// Make an arbitrary GL call (we don't actually need the result)
// IF YOU GET A CRASH HERE: it probably means the OpenGL function loader didn't do its job. Let us know!
GLint current_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture);
// Detect extensions we support
bd->HasClipOrigin = (bd->GlVersion >= 450);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS
GLint num_extensions = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions);
for (GLint i = 0; i < num_extensions; i++)
{
const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, i);
if (extension != NULL && strcmp(extension, "GL_ARB_clip_control") == 0)
bd->HasClipOrigin = true;
}
#endif
return true;
}
void ImGui_ImplOpenGL3_Shutdown()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?");
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOpenGL3_DestroyDeviceObjects();
io.BackendRendererName = NULL;
io.BackendRendererUserData = NULL;
IM_DELETE(bd);
}
void ImGui_ImplOpenGL3_NewFrame()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
IM_ASSERT(bd != NULL && "Did you call ImGui_ImplOpenGL3_Init()?");
if (!bd->ShaderHandle)
ImGui_ImplOpenGL3_CreateDeviceObjects();
}
static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object)
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glEnable(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
if (bd->GlVersion >= 310)
glDisable(GL_PRIMITIVE_RESTART);
#endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#endif
// Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
#if defined(GL_CLIP_ORIGIN)
bool clip_origin_lower_left = true;
if (bd->HasClipOrigin)
{
GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&current_clip_origin);
if (current_clip_origin == GL_UPPER_LEFT)
clip_origin_lower_left = false;
}
#endif
// Setup viewport, orthographic projection matrix
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
#if defined(GL_CLIP_ORIGIN)
if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left
#endif
const float ortho_projection[4][4] =
{
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{ (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f },
};
glUseProgram(bd->ShaderHandle);
glUniform1i(bd->AttribLocationTex, 0);
glUniformMatrix4fv(bd->AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
if (bd->GlVersion >= 330)
glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise.
#endif
(void)vertex_array_object;
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindVertexArray(vertex_array_object);
#endif
// Bind vertex/index buffers and setup attributes for ImDrawVert
glBindBuffer(GL_ARRAY_BUFFER, bd->VboHandle);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bd->ElementsHandle);
glEnableVertexAttribArray(bd->AttribLocationVtxPos);
glEnableVertexAttribArray(bd->AttribLocationVtxUV);
glEnableVertexAttribArray(bd->AttribLocationVtxColor);
glVertexAttribPointer(bd->AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos));
glVertexAttribPointer(bd->AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv));
glVertexAttribPointer(bd->AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col));
}
// OpenGL3 Render function.
// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly.
// This is in order to be able to run within an OpenGL engine that doesn't do so.
void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
if (fb_width <= 0 || fb_height <= 0)
return;
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Backup GL state
GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
glActiveTexture(GL_TEXTURE0);
GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program);
GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
GLuint last_sampler; if (bd->GlVersion >= 330) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; }
#endif
GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
// This is part of VAO on OpenGL 3.0+ and OpenGL ES 3.0+.
GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_pos; last_vtx_attrib_state_pos.GetState(bd->AttribLocationVtxPos);
ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_uv; last_vtx_attrib_state_uv.GetState(bd->AttribLocationVtxUV);
ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_color; last_vtx_attrib_state_color.GetState(bd->AttribLocationVtxColor);
#endif
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object);
#endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE
GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
#endif
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
GLboolean last_enable_stencil_test = glIsEnabled(GL_STENCIL_TEST);
GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
GLboolean last_enable_primitive_restart = (bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE;
#endif
// Setup desired GL state
// Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
// The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
GLuint vertex_array_object = 0;
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glGenVertexArrays(1, &vertex_array_object);
#endif
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
// Will project scissor/clipping rectangles into framebuffer space
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
// Render command lists
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
// Upload vertex/index buffers
// - On Intel windows drivers we got reports that regular glBufferData() led to accumulating leaks when using multi-viewports, so we started using orphaning + glBufferSubData(). (See https://github.com/ocornut/imgui/issues/4468)
// - On NVIDIA drivers we got reports that using orphaning + glBufferSubData() led to glitches when using multi-viewports.
// - OpenGL drivers are in a very sorry state in 2022, for now we are switching code path based on vendors.
const GLsizeiptr vtx_buffer_size = (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert);
const GLsizeiptr idx_buffer_size = (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx);
if (bd->UseBufferSubData)
{
if (bd->VertexBufferSize < vtx_buffer_size)
{
bd->VertexBufferSize = vtx_buffer_size;
glBufferData(GL_ARRAY_BUFFER, bd->VertexBufferSize, NULL, GL_STREAM_DRAW);
}
if (bd->IndexBufferSize < idx_buffer_size)
{
bd->IndexBufferSize = idx_buffer_size;
glBufferData(GL_ELEMENT_ARRAY_BUFFER, bd->IndexBufferSize, NULL, GL_STREAM_DRAW);
}
glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data);
}
else
{
glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW);
}
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback != NULL)
{
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
else
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// Project scissor/clipping rectangles into framebuffer space
ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
continue;
// Apply scissor/clipping rectangle (Y is inverted in OpenGL)
glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y));
// Bind texture, Draw
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID());
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (bd->GlVersion >= 320)
glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset);
else
#endif
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)));
}
}
}
// Destroy the temporary VAO
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glDeleteVertexArrays(1, &vertex_array_object);
#endif
// Restore modified GL state
glUseProgram(last_program);
glBindTexture(GL_TEXTURE_2D, last_texture);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
if (bd->GlVersion >= 330)
glBindSampler(0, last_sampler);
#endif
glActiveTexture(last_active_texture);
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindVertexArray(last_vertex_array_object);
#endif
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
last_vtx_attrib_state_pos.SetState(bd->AttribLocationVtxPos);
last_vtx_attrib_state_uv.SetState(bd->AttribLocationVtxUV);
last_vtx_attrib_state_color.SetState(bd->AttribLocationVtxColor);
#endif
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (last_enable_stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST);
if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
if (bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); }
#endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]);
#endif
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
(void)bd; // Not all compilation paths use this
}
bool ImGui_ImplOpenGL3_CreateFontsTexture()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Build texture atlas
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
// Upload texture to graphics system
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
GLint last_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGenTextures(1, &bd->FontTexture);
glBindTexture(GL_TEXTURE_2D, bd->FontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
#endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
// Restore state
glBindTexture(GL_TEXTURE_2D, last_texture);
return true;
}
void ImGui_ImplOpenGL3_DestroyFontsTexture()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
if (bd->FontTexture)
{
glDeleteTextures(1, &bd->FontTexture);
io.Fonts->SetTexID(0);
bd->FontTexture = 0;
}
}
// If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file.
static bool CheckShader(GLuint handle, const char* desc)
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
GLint status = 0, log_length = 0;
glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s! With GLSL: %s\n", desc, bd->GlslVersionString);
if (log_length > 1)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetShaderInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
// If you get an error please report on GitHub. You may try different GL context version or GLSL version.
static bool CheckProgram(GLuint handle, const char* desc)
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
GLint status = 0, log_length = 0;
glGetProgramiv(handle, GL_LINK_STATUS, &status);
glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! With GLSL %s\n", desc, bd->GlslVersionString);
if (log_length > 1)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetProgramInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
bool ImGui_ImplOpenGL3_CreateDeviceObjects()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Backup GL state
GLint last_texture, last_array_buffer;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GLint last_vertex_array;
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
#endif
// Parse GLSL version string
int glsl_version = 130;
sscanf(bd->GlslVersionString, "#version %d", &glsl_version);
const GLchar* vertex_shader_glsl_120 =
"uniform mat4 ProjMtx;\n"
"attribute vec2 Position;\n"
"attribute vec2 UV;\n"
"attribute vec4 Color;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_130 =
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_300_es =
"precision highp float;\n"
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_410_core =
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* fragment_shader_glsl_120 =
"#ifdef GL_ES\n"
" precision mediump float;\n"
"#endif\n"
"uniform sampler2D Texture;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_130 =
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_300_es =
"precision mediump float;\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_410_core =
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"uniform sampler2D Texture;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
// Select shaders matching our GLSL versions
const GLchar* vertex_shader = NULL;
const GLchar* fragment_shader = NULL;
if (glsl_version < 130)
{
vertex_shader = vertex_shader_glsl_120;
fragment_shader = fragment_shader_glsl_120;
}
else if (glsl_version >= 410)
{
vertex_shader = vertex_shader_glsl_410_core;
fragment_shader = fragment_shader_glsl_410_core;
}
else if (glsl_version == 300)
{
vertex_shader = vertex_shader_glsl_300_es;
fragment_shader = fragment_shader_glsl_300_es;
}
else
{
vertex_shader = vertex_shader_glsl_130;
fragment_shader = fragment_shader_glsl_130;
}
// Create shaders
const GLchar* vertex_shader_with_version[2] = { bd->GlslVersionString, vertex_shader };
GLuint vert_handle = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vert_handle, 2, vertex_shader_with_version, NULL);
glCompileShader(vert_handle);
CheckShader(vert_handle, "vertex shader");
const GLchar* fragment_shader_with_version[2] = { bd->GlslVersionString, fragment_shader };
GLuint frag_handle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(frag_handle, 2, fragment_shader_with_version, NULL);
glCompileShader(frag_handle);
CheckShader(frag_handle, "fragment shader");
// Link
bd->ShaderHandle = glCreateProgram();
glAttachShader(bd->ShaderHandle, vert_handle);
glAttachShader(bd->ShaderHandle, frag_handle);
glLinkProgram(bd->ShaderHandle);
CheckProgram(bd->ShaderHandle, "shader program");
glDetachShader(bd->ShaderHandle, vert_handle);
glDetachShader(bd->ShaderHandle, frag_handle);
glDeleteShader(vert_handle);
glDeleteShader(frag_handle);
bd->AttribLocationTex = glGetUniformLocation(bd->ShaderHandle, "Texture");
bd->AttribLocationProjMtx = glGetUniformLocation(bd->ShaderHandle, "ProjMtx");
bd->AttribLocationVtxPos = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Position");
bd->AttribLocationVtxUV = (GLuint)glGetAttribLocation(bd->ShaderHandle, "UV");
bd->AttribLocationVtxColor = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Color");
// Create buffers
glGenBuffers(1, &bd->VboHandle);
glGenBuffers(1, &bd->ElementsHandle);
ImGui_ImplOpenGL3_CreateFontsTexture();
// Restore modified GL state
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindVertexArray(last_vertex_array);
#endif
return true;
}
void ImGui_ImplOpenGL3_DestroyDeviceObjects()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
if (bd->VboHandle) { glDeleteBuffers(1, &bd->VboHandle); bd->VboHandle = 0; }
if (bd->ElementsHandle) { glDeleteBuffers(1, &bd->ElementsHandle); bd->ElementsHandle = 0; }
if (bd->ShaderHandle) { glDeleteProgram(bd->ShaderHandle); bd->ShaderHandle = 0; }
ImGui_ImplOpenGL3_DestroyFontsTexture();
}
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
+55
View File
@@ -0,0 +1,55 @@
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
// [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// About GLSL version:
// The 'glsl_version' initialization parameter should be NULL (default) or a "#version XXX" string.
// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es"
// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp.
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
// Backend API
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = NULL);
IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data);
// (Optional) Called by Init/NewFrame/Shutdown
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture();
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();
// Specific OpenGL ES versions
//#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten
//#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android
// You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
#if !defined(IMGUI_IMPL_OPENGL_ES2) \
&& !defined(IMGUI_IMPL_OPENGL_ES3)
// Try to detect GLES on matching platforms
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__))
#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es"
#elif defined(__EMSCRIPTEN__) || defined(__amigaos4__)
#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100"
#else
// Otherwise imgui_impl_opengl3_loader.h will be used.
#endif
#endif
+786
View File
@@ -0,0 +1,786 @@
//-----------------------------------------------------------------------------
// About imgui_impl_opengl3_loader.h:
//
// We embed our own OpenGL loader to not require user to provide their own or to have to use ours,
// which proved to be endless problems for users.
// Our loader is custom-generated, based on gl3w but automatically filtered to only include
// enums/functions that we use in our imgui_impl_opengl3.cpp source file in order to be small.
//
// YOU SHOULD NOT NEED TO INCLUDE/USE THIS DIRECTLY. THIS IS USED BY imgui_impl_opengl3.cpp ONLY.
// THE REST OF YOUR APP SHOULD USE A DIFFERENT GL LOADER: ANY GL LOADER OF YOUR CHOICE.
//
// Regenerate with:
// python gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt
//
// More info:
// https://github.com/dearimgui/gl3w_stripped
// https://github.com/ocornut/imgui/issues/4445
//-----------------------------------------------------------------------------
/*
* This file was generated with gl3w_gen.py, part of imgl3w
* (hosted at https://github.com/dearimgui/gl3w_stripped)
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef __gl3w_h_
#define __gl3w_h_
// Adapted from KHR/khrplatform.h to avoid including entire file.
#ifndef __khrplatform_h_
typedef float khronos_float_t;
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
#ifdef _WIN64
typedef signed long long int khronos_intptr_t;
typedef signed long long int khronos_ssize_t;
#else
typedef signed long int khronos_intptr_t;
typedef signed long int khronos_ssize_t;
#endif
#if defined(_MSC_VER) && !defined(__clang__)
typedef signed __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100)
#include <stdint.h>
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#else
typedef signed long long khronos_int64_t;
typedef unsigned long long khronos_uint64_t;
#endif
#endif // __khrplatform_h_
#ifndef __gl_glcorearb_h_
#define __gl_glcorearb_h_ 1
#ifdef __cplusplus
extern "C" {
#endif
/*
** Copyright 2013-2020 The Khronos Group Inc.
** SPDX-License-Identifier: MIT
**
** This header is generated from the Khronos OpenGL / OpenGL ES XML
** API Registry. The current version of the Registry, generator scripts
** used to make the header, and the header can be found at
** https://github.com/KhronosGroup/OpenGL-Registry
*/
#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
#endif
#ifndef APIENTRY
#define APIENTRY
#endif
#ifndef APIENTRYP
#define APIENTRYP APIENTRY *
#endif
#ifndef GLAPI
#define GLAPI extern
#endif
/* glcorearb.h is for use with OpenGL core profile implementations.
** It should should be placed in the same directory as gl.h and
** included as <GL/glcorearb.h>.
**
** glcorearb.h includes only APIs in the latest OpenGL core profile
** implementation together with APIs in newer ARB extensions which
** can be supported by the core profile. It does not, and never will
** include functionality removed from the core profile, such as
** fixed-function vertex and fragment processing.
**
** Do not #include both <GL/glcorearb.h> and either of <GL/gl.h> or
** <GL/glext.h> in the same source file.
*/
/* Generated C header for:
* API: gl
* Profile: core
* Versions considered: .*
* Versions emitted: .*
* Default extensions included: glcore
* Additional extensions included: _nomatch_^
* Extensions removed: _nomatch_^
*/
#ifndef GL_VERSION_1_0
typedef void GLvoid;
typedef unsigned int GLenum;
typedef khronos_float_t GLfloat;
typedef int GLint;
typedef int GLsizei;
typedef unsigned int GLbitfield;
typedef double GLdouble;
typedef unsigned int GLuint;
typedef unsigned char GLboolean;
typedef khronos_uint8_t GLubyte;
#define GL_COLOR_BUFFER_BIT 0x00004000
#define GL_FALSE 0
#define GL_TRUE 1
#define GL_TRIANGLES 0x0004
#define GL_ONE 1
#define GL_SRC_ALPHA 0x0302
#define GL_ONE_MINUS_SRC_ALPHA 0x0303
#define GL_FRONT_AND_BACK 0x0408
#define GL_POLYGON_MODE 0x0B40
#define GL_CULL_FACE 0x0B44
#define GL_DEPTH_TEST 0x0B71
#define GL_STENCIL_TEST 0x0B90
#define GL_VIEWPORT 0x0BA2
#define GL_BLEND 0x0BE2
#define GL_SCISSOR_BOX 0x0C10
#define GL_SCISSOR_TEST 0x0C11
#define GL_UNPACK_ROW_LENGTH 0x0CF2
#define GL_PACK_ALIGNMENT 0x0D05
#define GL_TEXTURE_2D 0x0DE1
#define GL_UNSIGNED_BYTE 0x1401
#define GL_UNSIGNED_SHORT 0x1403
#define GL_UNSIGNED_INT 0x1405
#define GL_FLOAT 0x1406
#define GL_RGBA 0x1908
#define GL_FILL 0x1B02
#define GL_VENDOR 0x1F00
#define GL_RENDERER 0x1F01
#define GL_VERSION 0x1F02
#define GL_EXTENSIONS 0x1F03
#define GL_LINEAR 0x2601
#define GL_TEXTURE_MAG_FILTER 0x2800
#define GL_TEXTURE_MIN_FILTER 0x2801
typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode);
typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param);
typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
typedef void (APIENTRYP PFNGLCLEARPROC) (GLbitfield mask);
typedef void (APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLENABLEPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLFLUSHPROC) (void);
typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param);
typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
typedef GLenum (APIENTRYP PFNGLGETERRORPROC) (void);
typedef void (APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data);
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGPROC) (GLenum name);
typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glPolygonMode (GLenum face, GLenum mode);
GLAPI void APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
GLAPI void APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
GLAPI void APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
GLAPI void APIENTRY glClear (GLbitfield mask);
GLAPI void APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
GLAPI void APIENTRY glDisable (GLenum cap);
GLAPI void APIENTRY glEnable (GLenum cap);
GLAPI void APIENTRY glFlush (void);
GLAPI void APIENTRY glPixelStorei (GLenum pname, GLint param);
GLAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
GLAPI GLenum APIENTRY glGetError (void);
GLAPI void APIENTRY glGetIntegerv (GLenum pname, GLint *data);
GLAPI const GLubyte *APIENTRY glGetString (GLenum name);
GLAPI GLboolean APIENTRY glIsEnabled (GLenum cap);
GLAPI void APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
#endif
#endif /* GL_VERSION_1_0 */
#ifndef GL_VERSION_1_1
typedef khronos_float_t GLclampf;
typedef double GLclampd;
#define GL_TEXTURE_BINDING_2D 0x8069
typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices);
typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture);
typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures);
typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices);
GLAPI void APIENTRY glBindTexture (GLenum target, GLuint texture);
GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures);
GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures);
#endif
#endif /* GL_VERSION_1_1 */
#ifndef GL_VERSION_1_3
#define GL_TEXTURE0 0x84C0
#define GL_ACTIVE_TEXTURE 0x84E0
typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glActiveTexture (GLenum texture);
#endif
#endif /* GL_VERSION_1_3 */
#ifndef GL_VERSION_1_4
#define GL_BLEND_DST_RGB 0x80C8
#define GL_BLEND_SRC_RGB 0x80C9
#define GL_BLEND_DST_ALPHA 0x80CA
#define GL_BLEND_SRC_ALPHA 0x80CB
#define GL_FUNC_ADD 0x8006
typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
GLAPI void APIENTRY glBlendEquation (GLenum mode);
#endif
#endif /* GL_VERSION_1_4 */
#ifndef GL_VERSION_1_5
typedef khronos_ssize_t GLsizeiptr;
typedef khronos_intptr_t GLintptr;
#define GL_ARRAY_BUFFER 0x8892
#define GL_ELEMENT_ARRAY_BUFFER 0x8893
#define GL_ARRAY_BUFFER_BINDING 0x8894
#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
#define GL_STREAM_DRAW 0x88E0
typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer);
GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers);
GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers);
GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
#endif
#endif /* GL_VERSION_1_5 */
#ifndef GL_VERSION_2_0
typedef char GLchar;
typedef khronos_int16_t GLshort;
typedef khronos_int8_t GLbyte;
typedef khronos_uint16_t GLushort;
#define GL_BLEND_EQUATION_RGB 0x8009
#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
#define GL_BLEND_EQUATION_ALPHA 0x883D
#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
#define GL_FRAGMENT_SHADER 0x8B30
#define GL_VERTEX_SHADER 0x8B31
#define GL_COMPILE_STATUS 0x8B81
#define GL_LINK_STATUS 0x8B82
#define GL_INFO_LOG_LENGTH 0x8B84
#define GL_CURRENT_PROGRAM 0x8B8D
#define GL_UPPER_LEFT 0x8CA2
typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer);
typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader);
GLAPI void APIENTRY glCompileShader (GLuint shader);
GLAPI GLuint APIENTRY glCreateProgram (void);
GLAPI GLuint APIENTRY glCreateShader (GLenum type);
GLAPI void APIENTRY glDeleteProgram (GLuint program);
GLAPI void APIENTRY glDeleteShader (GLuint shader);
GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader);
GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index);
GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index);
GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name);
GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name);
GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer);
GLAPI void APIENTRY glLinkProgram (GLuint program);
GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
GLAPI void APIENTRY glUseProgram (GLuint program);
GLAPI void APIENTRY glUniform1i (GLint location, GLint v0);
GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
#endif
#endif /* GL_VERSION_2_0 */
#ifndef GL_VERSION_3_0
typedef khronos_uint16_t GLhalf;
#define GL_MAJOR_VERSION 0x821B
#define GL_MINOR_VERSION 0x821C
#define GL_NUM_EXTENSIONS 0x821D
#define GL_FRAMEBUFFER_SRGB 0x8DB9
#define GL_VERTEX_ARRAY_BINDING 0x85B5
typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data);
typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data);
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index);
typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array);
typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays);
typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index);
GLAPI void APIENTRY glBindVertexArray (GLuint array);
GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays);
GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays);
#endif
#endif /* GL_VERSION_3_0 */
#ifndef GL_VERSION_3_1
#define GL_VERSION_3_1 1
#define GL_PRIMITIVE_RESTART 0x8F9D
#endif /* GL_VERSION_3_1 */
#ifndef GL_VERSION_3_2
#define GL_VERSION_3_2 1
typedef struct __GLsync *GLsync;
typedef khronos_uint64_t GLuint64;
typedef khronos_int64_t GLint64;
typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
#endif
#endif /* GL_VERSION_3_2 */
#ifndef GL_VERSION_3_3
#define GL_VERSION_3_3 1
#define GL_SAMPLER_BINDING 0x8919
typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler);
#endif
#endif /* GL_VERSION_3_3 */
#ifndef GL_VERSION_4_1
typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data);
typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data);
#endif /* GL_VERSION_4_1 */
#ifndef GL_VERSION_4_3
typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
#endif /* GL_VERSION_4_3 */
#ifndef GL_VERSION_4_5
#define GL_CLIP_ORIGIN 0x935C
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param);
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param);
#endif /* GL_VERSION_4_5 */
#ifndef GL_ARB_bindless_texture
typedef khronos_uint64_t GLuint64EXT;
#endif /* GL_ARB_bindless_texture */
#ifndef GL_ARB_cl_event
struct _cl_context;
struct _cl_event;
#endif /* GL_ARB_cl_event */
#ifndef GL_ARB_clip_control
#define GL_ARB_clip_control 1
#endif /* GL_ARB_clip_control */
#ifndef GL_ARB_debug_output
typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
#endif /* GL_ARB_debug_output */
#ifndef GL_EXT_EGL_image_storage
typedef void *GLeglImageOES;
#endif /* GL_EXT_EGL_image_storage */
#ifndef GL_EXT_direct_state_access
typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params);
typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params);
typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params);
typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param);
typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param);
#endif /* GL_EXT_direct_state_access */
#ifndef GL_NV_draw_vulkan_image
typedef void (APIENTRY *GLVULKANPROCNV)(void);
#endif /* GL_NV_draw_vulkan_image */
#ifndef GL_NV_gpu_shader5
typedef khronos_int64_t GLint64EXT;
#endif /* GL_NV_gpu_shader5 */
#ifndef GL_NV_vertex_buffer_unified_memory
typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result);
#endif /* GL_NV_vertex_buffer_unified_memory */
#ifdef __cplusplus
}
#endif
#endif
#ifndef GL3W_API
#define GL3W_API
#endif
#ifndef __gl_h_
#define __gl_h_
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define GL3W_OK 0
#define GL3W_ERROR_INIT -1
#define GL3W_ERROR_LIBRARY_OPEN -2
#define GL3W_ERROR_OPENGL_VERSION -3
typedef void (*GL3WglProc)(void);
typedef GL3WglProc (*GL3WGetProcAddressProc)(const char *proc);
/* gl3w api */
GL3W_API int imgl3wInit(void);
GL3W_API int imgl3wInit2(GL3WGetProcAddressProc proc);
GL3W_API int imgl3wIsSupported(int major, int minor);
GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc);
/* gl3w internal state */
union GL3WProcs {
GL3WglProc ptr[58];
struct {
PFNGLACTIVETEXTUREPROC ActiveTexture;
PFNGLATTACHSHADERPROC AttachShader;
PFNGLBINDBUFFERPROC BindBuffer;
PFNGLBINDSAMPLERPROC BindSampler;
PFNGLBINDTEXTUREPROC BindTexture;
PFNGLBINDVERTEXARRAYPROC BindVertexArray;
PFNGLBLENDEQUATIONPROC BlendEquation;
PFNGLBLENDEQUATIONSEPARATEPROC BlendEquationSeparate;
PFNGLBLENDFUNCSEPARATEPROC BlendFuncSeparate;
PFNGLBUFFERDATAPROC BufferData;
PFNGLBUFFERSUBDATAPROC BufferSubData;
PFNGLCLEARPROC Clear;
PFNGLCLEARCOLORPROC ClearColor;
PFNGLCOMPILESHADERPROC CompileShader;
PFNGLCREATEPROGRAMPROC CreateProgram;
PFNGLCREATESHADERPROC CreateShader;
PFNGLDELETEBUFFERSPROC DeleteBuffers;
PFNGLDELETEPROGRAMPROC DeleteProgram;
PFNGLDELETESHADERPROC DeleteShader;
PFNGLDELETETEXTURESPROC DeleteTextures;
PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays;
PFNGLDETACHSHADERPROC DetachShader;
PFNGLDISABLEPROC Disable;
PFNGLDISABLEVERTEXATTRIBARRAYPROC DisableVertexAttribArray;
PFNGLDRAWELEMENTSPROC DrawElements;
PFNGLDRAWELEMENTSBASEVERTEXPROC DrawElementsBaseVertex;
PFNGLENABLEPROC Enable;
PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray;
PFNGLFLUSHPROC Flush;
PFNGLGENBUFFERSPROC GenBuffers;
PFNGLGENTEXTURESPROC GenTextures;
PFNGLGENVERTEXARRAYSPROC GenVertexArrays;
PFNGLGETATTRIBLOCATIONPROC GetAttribLocation;
PFNGLGETERRORPROC GetError;
PFNGLGETINTEGERVPROC GetIntegerv;
PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog;
PFNGLGETPROGRAMIVPROC GetProgramiv;
PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog;
PFNGLGETSHADERIVPROC GetShaderiv;
PFNGLGETSTRINGPROC GetString;
PFNGLGETSTRINGIPROC GetStringi;
PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation;
PFNGLGETVERTEXATTRIBPOINTERVPROC GetVertexAttribPointerv;
PFNGLGETVERTEXATTRIBIVPROC GetVertexAttribiv;
PFNGLISENABLEDPROC IsEnabled;
PFNGLLINKPROGRAMPROC LinkProgram;
PFNGLPIXELSTOREIPROC PixelStorei;
PFNGLPOLYGONMODEPROC PolygonMode;
PFNGLREADPIXELSPROC ReadPixels;
PFNGLSCISSORPROC Scissor;
PFNGLSHADERSOURCEPROC ShaderSource;
PFNGLTEXIMAGE2DPROC TexImage2D;
PFNGLTEXPARAMETERIPROC TexParameteri;
PFNGLUNIFORM1IPROC Uniform1i;
PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv;
PFNGLUSEPROGRAMPROC UseProgram;
PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer;
PFNGLVIEWPORTPROC Viewport;
} gl;
};
GL3W_API extern union GL3WProcs imgl3wProcs;
/* OpenGL functions */
#define glActiveTexture imgl3wProcs.gl.ActiveTexture
#define glAttachShader imgl3wProcs.gl.AttachShader
#define glBindBuffer imgl3wProcs.gl.BindBuffer
#define glBindSampler imgl3wProcs.gl.BindSampler
#define glBindTexture imgl3wProcs.gl.BindTexture
#define glBindVertexArray imgl3wProcs.gl.BindVertexArray
#define glBlendEquation imgl3wProcs.gl.BlendEquation
#define glBlendEquationSeparate imgl3wProcs.gl.BlendEquationSeparate
#define glBlendFuncSeparate imgl3wProcs.gl.BlendFuncSeparate
#define glBufferData imgl3wProcs.gl.BufferData
#define glBufferSubData imgl3wProcs.gl.BufferSubData
#define glClear imgl3wProcs.gl.Clear
#define glClearColor imgl3wProcs.gl.ClearColor
#define glCompileShader imgl3wProcs.gl.CompileShader
#define glCreateProgram imgl3wProcs.gl.CreateProgram
#define glCreateShader imgl3wProcs.gl.CreateShader
#define glDeleteBuffers imgl3wProcs.gl.DeleteBuffers
#define glDeleteProgram imgl3wProcs.gl.DeleteProgram
#define glDeleteShader imgl3wProcs.gl.DeleteShader
#define glDeleteTextures imgl3wProcs.gl.DeleteTextures
#define glDeleteVertexArrays imgl3wProcs.gl.DeleteVertexArrays
#define glDetachShader imgl3wProcs.gl.DetachShader
#define glDisable imgl3wProcs.gl.Disable
#define glDisableVertexAttribArray imgl3wProcs.gl.DisableVertexAttribArray
#define glDrawElements imgl3wProcs.gl.DrawElements
#define glDrawElementsBaseVertex imgl3wProcs.gl.DrawElementsBaseVertex
#define glEnable imgl3wProcs.gl.Enable
#define glEnableVertexAttribArray imgl3wProcs.gl.EnableVertexAttribArray
#define glFlush imgl3wProcs.gl.Flush
#define glGenBuffers imgl3wProcs.gl.GenBuffers
#define glGenTextures imgl3wProcs.gl.GenTextures
#define glGenVertexArrays imgl3wProcs.gl.GenVertexArrays
#define glGetAttribLocation imgl3wProcs.gl.GetAttribLocation
#define glGetError imgl3wProcs.gl.GetError
#define glGetIntegerv imgl3wProcs.gl.GetIntegerv
#define glGetProgramInfoLog imgl3wProcs.gl.GetProgramInfoLog
#define glGetProgramiv imgl3wProcs.gl.GetProgramiv
#define glGetShaderInfoLog imgl3wProcs.gl.GetShaderInfoLog
#define glGetShaderiv imgl3wProcs.gl.GetShaderiv
#define glGetString imgl3wProcs.gl.GetString
#define glGetStringi imgl3wProcs.gl.GetStringi
#define glGetUniformLocation imgl3wProcs.gl.GetUniformLocation
#define glGetVertexAttribPointerv imgl3wProcs.gl.GetVertexAttribPointerv
#define glGetVertexAttribiv imgl3wProcs.gl.GetVertexAttribiv
#define glIsEnabled imgl3wProcs.gl.IsEnabled
#define glLinkProgram imgl3wProcs.gl.LinkProgram
#define glPixelStorei imgl3wProcs.gl.PixelStorei
#define glPolygonMode imgl3wProcs.gl.PolygonMode
#define glReadPixels imgl3wProcs.gl.ReadPixels
#define glScissor imgl3wProcs.gl.Scissor
#define glShaderSource imgl3wProcs.gl.ShaderSource
#define glTexImage2D imgl3wProcs.gl.TexImage2D
#define glTexParameteri imgl3wProcs.gl.TexParameteri
#define glUniform1i imgl3wProcs.gl.Uniform1i
#define glUniformMatrix4fv imgl3wProcs.gl.UniformMatrix4fv
#define glUseProgram imgl3wProcs.gl.UseProgram
#define glVertexAttribPointer imgl3wProcs.gl.VertexAttribPointer
#define glViewport imgl3wProcs.gl.Viewport
#ifdef __cplusplus
}
#endif
#endif
#ifdef IMGL3W_IMPL
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
static HMODULE libgl;
typedef PROC(__stdcall* GL3WglGetProcAddr)(LPCSTR);
static GL3WglGetProcAddr wgl_get_proc_address;
static int open_libgl(void)
{
libgl = LoadLibraryA("opengl32.dll");
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
wgl_get_proc_address = (GL3WglGetProcAddr)GetProcAddress(libgl, "wglGetProcAddress");
return GL3W_OK;
}
static void close_libgl(void) { FreeLibrary(libgl); }
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
res = (GL3WglProc)wgl_get_proc_address(proc);
if (!res)
res = (GL3WglProc)GetProcAddress(libgl, proc);
return res;
}
#elif defined(__APPLE__)
#include <dlfcn.h>
static void *libgl;
static int open_libgl(void)
{
libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
return GL3W_OK;
}
static void close_libgl(void) { dlclose(libgl); }
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
*(void **)(&res) = dlsym(libgl, proc);
return res;
}
#else
#include <dlfcn.h>
static void *libgl;
static GL3WglProc (*glx_get_proc_address)(const GLubyte *);
static int open_libgl(void)
{
libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
*(void **)(&glx_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB");
return GL3W_OK;
}
static void close_libgl(void) { dlclose(libgl); }
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
res = glx_get_proc_address((const GLubyte *)proc);
if (!res)
*(void **)(&res) = dlsym(libgl, proc);
return res;
}
#endif
static struct { int major, minor; } version;
static int parse_version(void)
{
if (!glGetIntegerv)
return GL3W_ERROR_INIT;
glGetIntegerv(GL_MAJOR_VERSION, &version.major);
glGetIntegerv(GL_MINOR_VERSION, &version.minor);
if (version.major < 3)
return GL3W_ERROR_OPENGL_VERSION;
return GL3W_OK;
}
static void load_procs(GL3WGetProcAddressProc proc);
int imgl3wInit(void)
{
int res = open_libgl();
if (res)
return res;
atexit(close_libgl);
return imgl3wInit2(get_proc);
}
int imgl3wInit2(GL3WGetProcAddressProc proc)
{
load_procs(proc);
return parse_version();
}
int imgl3wIsSupported(int major, int minor)
{
if (major < 3)
return 0;
if (version.major == major)
return version.minor >= minor;
return version.major >= major;
}
GL3WglProc imgl3wGetProcAddress(const char *proc) { return get_proc(proc); }
static const char *proc_names[] = {
"glActiveTexture",
"glAttachShader",
"glBindBuffer",
"glBindSampler",
"glBindTexture",
"glBindVertexArray",
"glBlendEquation",
"glBlendEquationSeparate",
"glBlendFuncSeparate",
"glBufferData",
"glBufferSubData",
"glClear",
"glClearColor",
"glCompileShader",
"glCreateProgram",
"glCreateShader",
"glDeleteBuffers",
"glDeleteProgram",
"glDeleteShader",
"glDeleteTextures",
"glDeleteVertexArrays",
"glDetachShader",
"glDisable",
"glDisableVertexAttribArray",
"glDrawElements",
"glDrawElementsBaseVertex",
"glEnable",
"glEnableVertexAttribArray",
"glFlush",
"glGenBuffers",
"glGenTextures",
"glGenVertexArrays",
"glGetAttribLocation",
"glGetError",
"glGetIntegerv",
"glGetProgramInfoLog",
"glGetProgramiv",
"glGetShaderInfoLog",
"glGetShaderiv",
"glGetString",
"glGetStringi",
"glGetUniformLocation",
"glGetVertexAttribPointerv",
"glGetVertexAttribiv",
"glIsEnabled",
"glLinkProgram",
"glPixelStorei",
"glPolygonMode",
"glReadPixels",
"glScissor",
"glShaderSource",
"glTexImage2D",
"glTexParameteri",
"glUniform1i",
"glUniformMatrix4fv",
"glUseProgram",
"glVertexAttribPointer",
"glViewport",
};
GL3W_API union GL3WProcs imgl3wProcs;
static void load_procs(GL3WGetProcAddressProc proc)
{
size_t i;
for (i = 0; i < ARRAY_SIZE(proc_names); i++)
imgl3wProcs.ptr[i] = proc(proc_names[i]);
}
#ifdef __cplusplus
}
#endif
#endif
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+627
View File
@@ -0,0 +1,627 @@
// [DEAR IMGUI]
// This is a slightly modified version of stb_rect_pack.h 1.01.
// Grep for [DEAR IMGUI] to find the changes.
//
// stb_rect_pack.h - v1.01 - public domain - rectangle packing
// Sean Barrett 2014
//
// Useful for e.g. packing rectangular textures into an atlas.
// Does not do rotation.
//
// Before #including,
//
// #define STB_RECT_PACK_IMPLEMENTATION
//
// in the file that you want to have the implementation.
//
// Not necessarily the awesomest packing method, but better than
// the totally naive one in stb_truetype (which is primarily what
// this is meant to replace).
//
// Has only had a few tests run, may have issues.
//
// More docs to come.
//
// No memory allocations; uses qsort() and assert() from stdlib.
// Can override those by defining STBRP_SORT and STBRP_ASSERT.
//
// This library currently uses the Skyline Bottom-Left algorithm.
//
// Please note: better rectangle packers are welcome! Please
// implement them to the same API, but with a different init
// function.
//
// Credits
//
// Library
// Sean Barrett
// Minor features
// Martins Mozeiko
// github:IntellectualKitty
//
// Bugfixes / warning fixes
// Jeremy Jaussaud
// Fabian Giesen
//
// Version history:
//
// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section
// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles
// 0.99 (2019-02-07) warning fixes
// 0.11 (2017-03-03) return packing success/fail result
// 0.10 (2016-10-25) remove cast-away-const to avoid warnings
// 0.09 (2016-08-27) fix compiler warnings
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//
// LICENSE
//
// See end of file for license information.
//////////////////////////////////////////////////////////////////////////////
//
// INCLUDE SECTION
//
#ifndef STB_INCLUDE_STB_RECT_PACK_H
#define STB_INCLUDE_STB_RECT_PACK_H
#define STB_RECT_PACK_VERSION 1
#ifdef STBRP_STATIC
#define STBRP_DEF static
#else
#define STBRP_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct stbrp_context stbrp_context;
typedef struct stbrp_node stbrp_node;
typedef struct stbrp_rect stbrp_rect;
typedef int stbrp_coord;
#define STBRP__MAXVAL 0x7fffffff
// Mostly for internal use, but this is the maximum supported coordinate value.
STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
// Assign packed locations to rectangles. The rectangles are of type
// 'stbrp_rect' defined below, stored in the array 'rects', and there
// are 'num_rects' many of them.
//
// Rectangles which are successfully packed have the 'was_packed' flag
// set to a non-zero value and 'x' and 'y' store the minimum location
// on each axis (i.e. bottom-left in cartesian coordinates, top-left
// if you imagine y increasing downwards). Rectangles which do not fit
// have the 'was_packed' flag set to 0.
//
// You should not try to access the 'rects' array from another thread
// while this function is running, as the function temporarily reorders
// the array while it executes.
//
// To pack into another rectangle, you need to call stbrp_init_target
// again. To continue packing into the same rectangle, you can call
// this function again. Calling this multiple times with multiple rect
// arrays will probably produce worse packing results than calling it
// a single time with the full rectangle array, but the option is
// available.
//
// The function returns 1 if all of the rectangles were successfully
// packed and 0 otherwise.
struct stbrp_rect
{
// reserved for your use:
int id;
// input:
stbrp_coord w, h;
// output:
stbrp_coord x, y;
int was_packed; // non-zero if valid packing
}; // 16 bytes, nominally
STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
// Initialize a rectangle packer to:
// pack a rectangle that is 'width' by 'height' in dimensions
// using temporary storage provided by the array 'nodes', which is 'num_nodes' long
//
// You must call this function every time you start packing into a new target.
//
// There is no "shutdown" function. The 'nodes' memory must stay valid for
// the following stbrp_pack_rects() call (or calls), but can be freed after
// the call (or calls) finish.
//
// Note: to guarantee best results, either:
// 1. make sure 'num_nodes' >= 'width'
// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
//
// If you don't do either of the above things, widths will be quantized to multiples
// of small integers to guarantee the algorithm doesn't run out of temporary storage.
//
// If you do #2, then the non-quantized algorithm will be used, but the algorithm
// may run out of temporary storage and be unable to pack some rectangles.
STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
// Optionally call this function after init but before doing any packing to
// change the handling of the out-of-temp-memory scenario, described above.
// If you call init again, this will be reset to the default (false).
STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
// Optionally select which packing heuristic the library should use. Different
// heuristics will produce better/worse results for different data sets.
// If you call init again, this will be reset to the default.
enum
{
STBRP_HEURISTIC_Skyline_default=0,
STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
STBRP_HEURISTIC_Skyline_BF_sortHeight
};
//////////////////////////////////////////////////////////////////////////////
//
// the details of the following structures don't matter to you, but they must
// be visible so you can handle the memory allocations for them
struct stbrp_node
{
stbrp_coord x,y;
stbrp_node *next;
};
struct stbrp_context
{
int width;
int height;
int align;
int init_mode;
int heuristic;
int num_nodes;
stbrp_node *active_head;
stbrp_node *free_head;
stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
};
#ifdef __cplusplus
}
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION SECTION
//
#ifdef STB_RECT_PACK_IMPLEMENTATION
#ifndef STBRP_SORT
#include <stdlib.h>
#define STBRP_SORT qsort
#endif
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#endif
#ifdef _MSC_VER
#define STBRP__NOTUSED(v) (void)(v)
#define STBRP__CDECL __cdecl
#else
#define STBRP__NOTUSED(v) (void)sizeof(v)
#define STBRP__CDECL
#endif
enum
{
STBRP__INIT_skyline = 1
};
STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
{
switch (context->init_mode) {
case STBRP__INIT_skyline:
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
context->heuristic = heuristic;
break;
default:
STBRP_ASSERT(0);
}
}
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
{
if (allow_out_of_mem)
// if it's ok to run out of memory, then don't bother aligning them;
// this gives better packing, but may fail due to OOM (even though
// the rectangles easily fit). @TODO a smarter approach would be to only
// quantize once we've hit OOM, then we could get rid of this parameter.
context->align = 1;
else {
// if it's not ok to run out of memory, then quantize the widths
// so that num_nodes is always enough nodes.
//
// I.e. num_nodes * align >= width
// align >= width / num_nodes
// align = ceil(width/num_nodes)
context->align = (context->width + context->num_nodes-1) / context->num_nodes;
}
}
STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
{
int i;
for (i=0; i < num_nodes-1; ++i)
nodes[i].next = &nodes[i+1];
nodes[i].next = NULL;
context->init_mode = STBRP__INIT_skyline;
context->heuristic = STBRP_HEURISTIC_Skyline_default;
context->free_head = &nodes[0];
context->active_head = &context->extra[0];
context->width = width;
context->height = height;
context->num_nodes = num_nodes;
stbrp_setup_allow_out_of_mem(context, 0);
// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
context->extra[0].x = 0;
context->extra[0].y = 0;
context->extra[0].next = &context->extra[1];
context->extra[1].x = (stbrp_coord) width;
context->extra[1].y = (1<<30);
context->extra[1].next = NULL;
}
// find minimum y position if it starts at x1
static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
{
stbrp_node *node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
STBRP__NOTUSED(c);
STBRP_ASSERT(first->x <= x0);
#if 0
// skip in case we're past the node
while (node->next->x <= x0)
++node;
#else
STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
#endif
STBRP_ASSERT(node->x <= x0);
min_y = 0;
waste_area = 0;
visited_width = 0;
while (node->x < x1) {
if (node->y > min_y) {
// raise min_y higher.
// we've accounted for all waste up to min_y,
// but we'll now add more waste for everything we've visted
waste_area += visited_width * (node->y - min_y);
min_y = node->y;
// the first time through, visited_width might be reduced
if (node->x < x0)
visited_width += node->next->x - x0;
else
visited_width += node->next->x - node->x;
} else {
// add waste area
int under_width = node->next->x - node->x;
if (under_width + visited_width > width)
under_width = width - visited_width;
waste_area += under_width * (min_y - node->y);
visited_width += under_width;
}
node = node->next;
}
*pwaste = waste_area;
return min_y;
}
typedef struct
{
int x,y;
stbrp_node **prev_link;
} stbrp__findresult;
static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
{
int best_waste = (1<<30), best_x, best_y = (1 << 30);
stbrp__findresult fr;
stbrp_node **prev, *node, *tail, **best = NULL;
// align to multiple of c->align
width = (width + c->align - 1);
width -= width % c->align;
STBRP_ASSERT(width % c->align == 0);
// if it can't possibly fit, bail immediately
if (width > c->width || height > c->height) {
fr.prev_link = NULL;
fr.x = fr.y = 0;
return fr;
}
node = c->active_head;
prev = &c->active_head;
while (node->x + width <= c->width) {
int y,waste;
y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
// bottom left
if (y < best_y) {
best_y = y;
best = prev;
}
} else {
// best-fit
if (y + height <= c->height) {
// can only use it if it first vertically
if (y < best_y || (y == best_y && waste < best_waste)) {
best_y = y;
best_waste = waste;
best = prev;
}
}
}
prev = &node->next;
node = node->next;
}
best_x = (best == NULL) ? 0 : (*best)->x;
// if doing best-fit (BF), we also have to try aligning right edge to each node position
//
// e.g, if fitting
//
// ____________________
// |____________________|
//
// into
//
// | |
// | ____________|
// |____________|
//
// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
//
// This makes BF take about 2x the time
if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
tail = c->active_head;
node = c->active_head;
prev = &c->active_head;
// find first node that's admissible
while (tail->x < width)
tail = tail->next;
while (tail) {
int xpos = tail->x - width;
int y,waste;
STBRP_ASSERT(xpos >= 0);
// find the left position that matches this
while (node->next->x <= xpos) {
prev = &node->next;
node = node->next;
}
STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
if (y + height <= c->height) {
if (y <= best_y) {
if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
best_x = xpos;
//STBRP_ASSERT(y <= best_y); [DEAR IMGUI]
best_y = y;
best_waste = waste;
best = prev;
}
}
}
tail = tail->next;
}
}
fr.prev_link = best;
fr.x = best_x;
fr.y = best_y;
return fr;
}
static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
{
// find best position according to heuristic
stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
stbrp_node *node, *cur;
// bail if:
// 1. it failed
// 2. the best node doesn't fit (we don't always check this)
// 3. we're out of memory
if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
res.prev_link = NULL;
return res;
}
// on success, create new node
node = context->free_head;
node->x = (stbrp_coord) res.x;
node->y = (stbrp_coord) (res.y + height);
context->free_head = node->next;
// insert the new node into the right starting point, and
// let 'cur' point to the remaining nodes needing to be
// stiched back in
cur = *res.prev_link;
if (cur->x < res.x) {
// preserve the existing one, so start testing with the next one
stbrp_node *next = cur->next;
cur->next = node;
cur = next;
} else {
*res.prev_link = node;
}
// from here, traverse cur and free the nodes, until we get to one
// that shouldn't be freed
while (cur->next && cur->next->x <= res.x + width) {
stbrp_node *next = cur->next;
// move the current node to the free list
cur->next = context->free_head;
context->free_head = cur;
cur = next;
}
// stitch the list back in
node->next = cur;
if (cur->x < res.x + width)
cur->x = (stbrp_coord) (res.x + width);
#ifdef _DEBUG
cur = context->active_head;
while (cur->x < context->width) {
STBRP_ASSERT(cur->x < cur->next->x);
cur = cur->next;
}
STBRP_ASSERT(cur->next == NULL);
{
int count=0;
cur = context->active_head;
while (cur) {
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes+2);
}
#endif
return res;
}
static int STBRP__CDECL rect_height_compare(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
if (p->h > q->h)
return -1;
if (p->h < q->h)
return 1;
return (p->w > q->w) ? -1 : (p->w < q->w);
}
static int STBRP__CDECL rect_original_order(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
}
STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
int i, all_rects_packed = 1;
// we use the 'was_packed' field internally to allow sorting/unsorting
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = i;
}
// sort according to heuristic
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
for (i=0; i < num_rects; ++i) {
if (rects[i].w == 0 || rects[i].h == 0) {
rects[i].x = rects[i].y = 0; // empty rect needs no space
} else {
stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
if (fr.prev_link) {
rects[i].x = (stbrp_coord) fr.x;
rects[i].y = (stbrp_coord) fr.y;
} else {
rects[i].x = rects[i].y = STBRP__MAXVAL;
}
}
}
// unsort
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
// set was_packed flags and all_rects_packed status
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
if (!rects[i].was_packed)
all_rects_packed = 0;
}
// return the all_rects_packed status
return all_rects_packed;
}
#endif
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Evan Pezent
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+166
View File
@@ -0,0 +1,166 @@
# ImPlot
ImPlot is an immediate mode, GPU accelerated plotting library for [Dear ImGui](https://github.com/ocornut/imgui). It aims to provide a first-class API that ImGui fans will love. ImPlot is well suited for visualizing program data in real-time or creating interactive plots, and requires minimal code to integrate. Just like ImGui, it does not burden the end user with GUI state management, avoids STL containers and C++ headers, and has no external dependencies except for ImGui itself.
<img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/controls.gif" width="270"> <img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/dnd.gif" width="270"> <img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/pie.gif" width="270">
<img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/query.gif" width="270"> <img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/bars.gif" width="270">
<img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/rt.gif" width="270">
<img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/stem.gif" width="270"> <img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/markers.gif" width="270">
<img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/shaded.gif" width="270">
<img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/candle.gif" width="270"> <img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/heat.gif" width="270">
<img src="https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/tables.gif" width="270">
## Features
- GPU accelerated rendering
- multiple plot types:
- line plots
- shaded plots
- scatter plots
- vertical/horizontal/stacked bars graphs
- vertical/horizontal error bars
- stem plots
- stair plots
- pie charts
- heatmap charts
- 1D/2D histograms
- images
- and more likely to come
- mix/match multiple plot items on a single plot
- configurable axes ranges and scaling (linear/log)
- subplots
- time formatted x-axes (US formatted or ISO 8601)
- reversible and lockable axes
- multiple x-axes and y-axes
- controls for zooming, panning, box selection, and auto-fitting data
- controls for creating persistent query ranges (see demo)
- several plot styling options: 10 marker types, adjustable marker sizes, line weights, outline colors, fill colors, etc.
- 16 built-in colormaps and support for and user-added colormaps
- optional plot titles, axis labels, and grid labels
- optional and configurable legends with toggle buttons to quickly show/hide plot items
- default styling based on current ImGui theme, or completely custom plot styles
- customizable data getters and data striding (just like ImGui:PlotLine)
- accepts data as float, double, and 8, 16, 32, and 64-bit signed/unsigned integral types
- and more! (see Announcements [2020](https://github.com/epezent/implot/issues/48)/[2021](https://github.com/epezent/implot/issues/168))
## Usage
The API is used just like any other ImGui `BeginX`/`EndX` pair. First, start a new plot with `ImPlot::BeginPlot()`. Next, plot as many items as you want with the provided `PlotX` functions (e.g. `PlotLine()`, `PlotBars()`, `PlotScatter()`, etc). Finally, wrap things up with a call to `ImPlot::EndPlot()`. That's it!
```cpp
int bar_data[11] = ...;
float x_data[1000] = ...;
float y_data[1000] = ...;
ImGui::Begin("My Window");
if (ImPlot::BeginPlot("My Plot")) {
ImPlot::PlotBars("My Bar Plot", bar_data, 11);
ImPlot::PlotLine("My Line Plot", x_data, y_data, 1000);
...
ImPlot::EndPlot();
}
ImGui::End();
```
![Usage](https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/example.PNG)
Of course, there's much more you can do with ImPlot...
## Demos
A comprehensive example of ImPlot's features can be found in `implot_demo.h`. Add this file to your sources and call `ImPlot::ShowDemoWindow()` somewhere in your update loop. You are encouraged to use this file as a reference when needing to implement various plot types. The demo is always updated to show new plot types and features as they are added, so check back with each release!
An online version of the demo is hosted [here](https://traineq.org/implot_demo/src/implot_demo.html). You can view the plots and the source code that generated them. Note that this demo may not always be up to date and is not as performant as a desktop implementation, but it should give you a general taste of what's possible with ImPlot. Special thanks to [pthom](https://github.com/pthom) for creating and hosting this!
More sophisticated demos requiring lengthier code and/or third-party libraries can be found in a separate repository: [implot_demos](https://github.com/epezent/implot_demos). Here, you will find advanced signal processing and ImPlot usage in action. Please read the `Contributing` section of that repository if you have an idea for a new demo!
## Integration
0) Set up an [ImGui](https://github.com/ocornut/imgui) environment if you don't already have one.
1) Add `implot.h`, `implot_internal.h`, `implot.cpp`, `implot_items.cpp` and optionally `implot_demo.cpp` to your sources. Alternatively, you can get ImPlot using [vcpkg](https://github.com/microsoft/vcpkg/tree/master/ports/implot).
2) Create and destroy an `ImPlotContext` wherever you do so for your `ImGuiContext`:
```cpp
ImGui::CreateContext();
ImPlot::CreateContext();
...
ImPlot::DestroyContext();
ImGui::DestroyContext();
```
You should be good to go!
If you want to test ImPlot quickly, consider trying [mahi-gui](https://github.com/mahilab/mahi-gui), which bundles ImGui, ImPlot, and several other packages for you.
## Extremely Important Note
Dear ImGui uses **16-bit indexing by default**, so high-density ImPlot widgets like `ImPlot::PlotHeatmap()` may produce too many vertices into `ImDrawList`, which causes an assertion failure and will result in data truncation and/or visual glitches. Therefore, it is **HIGHLY** recommended that you EITHER:
- **Option 1:** Enable 32-bit indices by uncommenting `#define ImDrawIdx unsigned int` in your ImGui [`imconfig.h`](https://github.com/ocornut/imgui/blob/master/imconfig.h#L89) file.
- **Option 2:** Handle the `ImGuiBackendFlags_RendererHasVtxOffset` flag in your renderer if you must use 16-bit indices. Many of the default ImGui rendering backends already support `ImGuiBackendFlags_RendererHasVtxOffset`. Refer to [this issue](https://github.com/ocornut/imgui/issues/2591) for more information.
## FAQ
**Q: Why?**
A: ImGui is an incredibly powerful tool for rapid prototyping and development, but provides only limited mechanisms for data visualization. Two dimensional plots are ubiquitous and useful to almost any application. Being able to visualize your data in real-time will give you insight and better understanding of your application.
**Q: Is ImPlot the right plotting library for me?**
A: If you're looking to generate publication quality plots and/or export plots to a file, ImPlot is NOT the library for you! ImPlot is geared toward plotting application data at realtime speeds with high levels of interactivity. ImPlot does its best to create pretty plots (indeed, there are quite a few styling options available), but it will always favor function over form.
**Q: Where is the documentation?**
A: The API is thoroughly commented in `implot.h`, and the demo in `implot_demo.cpp` should be more than enough to get you started. Also take a look at the [implot_demos](https://github.com/epezent/implot_demos) repository.
**Q: Is ImPlot suitable for plotting large datasets?**
A: Yes, within reason. You can plot tens to hundreds of thousands of points without issue, but don't expect millions to be a buttery smooth experience. That said, you can always downsample extremely large datasets by telling ImPlot to stride your data at larger intervals if needed. Also try the experimental `backends` branch which aims to provide GPU acceleration support.
**Q: What data types can I plot?**
A: ImPlot plotting functions accept most scalar types:
`float`, `double`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `uint32`, `int64`, `uint64`. Arrays of custom structs or classes (e.g. `Vector2f` or similar) are easily passed to ImPlot functions using the built in striding features (see `implot.h` for documentation), and many plotters provide a "getter" overload which accepts data generating callbacks.
**Q: Can plot styles be modified?**
A: Yes. Data colormaps and various styling colors and variables can be pushed/popped or modified permanently on startup. Three default styles are available, as well as an automatic style that attempts to match you ImGui style.
**Q: Does ImPlot support logarithmic scaling or time formatting?**
A: Yep! Both logscale and timescale are supported.
**Q: Does ImPlot support multiple y-axes? x-axes?**
A: Yes. Up to three x-axes and three y-axes can be enabled.
**Q: Does ImPlot support [insert plot type]?**
A: Maybe. Check the demo, gallery, or Announcements ([2020](https://github.com/epezent/implot/issues/48)/[2021](https://github.com/epezent/implot/issues/168))to see if your desired plot type is shown. If not, consider submitting an issue or better yet, a PR!
**Q: Does ImPlot support 3D plots?**
A: No, and likely never will since ImGui only deals in 2D rendering.
**Q: My plot lines look like crap!**
A: By default, no anti-aliasing is done on line plots for performance gains. If you use at least 4x MSAA, then you likely won't even notice. However, you can enable software AA per-plot with the `ImPlotFlags_AntiAliased` flag, or globally with `ImPlot::GetStyle().AntiAliasedLines = true;`.
**Q: Does ImPlot provide analytic tools?**
A: Not exactly, but it does give you the ability to query plot sub-ranges, with which you can process your data however you like.
**Q: Can plots be exported/saved to image?**
A: Not currently. Use your OS's screen capturing mechanisms if you need to capture a plot. ImPlot is not suitable for rendering publication quality plots; it is only intended to be used as a visualization tool. Post-process your data with MATLAB or matplotlib for these purposes.
**Q: Can I compile ImPlot as a dynamic library?**
A: Like ImGui, it is recommended that you compile and link ImPlot as a *static* library or directly as a part of your sources. However, if you must and are compiling ImPlot and ImGui as separate DLLs, make sure you set the current *ImGui* context with `ImPlot::SetImGuiContext(ImGuiContext* ctx)`. This ensures that global ImGui variables are correctly shared across the DLL boundary.
**Q: Can ImPlot be used with other languages/bindings?**
A: Yes, you can use the generated C binding, [cimplot](https://github.com/cimgui/cimplot) with most high level languages. [DearPyGui](https://github.com/hoffstadt/DearPyGui) provides a Python wrapper, among other things. [imgui-java](https://github.com/SpaiR/imgui-java) provides bindings for Java. A Rust binding, [implot-rs](https://github.com/4bb4/implot-rs), is currently in the works. An example using Emscripten can be found [here](https://github.com/pthom/implot_demo).
+69
View File
@@ -0,0 +1,69 @@
The list below represents a combination of high-priority work, nice-to-have features, and random ideas. We make no guarantees that all of this work will be completed or even started. If you see something that you need or would like to have, let us know, or better yet consider submitting a PR for the feature.
## API
- add shortcut/legacy overloads for BeginPlot
## Axes
- add flag to remove weekends on Time axis
- pixel space scale (`ImPlotTransform_Display`), normalized space scale (`ImPlotTransform_Axes`), data space scale (`ImPloTransform_Data`)
- make ImPlotFlags_Equal not a flag -> `SetupEqual(ImPlotAxis x, ImPlotAxis y)`
- allow inverted arguments `SetAxes` to transpose data?
- `SetupAxisColors()`
- `SetupAxisConstraints()`
- `SetupAxisHome()`
## Plot Items
- add `ImPlotLineFlags`, `ImPlotBarsFlags`, etc. for each plot type
- add `PlotBarGroups` wrapper that makes rendering groups of bars easier, with stacked bar support
- add `PlotBubbles` (see MATLAB bubble chart)
- add non-zero references for `PlotBars` etc.
- add exploding to `PlotPieChart` (on hover-highlight?)
## Styling
- support gradient and/or colormap sampled fills (e.g. ImPlotFillStyle_)
- add hover/active color for plot axes
- API for setting different fonts for plot elements
## Colormaps
- gradient editing tool
- `RemoveColormap`
## Legend
- `ImPlotLegendFlags_SortItems`
- `ImPlotLegendFlags_Scroll`
- improve legend icons (e.g. adopt markers, gradients, etc)
- make legend frame use ButtonBehavior (maybe impossible)
## Tools / Misc.
- add `IsPlotChanging` to detect change in limits
- add ability to extend plot/axis context menus
- add LTTB downsampling for lines
- add box selection to axes
- first frame render delay might fix "fit pop" effect
- move some code to new `implot_tools.cpp`
## Optimizations
- find faster way to buffer data into ImDrawList (very slow)
- reduce number of calls to `PushClipRect`
- explore SIMD operations for high density plot items
## Completed
- make BeginPlot take fewer args:
- make query a tool -> `DragRect`
- rework DragLine/Point to use ButtonBehavior
- add support for multiple x-axes and don't limit count to 3
- make axis side configurable (top/left, right/bottom) via new flag `ImPlotAxisFlags_Opposite`
- add support for setting tick label strings via callback
- give each axis an ID, remove ad-hoc DND solution
- allow axis to be drag to opposite side (ala ImGui Table headers)
- legend items can be hovered even if plot is not
- fix frame delay on DragX tools
- remove tag from drag line/point -> add `Tag` tool
File diff suppressed because it is too large. Load diff
+1143
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-484
View File
@@ -1,484 +0,0 @@
#pragma once
#include "vrinputemulator_types.h"
#include <utility>
#define IPC_PROTOCOL_VERSION 3
namespace vrinputemulator {
namespace ipc {
enum class RequestType : uint32_t {
None,
// IPC connection handling
IPC_ClientConnect,
IPC_ClientDisconnect,
IPC_Ping,
// These are indented to inject events into OpenVR and require an OpenVR device id.
// These are "fire and forget".
OpenVR_PoseUpdate,
OpenVR_ButtonEvent,
OpenVR_AxisEvent,
OpenVR_ProximitySensorEvent,
OpenVR_VendorSpecificEvent,
// These are indented to manage virtual devices and require the internal device id.
// The Reply is send to the client's message queue.
VirtualDevices_AddDevice,
VirtualDevices_PublishDevice,
VirtualDevices_GetDeviceCount,
VirtualDevices_GetDeviceInfo,
VirtualDevices_GetDevicePose,
VirtualDevices_GetControllerState,
VirtualDevices_SetDeviceProperty,
VirtualDevices_RemoveDeviceProperty,
VirtualDevices_SetDevicePose,
VirtualDevices_SetControllerState,
DeviceManipulation_GetDeviceInfo,
DeviceManipulation_ButtonMapping,
DeviceManipulation_GetDeviceOffsets,
DeviceManipulation_SetDeviceOffsets,
DeviceManipulation_DefaultMode,
DeviceManipulation_RedirectMode,
DeviceManipulation_SwapMode,
DeviceManipulation_MotionCompensationMode,
DeviceManipulation_FakeDisconnectedMode,
DeviceManipulation_TriggerHapticPulse,
DeviceManipulation_SetMotionCompensationProperties,
InputRemapping_SetDigitalRemapping,
InputRemapping_GetDigitalRemapping,
InputRemapping_SetAnalogRemapping,
InputRemapping_GetAnalogRemapping,
InputRemapping_SetTouchpadEmulationFixEnabled
};
enum class ReplyType : uint32_t {
None,
IPC_ClientConnect,
IPC_Ping,
GenericReply,
VirtualDevices_GetDeviceCount,
VirtualDevices_GetDeviceInfo,
VirtualDevices_GetDevicePose,
VirtualDevices_GetControllerState,
VirtualDevices_AddDevice,
DeviceManipulation_GetDeviceInfo,
DeviceManipulation_GetDeviceOffsets,
InputRemapping_GetDigitalRemapping,
InputRemapping_GetAnalogRemapping
};
enum class ReplyStatus : uint32_t {
None,
Ok,
UnknownError,
InvalidId,
AlreadyInUse,
InvalidType,
NotFound,
TooManyDevices,
InvalidVersion,
MissingProperty,
InvalidOperation,
NotTracking
};
struct Request_IPC_ClientConnect {
uint32_t messageId;
uint32_t ipcProcotolVersion;
char queueName[128];
};
struct Request_IPC_ClientDisconnect {
uint32_t clientId;
uint32_t messageId;
};
struct Request_IPC_Ping {
uint32_t clientId;
uint32_t messageId;
uint64_t nonce;
};
struct Request_OpenVR_PoseUpdate {
uint32_t deviceId;
vr::DriverPose_t pose;
};
#define REQUEST_OPENVR_BUTTONEVENT_MAXCOUNT 12
struct Request_OpenVR_ButtonEvent {
unsigned eventCount;
struct {
ButtonEventType eventType;
uint32_t deviceId;
vr::EVRButtonId buttonId;
double timeOffset;
} events[REQUEST_OPENVR_BUTTONEVENT_MAXCOUNT];
};
#define REQUEST_OPENVR_AXISEVENT_MAXCOUNT 12
struct Request_OpenVR_AxisEvent {
unsigned eventCount;
struct {
uint32_t deviceId;
uint32_t axisId;
vr::VRControllerAxis_t axisState;
} events[REQUEST_OPENVR_AXISEVENT_MAXCOUNT];
};
struct Request_OpenVR_ProximitySensorEvent {
uint32_t deviceId;
bool sensorTriggered;
};
struct Request_OpenVR_VendorSpecificEvent {
uint32_t deviceId;
vr::EVREventType eventType;
vr::VREvent_Data_t eventData;
double timeOffset;
};
struct Request_VirtualDevices_GenericClientMessage {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
};
struct Request_VirtualDevices_GenericDeviceIdMessage {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t deviceId;
};
struct Request_VirtualDevices_AddDevice {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
VirtualDeviceType deviceType;
char deviceSerial[256];
};
struct Request_VirtualDevices_SetDeviceProperty {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t virtualDeviceId;
vr::ETrackedDeviceProperty deviceProperty;
DevicePropertyValueType valueType;
union {
int32_t int32Value;
uint64_t uint64Value;
float floatValue;
bool boolValue;
char stringValue[256];
vr::HmdMatrix34_t matrix34Value;
vr::HmdMatrix44_t matrix44Value;
vr::HmdVector3_t vector3Value;
vr::HmdVector4_t vector4Value;
} value;
};
struct Request_VirtualDevices_RemoveDeviceProperty {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t virtualDeviceId;
vr::ETrackedDeviceProperty deviceProperty;
};
struct Request_VirtualDevices_SetDevicePose {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t virtualDeviceId;
vr::DriverPose_t pose;
};
struct Request_VirtualDevices_SetControllerState {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t virtualDeviceId;
vr::VRControllerState_t controllerState;
};
struct Request_DeviceManipulation_ButtonMapping {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t deviceId;
uint32_t enableMapping; // 0 .. don't change, 1 .. enable, 2 .. disable
uint32_t mappingOperation; // 0 .. do nothing, 1 .. add given mappings, 2 .. remove given mappings, 3 .. remove all mappings
uint32_t mappingCount;
vr::EVRButtonId buttonMappings[32];
};
struct Request_DeviceManipulation_SetDeviceOffsets {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t deviceId;
uint32_t enableOffsets; // 0 .. don't change, 1 .. enable, 2 .. disable
uint32_t offsetOperation; // 0 .. set, 1 .. add
// world-from-driver universe offsets
bool worldFromDriverRotationOffsetValid;
vr::HmdQuaternion_t worldFromDriverRotationOffset;
bool worldFromDriverTranslationOffsetValid;
vr::HmdVector3d_t worldFromDriverTranslationOffset;
// driver-from-head universe offsets
bool driverFromHeadRotationOffsetValid;
vr::HmdQuaternion_t driverFromHeadRotationOffset;
bool driverFromHeadTranslationOffsetValid;
vr::HmdVector3d_t driverFromHeadTranslationOffset;
// device offsets
bool deviceRotationOffsetValid;
vr::HmdQuaternion_t deviceRotationOffset;
bool deviceTranslationOffsetValid;
vr::HmdVector3d_t deviceTranslationOffset;
};
struct Request_DeviceManipulation_RedirectMode {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t deviceId;
uint32_t targetId;
};
struct Request_DeviceManipulation_SwapMode {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t deviceId;
uint32_t targetId;
};
struct Request_DeviceManipulation_MotionCompensationMode {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t deviceId;
MotionCompensationVelAccMode velAccCompensationMode;
};
struct Request_DeviceManipulation_TriggerHapticPulse {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t deviceId;
uint32_t axisId;
uint16_t durationMicroseconds;
bool directMode;
};
struct Request_DeviceManipulation_SetMotionCompensationProperties {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
bool velAccCompensationModeValid;
MotionCompensationVelAccMode velAccCompensationMode;
bool kalmanFilterProcessNoiseValid;
double kalmanFilterProcessNoise;
bool kalmanFilterObservationNoiseValid;
double kalmanFilterObservationNoise;
bool movingAverageWindowValid;
unsigned movingAverageWindow;
};
struct Request_InputRemapping_SetDigitalRemapping {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t controllerId;
uint32_t buttonId;
DigitalInputRemapping remapData;
};
struct Request_InputRemapping_GetDigitalRemapping {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t controllerId;
uint32_t buttonId;
};
struct Request_InputRemapping_SetAnalogRemapping {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t controllerId;
uint32_t axisId;
AnalogInputRemapping remapData;
};
struct Request_InputRemapping_GetAnalogRemapping {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
uint32_t controllerId;
uint32_t axisId;
};
struct Request_InputRemapping_SetTouchpadEmulationFixEnabled {
uint32_t clientId;
uint32_t messageId; // Used to associate with Reply
bool enable;
};
struct Request {
Request() {}
Request(RequestType type) : type(type) {
timestamp = std::chrono::duration_cast <std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
Request(RequestType type, uint64_t timestamp) : type(type), timestamp(timestamp) {}
void refreshTimestamp() {
timestamp = std::chrono::duration_cast <std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
RequestType type = RequestType::None;
int64_t timestamp = 0; // milliseconds since epoch
union MsgUnion {
Request_IPC_ClientConnect ipc_ClientConnect;
Request_IPC_ClientDisconnect ipc_ClientDisconnect;
Request_IPC_Ping ipc_Ping;
Request_OpenVR_PoseUpdate ipc_PoseUpdate;
Request_OpenVR_ButtonEvent ipc_ButtonEvent;
Request_OpenVR_AxisEvent ipc_AxisEvent;
Request_OpenVR_ProximitySensorEvent ovr_ProximitySensorEvent;
Request_OpenVR_VendorSpecificEvent ovr_VendorSpecificEvent;
Request_VirtualDevices_GenericClientMessage vd_GenericClientMessage;
Request_VirtualDevices_GenericDeviceIdMessage vd_GenericDeviceIdMessage;
Request_VirtualDevices_AddDevice vd_AddDevice;
Request_VirtualDevices_SetDeviceProperty vd_SetDeviceProperty;
Request_VirtualDevices_RemoveDeviceProperty vd_RemoveDeviceProperty;
Request_VirtualDevices_SetDevicePose vd_SetDevicePose;
Request_VirtualDevices_SetControllerState vd_SetControllerState;
Request_DeviceManipulation_ButtonMapping dm_ButtonMapping;
Request_DeviceManipulation_SetDeviceOffsets dm_DeviceOffsets;
Request_DeviceManipulation_RedirectMode dm_RedirectMode;
Request_DeviceManipulation_SwapMode dm_SwapMode;
Request_DeviceManipulation_MotionCompensationMode dm_MotionCompensationMode;
Request_DeviceManipulation_TriggerHapticPulse dm_triggerHapticPulse;
Request_DeviceManipulation_SetMotionCompensationProperties dm_SetMotionCompensationProperties;
Request_InputRemapping_SetDigitalRemapping ir_SetDigitalRemapping;
Request_InputRemapping_GetDigitalRemapping ir_GetDigitalRemapping;
Request_InputRemapping_SetAnalogRemapping ir_SetAnalogRemapping;
Request_InputRemapping_GetAnalogRemapping ir_GetAnalogRemapping;
Request_InputRemapping_SetTouchpadEmulationFixEnabled ir_SetTouchPadEmulationFixEnabled;
MsgUnion() {}
} msg;
};
struct Reply_IPC_ClientConnect {
uint32_t clientId;
uint32_t ipcProcotolVersion;
};
struct Reply_IPC_Ping {
uint64_t nonce;
};
struct Reply_VirtualDevices_GetDeviceCount {
uint32_t deviceCount;
};
struct Reply_VirtualDevices_GetDeviceInfo {
uint32_t virtualDeviceId;
uint32_t openvrDeviceId;
VirtualDeviceType deviceType;
char deviceSerial[128];
};
struct Reply_VirtualDevices_GetDevicePose {
vr::DriverPose_t pose;
};
struct Reply_VirtualDevices_GetControllerState {
vr::VRControllerState_t controllerState;
};
struct Reply_VirtualDevices_AddDevice {
uint32_t virtualDeviceId;
};
struct Reply_DeviceManipulation_GetDeviceInfo {
uint32_t deviceId;
vr::ETrackedDeviceClass deviceClass;
int deviceMode;
uint32_t refDeviceId;
bool offsetsEnabled;
bool redirectSuspended;
};
struct Reply_DeviceManipulation_GetDeviceOffsets {
uint32_t deviceId;
bool offsetsEnabled;
vr::HmdQuaternion_t worldFromDriverRotationOffset;
vr::HmdVector3d_t worldFromDriverTranslationOffset;
vr::HmdQuaternion_t driverFromHeadRotationOffset;
vr::HmdVector3d_t driverFromHeadTranslationOffset;
vr::HmdQuaternion_t deviceRotationOffset;
vr::HmdVector3d_t deviceTranslationOffset;
};
struct Reply_InputRemapping_GetDigitalRemapping {
uint32_t deviceId;
uint32_t buttonId;
DigitalInputRemapping remapData;
};
struct Reply_InputRemapping_GetAnalogRemapping {
uint32_t deviceId;
uint32_t axisId;
AnalogInputRemapping remapData;
};
struct Reply {
Reply() {}
Reply(ReplyType type) : type(type) {
timestamp = std::chrono::duration_cast <std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
Reply(ReplyType type, uint64_t timestamp) : type(type), timestamp(timestamp) {}
ReplyType type = ReplyType::None;
uint64_t timestamp = 0; // milliseconds since epoch
uint32_t messageId;
ReplyStatus status;
union MsgUnion {
Reply_IPC_ClientConnect ipc_ClientConnect;
Reply_IPC_Ping ipc_Ping;
Reply_VirtualDevices_GetDeviceCount vd_GetDeviceCount;
Reply_VirtualDevices_GetDeviceInfo vd_GetDeviceInfo;
Reply_VirtualDevices_GetDevicePose vd_GetDevicePose;
Reply_VirtualDevices_GetControllerState vd_GetControllerState;
Reply_VirtualDevices_AddDevice vd_AddDevice;
Reply_DeviceManipulation_GetDeviceInfo dm_deviceInfo;
Reply_DeviceManipulation_GetDeviceOffsets dm_deviceOffsets;
Reply_InputRemapping_GetDigitalRemapping ir_getDigitalRemapping;
Reply_InputRemapping_GetAnalogRemapping ir_getAnalogRemapping;
MsgUnion() {}
} msg;
};
} // end namespace ipc
} // end namespace vrinputemulator
File diff suppressed because it is too large. Load diff
-229
View File
@@ -1,229 +0,0 @@
#pragma once
#include <stdint.h>
#include <string>
#include <future>
#include <mutex>
#include <thread>
#include <map>
#include <memory>
#include <random>
#include <string>
#include <openvr.h>
#include <boost/interprocess/ipc/message_queue.hpp>
namespace vr {
// Copied from openvr_driver.h
struct DriverPose_t {
/* Time offset of this pose, in seconds from the actual time of the pose,
* relative to the time of the PoseUpdated() call made by the driver.
*/
double poseTimeOffset;
/* Generally, the pose maintained by a driver
* is in an inertial coordinate system different
* from the world system of x+ right, y+ up, z+ back.
* Also, the driver is not usually tracking the "head" position,
* but instead an internal IMU or another reference point in the HMD.
* The following two transforms transform positions and orientations
* to app world space from driver world space,
* and to HMD head space from driver local body space.
*
* We maintain the driver pose state in its internal coordinate system,
* so we can do the pose prediction math without having to
* use angular acceleration. A driver's angular acceleration is generally not measured,
* and is instead calculated from successive samples of angular velocity.
* This leads to a noisy angular acceleration values, which are also
* lagged due to the filtering required to reduce noise to an acceptable level.
*/
vr::HmdQuaternion_t qWorldFromDriverRotation;
double vecWorldFromDriverTranslation[3];
vr::HmdQuaternion_t qDriverFromHeadRotation;
double vecDriverFromHeadTranslation[3];
/* State of driver pose, in meters and radians. */
/* Position of the driver tracking reference in driver world space
* +[0] (x) is right
* +[1] (y) is up
* -[2] (z) is forward
*/
double vecPosition[3];
/* Velocity of the pose in meters/second */
double vecVelocity[3];
/* Acceleration of the pose in meters/second */
double vecAcceleration[3];
/* Orientation of the tracker, represented as a quaternion */
vr::HmdQuaternion_t qRotation;
/* Angular velocity of the pose in axis-angle
* representation. The direction is the angle of
* rotation and the magnitude is the angle around
* that axis in radians/second. */
double vecAngularVelocity[3];
/* Angular acceleration of the pose in axis-angle
* representation. The direction is the angle of
* rotation and the magnitude is the angle around
* that axis in radians/second^2. */
double vecAngularAcceleration[3];
ETrackingResult result;
bool poseIsValid;
bool willDriftInYaw;
bool shouldApplyHeadModel;
bool deviceIsConnected;
};
} // end namespace vr
#include "ipc_protocol.h"
namespace vrinputemulator {
class vrinputemulator_exception : public std::runtime_error {
public:
const int errorcode = 0;
using std::runtime_error::runtime_error;
vrinputemulator_exception(const std::string& msg, int code) : std::runtime_error(msg), errorcode(code) {}
};
class vrinputemulator_connectionerror : public vrinputemulator_exception {
using vrinputemulator_exception::vrinputemulator_exception;
};
class vrinputemulator_invalidversion : public vrinputemulator_exception {
using vrinputemulator_exception::vrinputemulator_exception;
};
class vrinputemulator_invalidid : public vrinputemulator_exception {
using vrinputemulator_exception::vrinputemulator_exception;
};
class vrinputemulator_invalidtype : public vrinputemulator_exception {
using vrinputemulator_exception::vrinputemulator_exception;
};
class vrinputemulator_notfound : public vrinputemulator_exception {
using vrinputemulator_exception::vrinputemulator_exception;
};
class vrinputemulator_alreadyinuse : public vrinputemulator_exception {
using vrinputemulator_exception::vrinputemulator_exception;
};
class vrinputemulator_toomanydevices : public vrinputemulator_exception {
using vrinputemulator_exception::vrinputemulator_exception;
};
struct VirtualDeviceInfo {
uint32_t virtualDeviceId;
uint32_t openvrDeviceId;
VirtualDeviceType deviceType;
std::string deviceSerial;
};
class VRInputEmulator {
public:
VRInputEmulator(const std::string& driverQueue = "driver_vrinputemulator.server_queue", const std::string& clientQueue = "driver_vrinputemulator.client_queue.");
~VRInputEmulator();
void connect();
bool isConnected() const;
void disconnect();
void ping(bool modal = true, bool enableReply = false);
void openvrUpdatePose(uint32_t deviceId, const vr::DriverPose_t& pose);
void openvrButtonEvent(ButtonEventType eventType, uint32_t deviceId, vr::EVRButtonId buttonId, double timeOffset = 0.0);
void openvrAxisEvent(uint32_t deviceId, uint32_t axisId, const vr::VRControllerAxis_t& axisState);
void openvrProximitySensorEvent(uint32_t deviceId, bool sensorTriggered);
void openvrVendorSpecificEvent(uint32_t deviceId, vr::EVREventType eventType, const vr::VREvent_Data_t& eventData, double timeOffset = 0.0);
uint32_t getVirtualDeviceCount();
VirtualDeviceInfo getVirtualDeviceInfo(uint32_t virtualDeviceId);
vr::DriverPose_t getVirtualDevicePose(uint32_t virtualDeviceId);
vr::VRControllerState_t getVirtualControllerState(uint32_t virtualDeviceId);
uint32_t addVirtualDevice(VirtualDeviceType deviceType, const std::string& deviceSerial, bool softfail = true);
void publishVirtualDevice(uint32_t virtualDeviceId, bool modal = true);
void setVirtualDeviceProperty(uint32_t virtualDeviceId, vr::ETrackedDeviceProperty deviceProperty, int32_t value, bool modal = true);
void setVirtualDeviceProperty(uint32_t virtualDeviceId, vr::ETrackedDeviceProperty deviceProperty, uint64_t value, bool modal = true);
void setVirtualDeviceProperty(uint32_t virtualDeviceId, vr::ETrackedDeviceProperty deviceProperty, float value, bool modal = true);
void setVirtualDeviceProperty(uint32_t virtualDeviceId, vr::ETrackedDeviceProperty deviceProperty, bool value, bool modal = true);
void setVirtualDeviceProperty(uint32_t virtualDeviceId, vr::ETrackedDeviceProperty deviceProperty, const std::string& value, bool modal = true);
void setVirtualDeviceProperty(uint32_t virtualDeviceId, vr::ETrackedDeviceProperty deviceProperty, const char* value, bool modal = true);
void setVirtualDeviceProperty(uint32_t virtualDeviceId, vr::ETrackedDeviceProperty deviceProperty, const vr::HmdMatrix34_t& value, bool modal = true);
void removeVirtualDeviceProperty(uint32_t virtualDeviceId, vr::ETrackedDeviceProperty deviceProperty, bool modal = true);
void setVirtualDevicePose(uint32_t virtualDeviceId, const vr::DriverPose_t& pose, bool modal = true);
void setVirtualControllerState(uint32_t virtualDeviceId, const vr::VRControllerState_t& state, bool modal = true);
void enableDeviceButtonMapping(uint32_t deviceId, bool enable, bool modal = true);
void addDeviceButtonMapping(uint32_t deviceId, vr::EVRButtonId button, vr::EVRButtonId mapped, bool modal = true);
void removeDeviceButtonMapping(uint32_t deviceId, vr::EVRButtonId button, bool modal = true);
void removeAllDeviceButtonMappings(uint32_t deviceId, bool modal = true);
void getDeviceOffsets(uint32_t deviceId, DeviceOffsets& data);
void enableDeviceOffsets(uint32_t deviceId, bool enable, bool modal = true);
void setWorldFromDriverRotationOffset(uint32_t deviceId, const vr::HmdQuaternion_t& value, bool modal = true);
void setWorldFromDriverTranslationOffset(uint32_t deviceId, const vr::HmdVector3d_t& value, bool modal = true);
void setDriverFromHeadRotationOffset(uint32_t deviceId, const vr::HmdQuaternion_t& value, bool modal = true);
void setDriverFromHeadTranslationOffset(uint32_t deviceId, const vr::HmdVector3d_t& value, bool modal = true);
void setDriverRotationOffset(uint32_t deviceId, const vr::HmdQuaternion_t& value, bool modal = true);
void setDriverTranslationOffset(uint32_t deviceId, const vr::HmdVector3d_t& value, bool modal = true);
void getDeviceInfo(uint32_t deviceId, DeviceInfo& info);
void setDeviceNormalMode(uint32_t deviceId, bool modal = true);
void setDeviceFakeDisconnectedMode(uint32_t deviceId, bool modal = true);
void setDeviceRedictMode(uint32_t deviceId, uint32_t target, bool modal = true);
void setDeviceSwapMode(uint32_t deviceId, uint32_t target, bool modal = true);
void setDeviceMotionCompensationMode(uint32_t deviceId, MotionCompensationVelAccMode velAccMode = MotionCompensationVelAccMode::Disabled, bool modal = true);
void setMotionVelAccCompensationMode(MotionCompensationVelAccMode velAccMode, bool modal = true);
void setMotionCompensationKalmanProcessNoise(double variance, bool modal = true);
void setMotionCompensationKalmanObservationNoise(double variance, bool modal = true);
void setMotionCompensationMovingAverageWindow(unsigned window, bool modal = true);
void triggerHapticPulse(uint32_t deviceId, uint32_t axisId, uint16_t durationMicroseconds, bool directMode, bool modal = true);
void setDigitalInputRemapping(uint32_t deviceId, uint32_t buttonId, const DigitalInputRemapping& remapping, bool modal = true);
DigitalInputRemapping getDigitalInputRemapping(uint32_t deviceId, uint32_t buttonId);
void setAnalogInputRemapping(uint32_t deviceId, uint32_t axisId, const AnalogInputRemapping& remapping, bool modal = true);
AnalogInputRemapping getAnalogInputRemapping(uint32_t deviceId, uint32_t axisId);
private:
std::recursive_mutex _mutex;
uint32_t m_clientId = 0;
bool _ipcThreadRunning = false;
volatile bool _ipcThreadStop = false;
std::thread _ipcThread;
static void _ipcThreadFunc(VRInputEmulator* _this);
std::random_device _ipcRandomDevice;
std::uniform_int_distribution<uint32_t> _ipcRandomDist;
struct _ipcPromiseMapEntry {
_ipcPromiseMapEntry() : isValid(false) {}
_ipcPromiseMapEntry(std::promise<ipc::Reply>&& _promise, bool isValid = true)
: promise(std::move(_promise)), isValid(isValid) {}
bool isValid;
std::promise<ipc::Reply> promise;
};
std::map<uint32_t, _ipcPromiseMapEntry> _ipcPromiseMap;
std::string _ipcServerQueueName;
std::string _ipcClientQueueName;
boost::interprocess::message_queue* _ipcServerQueue = nullptr;
boost::interprocess::message_queue* _ipcClientQueue = nullptr;
void _setVirtualDeviceProperty(uint32_t emulatorDeviceId, vr::ETrackedDeviceProperty deviceProperty, std::function<void(ipc::Request&)>, bool modal);
};
} // end namespace vrinputemulator
@@ -1,169 +0,0 @@
#pragma once
#include <stdint.h>
namespace vrinputemulator {
static const char* const vrsettings_SectionName = "driver_00vrinputemulator";
static const char* const vrsettings_overrideHmdManufacturer_string = "overrideHmdManufacturer";
static const char* const vrsettings_overrideHmdModel_string = "overrideHmdModel";
static const char* const vrsettings_overrideHmdTrackingSystem_string = "overrideHmdTrackingSystem";
static const char* const vrsettings_genericTrackerFakeController_bool = "genericTrackerFakeController";
enum class VirtualDeviceType : uint32_t {
None = 0,
TrackedController = 1
};
enum class ButtonEventType : uint32_t {
None = 0,
ButtonPressed = 1,
ButtonUnpressed = 2,
ButtonTouched = 3,
ButtonUntouched = 4,
};
enum class DevicePropertyValueType : uint32_t {
None = 0,
FLOAT = 1,
INT32 = 2,
UINT64 = 3,
BOOL = 4,
STRING = 5,
MATRIX34 = 20,
MATRIX44 = 21,
VECTOR3 = 22,
VECTOR4 = 23
};
struct DeviceOffsets {
uint32_t deviceId;
bool offsetsEnabled;
vr::HmdQuaternion_t worldFromDriverRotationOffset;
vr::HmdVector3d_t worldFromDriverTranslationOffset;
vr::HmdQuaternion_t driverFromHeadRotationOffset;
vr::HmdVector3d_t driverFromHeadTranslationOffset;
vr::HmdQuaternion_t deviceRotationOffset;
vr::HmdVector3d_t deviceTranslationOffset;
};
struct DeviceInfo {
uint32_t deviceId;
vr::ETrackedDeviceClass deviceClass;
int deviceMode;
uint32_t refDeviceId;
bool offsetsEnabled;
bool redirectSuspended;
};
enum class MotionCompensationVelAccMode : uint32_t {
Disabled = 0,
SetZero = 1,
SubstractMotionRef = 2,
LinearApproximation = 3,
KalmanFilter = 4
};
enum class DigitalBindingType : uint32_t {
NoRemapping = 0,
Disabled = 1,
OpenVR = 2,
Keyboard = 3,
SuspendRedirectMode = 4,
ToggleTouchpadEmulationFix = 5
};
struct DigitalBinding {
DigitalBindingType type = DigitalBindingType::NoRemapping;
union BindingUnion {
struct {
uint32_t controllerId;
uint32_t buttonId;
} openvr;
struct {
bool shiftPressed = false;
bool ctrlPressed = false;
bool altPressed = false;
uint32_t keyCode = 0x00;
bool sendScanCode = true;
} keyboard;
BindingUnion() {}
} data;
bool toggleEnabled = false;
uint32_t toggleDelay = 0;
bool autoTriggerEnabled = false;
uint32_t autoTriggerFrequency = 1;
DigitalBinding() {}
};
struct DigitalInputRemapping {
bool valid;
DigitalBinding binding;
bool touchAsClick = false;
bool longPressEnabled = false;
uint32_t longPressThreshold = 1000u;
DigitalBinding longPressBinding;
bool longPressImmediateRelease = false;
bool doublePressEnabled = false;
uint32_t doublePressThreshold = 300;
DigitalBinding doublePressBinding;
bool doublePressImmediateRelease = false;
DigitalInputRemapping(bool valid = false) : valid(valid) {}
};
enum class AnalogBindingType : uint32_t {
NoRemapping,
Disabled,
OpenVR
};
struct AnalogBinding {
AnalogBindingType type;
union BindingUnion {
struct {
uint32_t controllerId = vr::k_unTrackedDeviceIndexInvalid;
uint32_t axisId = 0;
} openvr;
BindingUnion() {}
} data;
bool invertXAxis = false;
bool invertYAxis = false;
bool swapAxes = false;
float lowerDeadzone = 0.0;
float upperDeadzone = 1.0;
unsigned touchpadEmulationMode = 0; // 0 .. Disabled, 1 .. Position Based, 2 .. Position Based (Deferred Zero Updates)
bool buttonPressDeadzoneFix = false;
AnalogBinding(AnalogBindingType type = AnalogBindingType::NoRemapping) : type(type) {}
};
struct AnalogInputRemapping {
bool valid;
AnalogBinding binding;
AnalogInputRemapping(bool valid = false) : valid(valid) {}
};
} // end namespace vrinputemulator
Submodule
+1
Submodule lib/minhook added at e33ec5abc0.
Binary file not shown.
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more