Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/ValveSoftware/openvr.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJeremy Selan <jeremys@valvesoftware.com>2016-11-16 20:37:20 +0300
committerJeremy Selan <jeremys@valvesoftware.com>2016-11-16 20:37:20 +0300
commit84e877f1e099173378759189609b90870f422130 (patch)
tree4d0bf61b6454a863ebe553292b9ea51115b8c458
parent5bc41e4b55d11dfc8fb4b958a6600aa7f8cee051 (diff)
OpenVR SDK 1.0.4:v1.0.4
General: * Further refinement to Vulkan support. Note: the interface is still subject to change. IVRSystem (v14): * ComputeDistortion signature change. Previous version used nan as error signaling. New version returns explicit success. * GetHiddenAreaMesh takes optional EHiddenAreaMeshType argument to request Standard, Inverse, or LineLoop mesh. IVRCompositor (v18): * New submit error, VRCompositorError_AlreadySubmitted (if you submit the same eye twice) * GetFrameTimings signature change * Exposed GetCurrentFadeColor, GetCurrentGridAlpha IVROverlay (v13): * Added SetOverlayIntersectionMask IServerDriverHost: * Added PollNextEvent IClientDriverHost: * Removed GetSettings * Added GetGenericInterface ClientTrackedDeviceProvider (v5): * GetHiddenAreaMesh takes additional argument, EHiddenAreaMeshType Pull Requests integrated: #48 Format README in Markdown #58 correct detection of GCC #68 helloworldoverlay: Specify c++11 to fix gcc errors #76 Remove duplicate, unneeded glBindBuffer call. #135 Invert m_mat4HMDPose after assignment copying. #191 Document additional methods #278 include stdbool.h on non windows platform #306 Multi-platform CMake support. [git-p4: depot-paths = "//vr/steamvr/sdk_release/": change = 3697868]
-rw-r--r--README.md (renamed from README)8
-rwxr-xr-xbin/linux64/libopenvr_api.sobin389560 -> 394088 bytes
-rwxr-xr-xbin/linux64/libopenvr_api.so.dbgbin3151279 -> 3165767 bytes
-rwxr-xr-xbin/osx32/libopenvr_api.dylibbin304956 -> 308788 bytes
-rw-r--r--bin/osx32/libopenvr_api.dylib.dSYM/Contents/Resources/DWARF/libopenvr_api.dylibbin2197457 -> 2184089 bytes
-rw-r--r--bin/win32/openvr_api.dllbin267040 -> 267040 bytes
-rw-r--r--bin/win32/openvr_api.pdbbin4542464 -> 4526080 bytes
-rw-r--r--bin/win64/openvr_api.dllbin314656 -> 314656 bytes
-rw-r--r--bin/win64/openvr_api.pdbbin4313088 -> 4304896 bytes
-rw-r--r--headers/openvr.h173
-rw-r--r--headers/openvr_api.cs135
-rw-r--r--headers/openvr_api.json96
-rw-r--r--headers/openvr_capi.h74
-rw-r--r--headers/openvr_driver.h77
-rwxr-xr-xlib/linux64/libopenvr_api.sobin3144159 -> 3158647 bytes
-rw-r--r--lib/win32/openvr_api.libbin5750 -> 5750 bytes
-rw-r--r--lib/win64/openvr_api.libbin5668 -> 5668 bytes
-rw-r--r--samples/CMakeLists.txt213
-rw-r--r--samples/README.md70
-rw-r--r--samples/bin/linux64/libopenvr_api.sobin389560 -> 394088 bytes
-rw-r--r--samples/bin/osx32/libopenvr_api.dylibbin304988 -> 308788 bytes
-rw-r--r--samples/bin/win32/openvr_api.dllbin267040 -> 267040 bytes
-rw-r--r--samples/bin/win64/openvr_api.dllbin314656 -> 314656 bytes
-rw-r--r--samples/driver_sample/CMakeLists.txt16
-rw-r--r--samples/driver_sample/driver_sample.cpp38
-rw-r--r--samples/hellovr_opengl/CMakeLists.txt16
-rw-r--r--samples/hellovr_opengl/hellovr_opengl_main.cpp306
-rw-r--r--samples/helloworldoverlay/CMakeLists.txt28
-rw-r--r--samples/helloworldoverlay/helloworldoverlay.pro1
-rw-r--r--samples/helloworldoverlay/openvroverlaycontroller.h1
-rw-r--r--samples/shared/compat.h27
-rw-r--r--samples/tracked_camera_openvr_sample/CMakeLists.txt26
-rw-r--r--samples/tracked_camera_openvr_sample/tracked_camera_openvr_sample.cpp2
-rw-r--r--src/CMakeLists.txt14
-rw-r--r--src/README35
-rw-r--r--src/ivrclientcore.h35
-rw-r--r--src/json/json-forwards.h284
-rw-r--r--src/json/json.h2077
-rw-r--r--src/jsoncpp.cpp5266
-rw-r--r--src/openvr_api_public.cpp278
-rw-r--r--src/vrcommon/dirtools.h17
-rw-r--r--src/vrcommon/dirtools_public.cpp100
-rw-r--r--src/vrcommon/envvartools.h7
-rw-r--r--src/vrcommon/envvartools_public.cpp46
-rw-r--r--src/vrcommon/hmderrors.h8
-rw-r--r--src/vrcommon/hmderrors_public.cpp204
-rw-r--r--src/vrcommon/pathtools.h129
-rw-r--r--src/vrcommon/pathtools_public.cpp817
-rw-r--r--src/vrcommon/sharedlibtools.h10
-rw-r--r--src/vrcommon/sharedlibtools_public.cpp41
-rw-r--r--src/vrcommon/strtools.h126
-rw-r--r--src/vrcommon/strtools_public.cpp437
-rw-r--r--src/vrcommon/vrpathregistry.h46
-rw-r--r--src/vrcommon/vrpathregistry_public.cpp406
-rw-r--r--unity_package/Assets/Plugins/openvr_api.cs135
-rw-r--r--unity_package/Assets/SteamVR/Extras/SteamVR_TrackedController.cs2
-rw-r--r--unity_package/Assets/SteamVR/Scripts/SteamVR_CameraMask.cs4
-rw-r--r--unity_package/Assets/SteamVR/Scripts/SteamVR_Controller.cs2
58 files changed, 11468 insertions, 365 deletions
diff --git a/README b/README.md
index 9a89231..5976d62 100644
--- a/README
+++ b/README.md
@@ -1,9 +1,13 @@
+OpenVR SDK
+---
+
OpenVR is an API and runtime that allows access to VR hardware from multiple
vendors without requiring that applications have specific knowledge of the
hardware they are targeting. This repository is an SDK that contains the API
and samples. The runtime is under SteamVR in Tools on Steam.
-Documentation for the API is available in the wiki: https://github.com/ValveSoftware/openvr/wiki/API-Documentation
+### Documentation
-More information on OpenVR and SteamVR can be found on http://steamvr.com
+Documentation for the API is available on the [Github Wiki](https://github.com/ValveSoftware/openvr/wiki/API-Documentation)
+More information on OpenVR and SteamVR can be found on http://steamvr.com
diff --git a/bin/linux64/libopenvr_api.so b/bin/linux64/libopenvr_api.so
index 692a87c..a7d57c6 100755
--- a/bin/linux64/libopenvr_api.so
+++ b/bin/linux64/libopenvr_api.so
Binary files differ
diff --git a/bin/linux64/libopenvr_api.so.dbg b/bin/linux64/libopenvr_api.so.dbg
index 6285a38..cc7976f 100755
--- a/bin/linux64/libopenvr_api.so.dbg
+++ b/bin/linux64/libopenvr_api.so.dbg
Binary files differ
diff --git a/bin/osx32/libopenvr_api.dylib b/bin/osx32/libopenvr_api.dylib
index e3e871a..2ac282b 100755
--- a/bin/osx32/libopenvr_api.dylib
+++ b/bin/osx32/libopenvr_api.dylib
Binary files differ
diff --git a/bin/osx32/libopenvr_api.dylib.dSYM/Contents/Resources/DWARF/libopenvr_api.dylib b/bin/osx32/libopenvr_api.dylib.dSYM/Contents/Resources/DWARF/libopenvr_api.dylib
index 9b6372f..f10a99a 100644
--- a/bin/osx32/libopenvr_api.dylib.dSYM/Contents/Resources/DWARF/libopenvr_api.dylib
+++ b/bin/osx32/libopenvr_api.dylib.dSYM/Contents/Resources/DWARF/libopenvr_api.dylib
Binary files differ
diff --git a/bin/win32/openvr_api.dll b/bin/win32/openvr_api.dll
index 2dd3fbe..0b0cc0e 100644
--- a/bin/win32/openvr_api.dll
+++ b/bin/win32/openvr_api.dll
Binary files differ
diff --git a/bin/win32/openvr_api.pdb b/bin/win32/openvr_api.pdb
index 5a43d1b..f477abc 100644
--- a/bin/win32/openvr_api.pdb
+++ b/bin/win32/openvr_api.pdb
Binary files differ
diff --git a/bin/win64/openvr_api.dll b/bin/win64/openvr_api.dll
index 9ae4922..8b33ebb 100644
--- a/bin/win64/openvr_api.dll
+++ b/bin/win64/openvr_api.dll
Binary files differ
diff --git a/bin/win64/openvr_api.pdb b/bin/win64/openvr_api.pdb
index e575e13..bde2843 100644
--- a/bin/win64/openvr_api.pdb
+++ b/bin/win64/openvr_api.pdb
Binary files differ
diff --git a/headers/openvr.h b/headers/openvr.h
index b72fcae..d9d7dee 100644
--- a/headers/openvr.h
+++ b/headers/openvr.h
@@ -146,7 +146,6 @@ enum ETrackingResult
TrackingResult_Running_OutOfRange = 201,
};
-static const uint32_t k_unTrackingStringSize = 32;
static const uint32_t k_unMaxDriverDebugResponseSize = 32768;
/** Used to pass device IDs to API calls */
@@ -241,6 +240,7 @@ enum ETrackedDeviceProperty
Prop_HasCamera_Bool = 1030,
Prop_DriverVersion_String = 1031,
Prop_Firmware_ForceUpdateRequired_Bool = 1032,
+ Prop_ViveSystemButtonFixRequired_Bool = 1033,
// Properties that are unique to TrackedDeviceClass_HMD
Prop_ReportsTimeSinceVSync_Bool = 2000,
@@ -280,6 +280,7 @@ enum ETrackedDeviceProperty
Prop_ScreenshotHorizontalFieldOfViewDegrees_Float = 2034,
Prop_ScreenshotVerticalFieldOfViewDegrees_Float = 2035,
Prop_DisplaySuppressed_Bool = 2036,
+ Prop_DisplayAllowNightMode_Bool = 2037,
// Properties that are unique to TrackedDeviceClass_Controller
Prop_AttachedDeviceId_String = 3000,
@@ -702,7 +703,7 @@ struct VREvent_EditingCameraSurface_t
uint32_t nVisualMode;
};
-/** If you change this you must manually update openvr_interop.cs.py */
+/** NOTE!!! If you change this you MUST manually update openvr_interop.cs.py */
typedef union
{
VREvent_Reserved_t reserved;
@@ -749,6 +750,14 @@ struct HiddenAreaMesh_t
};
+enum EHiddenAreaMeshType
+{
+ k_eHiddenAreaMesh_Standard = 0,
+ k_eHiddenAreaMesh_Inverse = 1,
+ k_eHiddenAreaMesh_LineLoop = 2,
+};
+
+
/** Identifies what kind of axis is on the controller at index n. Read this type
* with pVRSystem->Get( nControllerDeviceIndex, Prop_Axis0Type_Int32 + n );
*/
@@ -832,26 +841,28 @@ static const VROverlayHandle_t k_ulOverlayHandleInvalid = 0;
/** Errors that can occur around VR overlays */
enum EVROverlayError
{
- VROverlayError_None = 0,
-
- VROverlayError_UnknownOverlay = 10,
- VROverlayError_InvalidHandle = 11,
- VROverlayError_PermissionDenied = 12,
- VROverlayError_OverlayLimitExceeded = 13, // No more overlays could be created because the maximum number already exist
- VROverlayError_WrongVisibilityType = 14,
- VROverlayError_KeyTooLong = 15,
- VROverlayError_NameTooLong = 16,
- VROverlayError_KeyInUse = 17,
- VROverlayError_WrongTransformType = 18,
- VROverlayError_InvalidTrackedDevice = 19,
- VROverlayError_InvalidParameter = 20,
- VROverlayError_ThumbnailCantBeDestroyed = 21,
- VROverlayError_ArrayTooSmall = 22,
- VROverlayError_RequestFailed = 23,
- VROverlayError_InvalidTexture = 24,
- VROverlayError_UnableToLoadFile = 25,
- VROverlayError_KeyboardAlreadyInUse = 26,
- VROverlayError_NoNeighbor = 27,
+ VROverlayError_None = 0,
+
+ VROverlayError_UnknownOverlay = 10,
+ VROverlayError_InvalidHandle = 11,
+ VROverlayError_PermissionDenied = 12,
+ VROverlayError_OverlayLimitExceeded = 13, // No more overlays could be created because the maximum number already exist
+ VROverlayError_WrongVisibilityType = 14,
+ VROverlayError_KeyTooLong = 15,
+ VROverlayError_NameTooLong = 16,
+ VROverlayError_KeyInUse = 17,
+ VROverlayError_WrongTransformType = 18,
+ VROverlayError_InvalidTrackedDevice = 19,
+ VROverlayError_InvalidParameter = 20,
+ VROverlayError_ThumbnailCantBeDestroyed = 21,
+ VROverlayError_ArrayTooSmall = 22,
+ VROverlayError_RequestFailed = 23,
+ VROverlayError_InvalidTexture = 24,
+ VROverlayError_UnableToLoadFile = 25,
+ VROverlayError_KeyboardAlreadyInUse = 26,
+ VROverlayError_NoNeighbor = 27,
+ VROverlayError_TooManyMaskPrimitives = 29,
+ VROverlayError_BadMaskPrimitive = 30,
};
/** enum values to pass in to VR_Init to identify whether the application will
@@ -1126,10 +1137,10 @@ public:
* application is doing something fancy like infinite Z */
virtual void GetProjectionRaw( EVREye eEye, float *pfLeft, float *pfRight, float *pfTop, float *pfBottom ) = 0;
- /** Returns the result of the distortion function for the specified eye and input UVs. UVs go from 0,0 in
+ /** Gets the result of the distortion function for the specified eye and input UVs. UVs go from 0,0 in
* the upper left of that eye's viewport and 1,1 in the lower right of that eye's viewport.
- * Values may be NAN to indicate an error has occurred. */
- virtual DistortionCoordinates_t ComputeDistortion( EVREye eEye, float fU, float fV ) = 0;
+ * Returns true for success. Otherwise, returns false, and distortion coordinates are not suitable. */
+ virtual bool ComputeDistortion( EVREye eEye, float fU, float fV, DistortionCoordinates_t *pDistortionCoordinates ) = 0;
/** Returns the transform from eye space to the head space. Eye space is the per-eye flavor of head
* space that provides stereo disparity. Instead of Model * View * Projection the sequence is Model * View * Eye^-1 * Projection.
@@ -1265,7 +1276,7 @@ public:
/** Returns a string property. If the device index is not valid or the property is not a string type this function will
* return 0. Otherwise it returns the length of the number of bytes necessary to hold this string including the trailing
- * null. Strings will generally fit in buffers of k_unTrackingStringSize characters. */
+ * null. Strings will always fit in buffers of k_unMaxPropertyStringSize characters. */
virtual uint32_t GetStringTrackedDeviceProperty( vr::TrackedDeviceIndex_t unDeviceIndex, ETrackedDeviceProperty prop, VR_OUT_STRING() char *pchValue, uint32_t unBufferSize, ETrackedPropertyError *pError = 0L ) = 0;
/** returns a string that corresponds with the specified property error. The string will be the name
@@ -1293,14 +1304,15 @@ public:
// Rendering helper methods
// ------------------------------------
- /** Returns the stencil mesh information for the current HMD. If this HMD does not have a stencil mesh the vertex data and count will be
- * NULL and 0 respectively. This mesh is meant to be rendered into the stencil buffer (or into the depth buffer setting nearz) before rendering
- * each eye's view. The pixels covered by this mesh will never be seen by the user after the lens distortion is applied and based on visibility to the panels.
- * This will improve perf by letting the GPU early-reject pixels the user will never see before running the pixel shader.
+ /** Returns the hidden area mesh for the current HMD. The pixels covered by this mesh will never be seen by the user after the lens distortion is
+ * applied based on visibility to the panels. If this HMD does not have a hidden area mesh, the vertex data and count will be NULL and 0 respectively.
+ * This mesh is meant to be rendered into the stencil buffer (or into the depth buffer setting nearz) before rendering each eye's view.
+ * This will improve performance by letting the GPU early-reject pixels the user will never see before running the pixel shader.
* NOTE: Render this mesh with backface culling disabled since the winding order of the vertices can be different per-HMD or per-eye.
+ * Setting the bInverse argument to true will produce the visible area mesh that is commonly used in place of full-screen quads. The visible area mesh covers all of the pixels the hidden area mesh does not cover.
+ * Setting the bLineLoop argument will return a line loop of vertices in HiddenAreaMesh_t->pVertexData with HiddenAreaMesh_t->unTriangleCount set to the number of vertices.
*/
- virtual HiddenAreaMesh_t GetHiddenAreaMesh( EVREye eEye ) = 0;
-
+ virtual HiddenAreaMesh_t GetHiddenAreaMesh( EVREye eEye, EHiddenAreaMeshType type = k_eHiddenAreaMesh_Standard ) = 0;
// ------------------------------------
// Controller methods
@@ -1308,12 +1320,12 @@ public:
/** Fills the supplied struct with the current state of the controller. Returns false if the controller index
* is invalid. */
- virtual bool GetControllerState( vr::TrackedDeviceIndex_t unControllerDeviceIndex, vr::VRControllerState_t *pControllerState ) = 0;
+ virtual bool GetControllerState( vr::TrackedDeviceIndex_t unControllerDeviceIndex, vr::VRControllerState_t *pControllerState, uint32_t unControllerStateSize ) = 0;
/** fills the supplied struct with the current state of the controller and the provided pose with the pose of
* the controller when the controller state was updated most recently. Use this form if you need a precise controller
* pose as input to your application when the user presses or releases a button. */
- virtual bool GetControllerStateWithPose( ETrackingUniverseOrigin eOrigin, vr::TrackedDeviceIndex_t unControllerDeviceIndex, vr::VRControllerState_t *pControllerState, TrackedDevicePose_t *pTrackedDevicePose ) = 0;
+ virtual bool GetControllerStateWithPose( ETrackingUniverseOrigin eOrigin, vr::TrackedDeviceIndex_t unControllerDeviceIndex, vr::VRControllerState_t *pControllerState, uint32_t unControllerStateSize, TrackedDevicePose_t *pTrackedDevicePose ) = 0;
/** Trigger a single haptic pulse on a controller. After this call the application may not trigger another haptic pulse on this controller
* and axis combination for 5ms. */
@@ -1346,7 +1358,6 @@ public:
* The size of the response including its terminating null is returned. */
virtual uint32_t DriverDebugRequest( vr::TrackedDeviceIndex_t unDeviceIndex, const char *pchRequest, char *pchResponseBuffer, uint32_t unResponseBufferSize ) = 0;
-
// ------------------------------------
// Firmware methods
// ------------------------------------
@@ -1358,7 +1369,6 @@ public:
* Prop_Firmware_ManualUpdateURL_String should point to an URL describing the manual update process */
virtual vr::EVRFirmwareError PerformFirmwareUpdate( vr::TrackedDeviceIndex_t unDeviceIndex ) = 0;
-
// ------------------------------------
// Application life cycle methods
// ------------------------------------
@@ -1374,7 +1384,7 @@ public:
};
-static const char * const IVRSystem_Version = "IVRSystem_012";
+static const char * const IVRSystem_Version = "IVRSystem_014";
}
@@ -1644,9 +1654,9 @@ namespace vr
static const char * const k_pch_SteamVR_LogLevel_Int32 = "loglevel";
static const char * const k_pch_SteamVR_IPD_Float = "ipd";
static const char * const k_pch_SteamVR_Background_String = "background";
+ static const char * const k_pch_SteamVR_BackgroundUseDomeProjection_Bool = "backgroundUseDomeProjection";
static const char * const k_pch_SteamVR_BackgroundCameraHeight_Float = "backgroundCameraHeight";
static const char * const k_pch_SteamVR_BackgroundDomeRadius_Float = "backgroundDomeRadius";
- static const char * const k_pch_SteamVR_Environment_String = "environment";
static const char * const k_pch_SteamVR_GridColor_String = "gridColor";
static const char * const k_pch_SteamVR_PlayAreaColor_String = "playAreaColor";
static const char * const k_pch_SteamVR_ShowStage_Bool = "showStage";
@@ -1659,7 +1669,8 @@ namespace vr
static const char * const k_pch_SteamVR_BaseStationPowerManagement_Bool = "basestationPowerManagement";
static const char * const k_pch_SteamVR_NeverKillProcesses_Bool = "neverKillProcesses";
static const char * const k_pch_SteamVR_RenderTargetMultiplier_Float = "renderTargetMultiplier";
- static const char * const k_pch_SteamVR_AllowReprojection_Bool = "allowReprojection";
+ static const char * const k_pch_SteamVR_AllowAsyncReprojection_Bool = "allowAsyncReprojection";
+ static const char * const k_pch_SteamVR_AllowReprojection_Bool = "allowInterleavedReprojection";
static const char * const k_pch_SteamVR_ForceReprojection_Bool = "forceReprojection";
static const char * const k_pch_SteamVR_ForceFadeOnBadTracking_Bool = "forceFadeOnBadTracking";
static const char * const k_pch_SteamVR_DefaultMirrorView_Int32 = "defaultMirrorView";
@@ -1670,6 +1681,7 @@ namespace vr
static const char * const k_pch_SteamVR_SetInitialDefaultHomeApp = "setInitialDefaultHomeApp";
static const char * const k_pch_SteamVR_CycleBackgroundImageTimeSec_Int32 = "CycleBackgroundImageTimeSec";
static const char * const k_pch_SteamVR_RetailDemo_Bool = "retailDemo";
+ static const char * const k_pch_SteamVR_IpdOffset_Float = "ipdOffset";
//-----------------------------------------------------------------------------
@@ -1703,6 +1715,7 @@ namespace vr
// user interface keys
static const char * const k_pch_UserInterface_Section = "userinterface";
static const char * const k_pch_UserInterface_StatusAlwaysOnTop_Bool = "StatusAlwaysOnTop";
+ static const char * const k_pch_UserInterface_MinimizeToTray_Bool = "MinimizeToTray";
static const char * const k_pch_UserInterface_Screenshots_Bool = "screenshots";
static const char * const k_pch_UserInterface_ScreenshotType_Int = "screenshotType";
@@ -1987,10 +2000,17 @@ enum EVRCompositorError
VRCompositorError_TextureUsesUnsupportedFormat = 105,
VRCompositorError_SharedTexturesNotSupported = 106,
VRCompositorError_IndexOutOfRange = 107,
+ VRCompositorError_AlreadySubmitted = 108,
};
const uint32_t VRCompositor_ReprojectionReason_Cpu = 0x01;
const uint32_t VRCompositor_ReprojectionReason_Gpu = 0x02;
+const uint32_t VRCompositor_ReprojectionAsync = 0x04; // This flag indicates the async reprojection mode is active,
+ // but does not indicate if reprojection actually happened or not.
+ // Use the ReprojectionReason flags above to check if reprojection
+ // was actually applied (i.e. scene texture was reused).
+ // NumFramePresents > 1 also indicates the scene texture was reused,
+ // and also the number of times that it was presented in total.
/** Provides a single frame's timing information to the app */
struct Compositor_FrameTiming
@@ -1998,6 +2018,7 @@ struct Compositor_FrameTiming
uint32_t m_nSize; // Set to sizeof( Compositor_FrameTiming )
uint32_t m_nFrameIndex;
uint32_t m_nNumFramePresents; // number of times this frame was presented
+ uint32_t m_nNumMisPresented; // number of times this frame was presented on a vsync other than it was originally predicted to
uint32_t m_nNumDroppedFrames; // number of additional times previous frame was scanned out
uint32_t m_nReprojectionFlags;
@@ -2074,7 +2095,14 @@ public:
/** Gets current tracking space returned by WaitGetPoses */
virtual ETrackingUniverseOrigin GetTrackingSpace() = 0;
- /** Returns pose(s) to use to render scene (and optionally poses predicted two frames out for gameplay). */
+ /** Scene applications should call this function to get poses to render with (and optionally poses predicted an additional frame out to use for gameplay).
+ * This function will block until "running start" milliseconds before the start of the frame, and should be called at the last moment before needing to
+ * start rendering.
+ *
+ * Return codes:
+ * - IsNotSceneApplication (make sure to call VR_Init with VRApplicaiton_Scene)
+ * - DoNotHaveFocus (some other app has taken focus - this will throttle the call to 10hz to reduce the impact on that app)
+ */
virtual EVRCompositorError WaitGetPoses( VR_ARRAY_COUNT(unRenderPoseArrayCount) TrackedDevicePose_t* pRenderPoseArray, uint32_t unRenderPoseArrayCount,
VR_ARRAY_COUNT(unGamePoseArrayCount) TrackedDevicePose_t* pGamePoseArray, uint32_t unGamePoseArrayCount ) = 0;
@@ -2092,6 +2120,15 @@ public:
*
* OpenGL dirty state:
* glBindTexture
+ *
+ * Return codes:
+ * - IsNotSceneApplication (make sure to call VR_Init with VRApplicaiton_Scene)
+ * - DoNotHaveFocus (some other app has taken focus)
+ * - TextureIsOnWrongDevice (application did not use proper AdapterIndex - see IVRSystem.GetDXGIOutputInfo)
+ * - SharedTexturesNotSupported (application needs to call CreateDXGIFactory1 or later before creating DX device)
+ * - TextureUsesUnsupportedFormat (scene textures must be compatible with DXGI sharing rules - e.g. uncompressed, no mips, etc.)
+ * - InvalidTexture (usually means bad arguments passed in)
+ * - AlreadySubmitted (app has submitted two left textures or two right textures in a single frame - i.e. before calling WaitGetPoses again)
*/
virtual EVRCompositorError Submit( EVREye eEye, const Texture_t *pTexture, const VRTextureBounds_t* pBounds = 0, EVRSubmitFlags nSubmitFlags = Submit_Default ) = 0;
@@ -2110,6 +2147,10 @@ public:
* Be sure to set timing.size = sizeof(Compositor_FrameTiming) on struct passed in before calling this function. */
virtual bool GetFrameTiming( Compositor_FrameTiming *pTiming, uint32_t unFramesAgo = 0 ) = 0;
+ /** Interface for copying a range of timing data. Frames are returned in ascending order (oldest to newest) with the last being the most recent frame.
+ * Only the first entry's m_nSize needs to be set, as the rest will be inferred from that. Returns total number of entries filled out. */
+ virtual uint32_t GetFrameTimings( Compositor_FrameTiming *pTiming, uint32_t nFrames ) = 0;
+
/** Returns the time in seconds left in the current (as identified by FrameTiming's frameIndex) frame.
* Due to "running start", this value may roll over to the next frame before ever reaching 0.0. */
virtual float GetFrameTimeRemaining() = 0;
@@ -2122,9 +2163,15 @@ public:
* would be FadeToColor( 0.0, 0.0, 0.0, 0.0, 0.0 ). Values are in un-premultiplied alpha space. */
virtual void FadeToColor( float fSeconds, float fRed, float fGreen, float fBlue, float fAlpha, bool bBackground = false ) = 0;
+ /** Get current fade color value. */
+ virtual HmdColor_t GetCurrentFadeColor( bool bBackground = false ) = 0;
+
/** Fading the Grid in or out in fSeconds */
virtual void FadeGrid( float fSeconds, bool bFadeIn ) = 0;
+ /** Get current alpha value of grid. */
+ virtual float GetCurrentGridAlpha() = 0;
+
/** Override the skybox used in the compositor (e.g. for during level loads when the app can't feed scene images fast enough)
* Order is Front, Back, Left, Right, Top, Bottom. If only a single texture is passed, it is assumed in lat-long format.
* If two are passed, it is assumed a lat-long stereo pair. */
@@ -2191,7 +2238,7 @@ public:
virtual void UnlockGLSharedTextureForAccess( vr::glSharedTextureHandle_t glSharedTextureHandle ) = 0;
};
-static const char * const IVRCompositor_Version = "IVRCompositor_016";
+static const char * const IVRCompositor_Version = "IVRCompositor_018";
} // namespace vr
@@ -2308,6 +2355,9 @@ namespace vr
/** The maximum number of overlays that can exist in the system at one time. */
static const uint32_t k_unMaxOverlayCount = 64;
+ /** The maximum number of overlay intersection mask primitives per overlay */
+ static const uint32_t k_unMaxOverlayIntersectionMaskPrimitivesCount = 32;
+
/** Types of input supported by VR Overlays */
enum VROverlayInputMethod
{
@@ -2407,6 +2457,40 @@ namespace vr
OverlayDirection_Count = 4,
};
+ enum EVROverlayIntersectionMaskPrimitiveType
+ {
+ OverlayIntersectionPrimitiveType_Rectangle,
+ OverlayIntersectionPrimitiveType_Circle,
+ };
+
+ struct IntersectionMaskRectangle_t
+ {
+ float m_flTopLeftX;
+ float m_flTopLeftY;
+ float m_flWidth;
+ float m_flHeight;
+ };
+
+ struct IntersectionMaskCircle_t
+ {
+ float m_flCenterX;
+ float m_flCenterY;
+ float m_flRadius;
+ };
+
+ /** NOTE!!! If you change this you MUST manually update openvr_interop.cs.py and openvr_api_flat.h.py */
+ typedef union
+ {
+ IntersectionMaskRectangle_t m_Rectangle;
+ IntersectionMaskCircle_t m_Circle;
+ } VROverlayIntersectionMaskPrimitive_Data_t;
+
+ struct VROverlayIntersectionMaskPrimitive_t
+ {
+ EVROverlayIntersectionMaskPrimitiveType m_nPrimitiveType;
+ VROverlayIntersectionMaskPrimitive_Data_t m_Primitive;
+ };
+
class IVROverlay
{
public:
@@ -2703,6 +2787,13 @@ namespace vr
/** Set the position of the keyboard in overlay space by telling it to avoid a rectangle in the overlay. Rectangle coords have (0,0) in the bottom left **/
virtual void SetKeyboardPositionForOverlay( VROverlayHandle_t ulOverlayHandle, HmdRect2_t avoidRect ) = 0;
+ // ---------------------------------------------
+ // Overlay input methods
+ // ---------------------------------------------
+
+ /** Sets a list of primitives to be used for controller ray intersection
+ * typically the size of the underlying UI in pixels (not in world space). */
+ virtual EVROverlayError SetOverlayIntersectionMask( VROverlayHandle_t ulOverlayHandle, VROverlayIntersectionMaskPrimitive_t *pMaskPrimitives, uint32_t unNumMaskPrimitives, uint32_t unPrimitiveSize = sizeof( VROverlayIntersectionMaskPrimitive_t ) ) = 0;
};
static const char * const IVROverlay_Version = "IVROverlay_013";
diff --git a/headers/openvr_api.cs b/headers/openvr_api.cs
index 8fcac88..517e2af 100644
--- a/headers/openvr_api.cs
+++ b/headers/openvr_api.cs
@@ -31,7 +31,7 @@ public struct IVRSystem
internal _GetProjectionRaw GetProjectionRaw;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
- internal delegate DistortionCoordinates_t _ComputeDistortion(EVREye eEye, float fU, float fV);
+ internal delegate bool _ComputeDistortion(EVREye eEye, float fU, float fV, ref DistortionCoordinates_t pDistortionCoordinates);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _ComputeDistortion ComputeDistortion;
@@ -171,17 +171,17 @@ public struct IVRSystem
internal _GetEventTypeNameFromEnum GetEventTypeNameFromEnum;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
- internal delegate HiddenAreaMesh_t _GetHiddenAreaMesh(EVREye eEye);
+ internal delegate HiddenAreaMesh_t _GetHiddenAreaMesh(EVREye eEye, EHiddenAreaMeshType type);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _GetHiddenAreaMesh GetHiddenAreaMesh;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
- internal delegate bool _GetControllerState(uint unControllerDeviceIndex, ref VRControllerState_t pControllerState);
+ internal delegate bool _GetControllerState(uint unControllerDeviceIndex, ref VRControllerState_t pControllerState, uint unControllerStateSize);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _GetControllerState GetControllerState;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
- internal delegate bool _GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin, uint unControllerDeviceIndex, ref VRControllerState_t pControllerState, ref TrackedDevicePose_t pTrackedDevicePose);
+ internal delegate bool _GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin, uint unControllerDeviceIndex, ref VRControllerState_t pControllerState, uint unControllerStateSize, ref TrackedDevicePose_t pTrackedDevicePose);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _GetControllerStateWithPose GetControllerStateWithPose;
@@ -676,6 +676,11 @@ public struct IVRCompositor
internal _GetFrameTiming GetFrameTiming;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ internal delegate uint _GetFrameTimings(ref Compositor_FrameTiming pTiming, uint nFrames);
+ [MarshalAs(UnmanagedType.FunctionPtr)]
+ internal _GetFrameTimings GetFrameTimings;
+
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate float _GetFrameTimeRemaining();
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _GetFrameTimeRemaining GetFrameTimeRemaining;
@@ -691,11 +696,21 @@ public struct IVRCompositor
internal _FadeToColor FadeToColor;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ internal delegate HmdColor_t _GetCurrentFadeColor(bool bBackground);
+ [MarshalAs(UnmanagedType.FunctionPtr)]
+ internal _GetCurrentFadeColor GetCurrentFadeColor;
+
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void _FadeGrid(float fSeconds, bool bFadeIn);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _FadeGrid FadeGrid;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ internal delegate float _GetCurrentGridAlpha();
+ [MarshalAs(UnmanagedType.FunctionPtr)]
+ internal _GetCurrentGridAlpha GetCurrentGridAlpha;
+
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate EVRCompositorError _SetSkyboxOverride([In, Out] Texture_t[] pTextures, uint unTextureCount);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _SetSkyboxOverride SetSkyboxOverride;
@@ -1170,6 +1185,11 @@ public struct IVROverlay
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _SetKeyboardPositionForOverlay SetKeyboardPositionForOverlay;
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ internal delegate EVROverlayError _SetOverlayIntersectionMask(ulong ulOverlayHandle, ref VROverlayIntersectionMaskPrimitive_t pMaskPrimitives, uint unNumMaskPrimitives, uint unPrimitiveSize);
+ [MarshalAs(UnmanagedType.FunctionPtr)]
+ internal _SetOverlayIntersectionMask SetOverlayIntersectionMask;
+
}
[StructLayout(LayoutKind.Sequential)]
@@ -1429,9 +1449,9 @@ public class CVRSystem
pfBottom = 0;
FnTable.GetProjectionRaw(eEye,ref pfLeft,ref pfRight,ref pfTop,ref pfBottom);
}
- public DistortionCoordinates_t ComputeDistortion(EVREye eEye,float fU,float fV)
+ public bool ComputeDistortion(EVREye eEye,float fU,float fV,ref DistortionCoordinates_t pDistortionCoordinates)
{
- DistortionCoordinates_t result = FnTable.ComputeDistortion(eEye,fU,fV);
+ bool result = FnTable.ComputeDistortion(eEye,fU,fV,ref pDistortionCoordinates);
return result;
}
public HmdMatrix34_t GetEyeToHeadTransform(EVREye eEye)
@@ -1568,19 +1588,19 @@ public class CVRSystem
IntPtr result = FnTable.GetEventTypeNameFromEnum(eType);
return Marshal.PtrToStringAnsi(result);
}
- public HiddenAreaMesh_t GetHiddenAreaMesh(EVREye eEye)
+ public HiddenAreaMesh_t GetHiddenAreaMesh(EVREye eEye,EHiddenAreaMeshType type)
{
- HiddenAreaMesh_t result = FnTable.GetHiddenAreaMesh(eEye);
+ HiddenAreaMesh_t result = FnTable.GetHiddenAreaMesh(eEye,type);
return result;
}
- public bool GetControllerState(uint unControllerDeviceIndex,ref VRControllerState_t pControllerState)
+ public bool GetControllerState(uint unControllerDeviceIndex,ref VRControllerState_t pControllerState,uint unControllerStateSize)
{
- bool result = FnTable.GetControllerState(unControllerDeviceIndex,ref pControllerState);
+ bool result = FnTable.GetControllerState(unControllerDeviceIndex,ref pControllerState,unControllerStateSize);
return result;
}
- public bool GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin,uint unControllerDeviceIndex,ref VRControllerState_t pControllerState,ref TrackedDevicePose_t pTrackedDevicePose)
+ public bool GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin,uint unControllerDeviceIndex,ref VRControllerState_t pControllerState,uint unControllerStateSize,ref TrackedDevicePose_t pTrackedDevicePose)
{
- bool result = FnTable.GetControllerStateWithPose(eOrigin,unControllerDeviceIndex,ref pControllerState,ref pTrackedDevicePose);
+ bool result = FnTable.GetControllerStateWithPose(eOrigin,unControllerDeviceIndex,ref pControllerState,unControllerStateSize,ref pTrackedDevicePose);
return result;
}
public void TriggerHapticPulse(uint unControllerDeviceIndex,uint unAxisId,char usDurationMicroSec)
@@ -2117,6 +2137,11 @@ public class CVRCompositor
bool result = FnTable.GetFrameTiming(ref pTiming,unFramesAgo);
return result;
}
+ public uint GetFrameTimings(ref Compositor_FrameTiming pTiming,uint nFrames)
+ {
+ uint result = FnTable.GetFrameTimings(ref pTiming,nFrames);
+ return result;
+ }
public float GetFrameTimeRemaining()
{
float result = FnTable.GetFrameTimeRemaining();
@@ -2130,10 +2155,20 @@ public class CVRCompositor
{
FnTable.FadeToColor(fSeconds,fRed,fGreen,fBlue,fAlpha,bBackground);
}
+ public HmdColor_t GetCurrentFadeColor(bool bBackground)
+ {
+ HmdColor_t result = FnTable.GetCurrentFadeColor(bBackground);
+ return result;
+ }
public void FadeGrid(float fSeconds,bool bFadeIn)
{
FnTable.FadeGrid(fSeconds,bFadeIn);
}
+ public float GetCurrentGridAlpha()
+ {
+ float result = FnTable.GetCurrentGridAlpha();
+ return result;
+ }
public EVRCompositorError SetSkyboxOverride(Texture_t [] pTextures)
{
EVRCompositorError result = FnTable.SetSkyboxOverride(pTextures,(uint) pTextures.Length);
@@ -2623,6 +2658,11 @@ public class CVROverlay
{
FnTable.SetKeyboardPositionForOverlay(ulOverlayHandle,avoidRect);
}
+ public EVROverlayError SetOverlayIntersectionMask(ulong ulOverlayHandle,ref VROverlayIntersectionMaskPrimitive_t pMaskPrimitives,uint unNumMaskPrimitives,uint unPrimitiveSize)
+ {
+ EVROverlayError result = FnTable.SetOverlayIntersectionMask(ulOverlayHandle,ref pMaskPrimitives,unNumMaskPrimitives,unPrimitiveSize);
+ return result;
+ }
}
@@ -2876,21 +2916,21 @@ public class CVRResources
public class OpenVRInterop
{
- [DllImportAttribute("openvr_api", EntryPoint = "VR_InitInternal")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_InitInternal", CallingConvention = CallingConvention.Cdecl)]
internal static extern uint InitInternal(ref EVRInitError peError, EVRApplicationType eApplicationType);
- [DllImportAttribute("openvr_api", EntryPoint = "VR_ShutdownInternal")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_ShutdownInternal", CallingConvention = CallingConvention.Cdecl)]
internal static extern void ShutdownInternal();
- [DllImportAttribute("openvr_api", EntryPoint = "VR_IsHmdPresent")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_IsHmdPresent", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool IsHmdPresent();
- [DllImportAttribute("openvr_api", EntryPoint = "VR_IsRuntimeInstalled")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_IsRuntimeInstalled", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool IsRuntimeInstalled();
- [DllImportAttribute("openvr_api", EntryPoint = "VR_GetStringForHmdError")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_GetStringForHmdError", CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr GetStringForHmdError(EVRInitError error);
- [DllImportAttribute("openvr_api", EntryPoint = "VR_GetGenericInterface")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_GetGenericInterface", CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr GetGenericInterface([In, MarshalAs(UnmanagedType.LPStr)] string pchInterfaceVersion, ref EVRInitError peError);
- [DllImportAttribute("openvr_api", EntryPoint = "VR_IsInterfaceVersionValid")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_IsInterfaceVersionValid", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool IsInterfaceVersionValid([In, MarshalAs(UnmanagedType.LPStr)] string pchInterfaceVersion);
- [DllImportAttribute("openvr_api", EntryPoint = "VR_GetInitToken")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_GetInitToken", CallingConvention = CallingConvention.Cdecl)]
internal static extern uint GetInitToken();
}
@@ -2975,6 +3015,7 @@ public enum ETrackedDeviceProperty
Prop_HasCamera_Bool = 1030,
Prop_DriverVersion_String = 1031,
Prop_Firmware_ForceUpdateRequired_Bool = 1032,
+ Prop_ViveSystemButtonFixRequired_Bool = 1033,
Prop_ReportsTimeSinceVSync_Bool = 2000,
Prop_SecondsFromVsyncToPhotons_Float = 2001,
Prop_DisplayFrequency_Float = 2002,
@@ -3012,6 +3053,7 @@ public enum ETrackedDeviceProperty
Prop_ScreenshotHorizontalFieldOfViewDegrees_Float = 2034,
Prop_ScreenshotVerticalFieldOfViewDegrees_Float = 2035,
Prop_DisplaySuppressed_Bool = 2036,
+ Prop_DisplayAllowNightMode_Bool = 2037,
Prop_AttachedDeviceId_String = 3000,
Prop_SupportedButtons_Uint64 = 3001,
Prop_Axis0Type_Int32 = 3002,
@@ -3214,6 +3256,12 @@ public enum EVRMouseButton
Right = 2,
Middle = 4,
}
+public enum EHiddenAreaMeshType
+{
+ k_eHiddenAreaMesh_Standard = 0,
+ k_eHiddenAreaMesh_Inverse = 1,
+ k_eHiddenAreaMesh_LineLoop = 2,
+}
public enum EVRControllerAxisType
{
k_eControllerAxis_None = 0,
@@ -3256,6 +3304,8 @@ public enum EVROverlayError
UnableToLoadFile = 25,
KeyboardAlreadyInUse = 26,
NoNeighbor = 27,
+ TooManyMaskPrimitives = 29,
+ BadMaskPrimitive = 30,
}
public enum EVRApplicationType
{
@@ -3483,6 +3533,7 @@ public enum EVRCompositorError
TextureUsesUnsupportedFormat = 105,
SharedTexturesNotSupported = 106,
IndexOutOfRange = 107,
+ AlreadySubmitted = 108,
}
public enum VROverlayInputMethod
{
@@ -3533,6 +3584,11 @@ public enum EOverlayDirection
Right = 3,
Count = 4,
}
+public enum EVROverlayIntersectionMaskPrimitiveType
+{
+ OverlayIntersectionPrimitiveType_Rectangle = 0,
+ OverlayIntersectionPrimitiveType_Circle = 1,
+}
public enum EVRRenderModelError
{
None = 0,
@@ -3609,6 +3665,13 @@ public enum EVRScreenshotError
[FieldOffset(0)] public VREvent_Keyboard_t keyboard; // This has to be at the end due to a mono bug
}
+
+[StructLayout(LayoutKind.Explicit)] public struct VROverlayIntersectionMaskPrimitive_Data_t
+{
+ [FieldOffset(0)] public IntersectionMaskRectangle_t m_Rectangle;
+ [FieldOffset(0)] public IntersectionMaskCircle_t m_Circle;
+}
+
[StructLayout(LayoutKind.Sequential)] public struct HmdMatrix34_t
{
public float m0; //float[3][4]
@@ -3898,6 +3961,7 @@ public enum EVRScreenshotError
public uint m_nSize;
public uint m_nFrameIndex;
public uint m_nNumFramePresents;
+ public uint m_nNumMisPresented;
public uint m_nNumDroppedFrames;
public uint m_nReprojectionFlags;
public double m_flSystemTimeInSeconds;
@@ -3950,6 +4014,24 @@ public enum EVRScreenshotError
public HmdVector2_t vUVs;
public float fDistance;
}
+[StructLayout(LayoutKind.Sequential)] public struct IntersectionMaskRectangle_t
+{
+ public float m_flTopLeftX;
+ public float m_flTopLeftY;
+ public float m_flWidth;
+ public float m_flHeight;
+}
+[StructLayout(LayoutKind.Sequential)] public struct IntersectionMaskCircle_t
+{
+ public float m_flCenterX;
+ public float m_flCenterY;
+ public float m_flRadius;
+}
+[StructLayout(LayoutKind.Sequential)] public struct VROverlayIntersectionMaskPrimitive_t
+{
+ public EVROverlayIntersectionMaskPrimitiveType m_nPrimitiveType;
+ public VROverlayIntersectionMaskPrimitive_Data_t m_Primitive;
+}
[StructLayout(LayoutKind.Sequential)] public struct RenderModel_ComponentState_t
{
public HmdMatrix34_t mTrackingToComponentRenderModel;
@@ -4048,7 +4130,6 @@ public class OpenVR
return OpenVRInterop.GetInitToken();
}
- public const uint k_unTrackingStringSize = 32;
public const uint k_unMaxDriverDebugResponseSize = 32768;
public const uint k_unTrackedDeviceIndex_Hmd = 0;
public const uint k_unMaxTrackedDeviceCount = 16;
@@ -4058,7 +4139,7 @@ public class OpenVR
public const uint k_unControllerStateAxisCount = 5;
public const ulong k_ulOverlayHandleInvalid = 0;
public const uint k_unScreenshotHandleInvalid = 0;
- public const string IVRSystem_Version = "IVRSystem_012";
+ public const string IVRSystem_Version = "IVRSystem_014";
public const string IVRExtendedDisplay_Version = "IVRExtendedDisplay_001";
public const string IVRTrackedCamera_Version = "IVRTrackedCamera_003";
public const uint k_unMaxApplicationKeyLength = 128;
@@ -4067,10 +4148,11 @@ public class OpenVR
public const string IVRApplications_Version = "IVRApplications_006";
public const string IVRChaperone_Version = "IVRChaperone_003";
public const string IVRChaperoneSetup_Version = "IVRChaperoneSetup_005";
- public const string IVRCompositor_Version = "IVRCompositor_016";
+ public const string IVRCompositor_Version = "IVRCompositor_018";
public const uint k_unVROverlayMaxKeyLength = 128;
public const uint k_unVROverlayMaxNameLength = 128;
public const uint k_unMaxOverlayCount = 64;
+ public const uint k_unMaxOverlayIntersectionMaskPrimitivesCount = 32;
public const string IVROverlay_Version = "IVROverlay_013";
public const string k_pch_Controller_Component_GDC2015 = "gdc2015";
public const string k_pch_Controller_Component_Base = "base";
@@ -4095,9 +4177,9 @@ public class OpenVR
public const string k_pch_SteamVR_LogLevel_Int32 = "loglevel";
public const string k_pch_SteamVR_IPD_Float = "ipd";
public const string k_pch_SteamVR_Background_String = "background";
+ public const string k_pch_SteamVR_BackgroundUseDomeProjection_Bool = "backgroundUseDomeProjection";
public const string k_pch_SteamVR_BackgroundCameraHeight_Float = "backgroundCameraHeight";
public const string k_pch_SteamVR_BackgroundDomeRadius_Float = "backgroundDomeRadius";
- public const string k_pch_SteamVR_Environment_String = "environment";
public const string k_pch_SteamVR_GridColor_String = "gridColor";
public const string k_pch_SteamVR_PlayAreaColor_String = "playAreaColor";
public const string k_pch_SteamVR_ShowStage_Bool = "showStage";
@@ -4110,7 +4192,8 @@ public class OpenVR
public const string k_pch_SteamVR_BaseStationPowerManagement_Bool = "basestationPowerManagement";
public const string k_pch_SteamVR_NeverKillProcesses_Bool = "neverKillProcesses";
public const string k_pch_SteamVR_RenderTargetMultiplier_Float = "renderTargetMultiplier";
- public const string k_pch_SteamVR_AllowReprojection_Bool = "allowReprojection";
+ public const string k_pch_SteamVR_AllowAsyncReprojection_Bool = "allowAsyncReprojection";
+ public const string k_pch_SteamVR_AllowReprojection_Bool = "allowInterleavedReprojection";
public const string k_pch_SteamVR_ForceReprojection_Bool = "forceReprojection";
public const string k_pch_SteamVR_ForceFadeOnBadTracking_Bool = "forceFadeOnBadTracking";
public const string k_pch_SteamVR_DefaultMirrorView_Int32 = "defaultMirrorView";
@@ -4121,6 +4204,7 @@ public class OpenVR
public const string k_pch_SteamVR_SetInitialDefaultHomeApp = "setInitialDefaultHomeApp";
public const string k_pch_SteamVR_CycleBackgroundImageTimeSec_Int32 = "CycleBackgroundImageTimeSec";
public const string k_pch_SteamVR_RetailDemo_Bool = "retailDemo";
+ public const string k_pch_SteamVR_IpdOffset_Float = "ipdOffset";
public const string k_pch_Lighthouse_Section = "driver_lighthouse";
public const string k_pch_Lighthouse_DisableIMU_Bool = "disableimu";
public const string k_pch_Lighthouse_UseDisambiguation_String = "usedisambiguation";
@@ -4141,6 +4225,7 @@ public class OpenVR
public const string k_pch_Null_DisplayFrequency_Float = "displayFrequency";
public const string k_pch_UserInterface_Section = "userinterface";
public const string k_pch_UserInterface_StatusAlwaysOnTop_Bool = "StatusAlwaysOnTop";
+ public const string k_pch_UserInterface_MinimizeToTray_Bool = "MinimizeToTray";
public const string k_pch_UserInterface_Screenshots_Bool = "screenshots";
public const string k_pch_UserInterface_ScreenshotType_Int = "screenshotType";
public const string k_pch_Notifications_Section = "notifications";
diff --git a/headers/openvr_api.json b/headers/openvr_api.json
index 832e864..d16771d 100644
--- a/headers/openvr_api.json
+++ b/headers/openvr_api.json
@@ -8,6 +8,7 @@
,{"typedef": "vr::VROverlayHandle_t","type": "uint64_t"}
,{"typedef": "vr::TrackedCameraHandle_t","type": "uint64_t"}
,{"typedef": "vr::ScreenshotHandle_t","type": "uint32_t"}
+,{"typedef": "vr::VROverlayIntersectionMaskPrimitive_Data_t","type": "union VROverlayIntersectionMaskPrimitive_Data_t"}
,{"typedef": "vr::VRComponentProperties","type": "uint32_t"}
,{"typedef": "vr::TextureID_t","type": "int32_t"}
,{"typedef": "vr::VRNotificationId","type": "uint32_t"}
@@ -101,6 +102,7 @@
,{"name": "Prop_HasCamera_Bool","value": "1030"}
,{"name": "Prop_DriverVersion_String","value": "1031"}
,{"name": "Prop_Firmware_ForceUpdateRequired_Bool","value": "1032"}
+ ,{"name": "Prop_ViveSystemButtonFixRequired_Bool","value": "1033"}
,{"name": "Prop_ReportsTimeSinceVSync_Bool","value": "2000"}
,{"name": "Prop_SecondsFromVsyncToPhotons_Float","value": "2001"}
,{"name": "Prop_DisplayFrequency_Float","value": "2002"}
@@ -138,6 +140,7 @@
,{"name": "Prop_ScreenshotHorizontalFieldOfViewDegrees_Float","value": "2034"}
,{"name": "Prop_ScreenshotVerticalFieldOfViewDegrees_Float","value": "2035"}
,{"name": "Prop_DisplaySuppressed_Bool","value": "2036"}
+ ,{"name": "Prop_DisplayAllowNightMode_Bool","value": "2037"}
,{"name": "Prop_AttachedDeviceId_String","value": "3000"}
,{"name": "Prop_SupportedButtons_Uint64","value": "3001"}
,{"name": "Prop_Axis0Type_Int32","value": "3002"}
@@ -333,6 +336,11 @@
,{"name": "VRMouseButton_Right","value": "2"}
,{"name": "VRMouseButton_Middle","value": "4"}
]}
+, {"enumname": "vr::EHiddenAreaMeshType","values": [
+ {"name": "k_eHiddenAreaMesh_Standard","value": "0"}
+ ,{"name": "k_eHiddenAreaMesh_Inverse","value": "1"}
+ ,{"name": "k_eHiddenAreaMesh_LineLoop","value": "2"}
+]}
, {"enumname": "vr::EVRControllerAxisType","values": [
{"name": "k_eControllerAxis_None","value": "0"}
,{"name": "k_eControllerAxis_TrackPad","value": "1"}
@@ -371,6 +379,8 @@
,{"name": "VROverlayError_UnableToLoadFile","value": "25"}
,{"name": "VROverlayError_KeyboardAlreadyInUse","value": "26"}
,{"name": "VROverlayError_NoNeighbor","value": "27"}
+ ,{"name": "VROverlayError_TooManyMaskPrimitives","value": "29"}
+ ,{"name": "VROverlayError_BadMaskPrimitive","value": "30"}
]}
, {"enumname": "vr::EVRApplicationType","values": [
{"name": "VRApplication_Other","value": "0"}
@@ -583,6 +593,7 @@
,{"name": "VRCompositorError_TextureUsesUnsupportedFormat","value": "105"}
,{"name": "VRCompositorError_SharedTexturesNotSupported","value": "106"}
,{"name": "VRCompositorError_IndexOutOfRange","value": "107"}
+ ,{"name": "VRCompositorError_AlreadySubmitted","value": "108"}
]}
, {"enumname": "vr::VROverlayInputMethod","values": [
{"name": "VROverlayInputMethod_None","value": "0"}
@@ -627,6 +638,10 @@
,{"name": "OverlayDirection_Right","value": "3"}
,{"name": "OverlayDirection_Count","value": "4"}
]}
+, {"enumname": "vr::EVROverlayIntersectionMaskPrimitiveType","values": [
+ {"name": "OverlayIntersectionPrimitiveType_Rectangle","value": "0"}
+ ,{"name": "OverlayIntersectionPrimitiveType_Circle","value": "1"}
+]}
, {"enumname": "vr::EVRRenderModelError","values": [
{"name": "VRRenderModelError_None","value": "0"}
,{"name": "VRRenderModelError_Loading","value": "100"}
@@ -679,8 +694,6 @@
]}
],
"consts":[{
- "constname": "k_unTrackingStringSize","consttype": "const uint32_t", "constval": "32"}
-,{
"constname": "k_unMaxDriverDebugResponseSize","consttype": "const uint32_t", "constval": "32768"}
,{
"constname": "k_unTrackedDeviceIndex_Hmd","consttype": "const uint32_t", "constval": "0"}
@@ -699,7 +712,7 @@
,{
"constname": "k_unScreenshotHandleInvalid","consttype": "const uint32_t", "constval": "0"}
,{
- "constname": "IVRSystem_Version","consttype": "const char *const", "constval": "IVRSystem_012"}
+ "constname": "IVRSystem_Version","consttype": "const char *const", "constval": "IVRSystem_014"}
,{
"constname": "IVRExtendedDisplay_Version","consttype": "const char *const", "constval": "IVRExtendedDisplay_001"}
,{
@@ -717,7 +730,7 @@
,{
"constname": "IVRChaperoneSetup_Version","consttype": "const char *const", "constval": "IVRChaperoneSetup_005"}
,{
- "constname": "IVRCompositor_Version","consttype": "const char *const", "constval": "IVRCompositor_016"}
+ "constname": "IVRCompositor_Version","consttype": "const char *const", "constval": "IVRCompositor_018"}
,{
"constname": "k_unVROverlayMaxKeyLength","consttype": "const uint32_t", "constval": "128"}
,{
@@ -725,6 +738,8 @@
,{
"constname": "k_unMaxOverlayCount","consttype": "const uint32_t", "constval": "64"}
,{
+ "constname": "k_unMaxOverlayIntersectionMaskPrimitivesCount","consttype": "const uint32_t", "constval": "32"}
+,{
"constname": "IVROverlay_Version","consttype": "const char *const", "constval": "IVROverlay_013"}
,{
"constname": "k_pch_Controller_Component_GDC2015","consttype": "const char *const", "constval": "gdc2015"}
@@ -773,12 +788,12 @@
,{
"constname": "k_pch_SteamVR_Background_String","consttype": "const char *const", "constval": "background"}
,{
+ "constname": "k_pch_SteamVR_BackgroundUseDomeProjection_Bool","consttype": "const char *const", "constval": "backgroundUseDomeProjection"}
+,{
"constname": "k_pch_SteamVR_BackgroundCameraHeight_Float","consttype": "const char *const", "constval": "backgroundCameraHeight"}
,{
"constname": "k_pch_SteamVR_BackgroundDomeRadius_Float","consttype": "const char *const", "constval": "backgroundDomeRadius"}
,{
- "constname": "k_pch_SteamVR_Environment_String","consttype": "const char *const", "constval": "environment"}
-,{
"constname": "k_pch_SteamVR_GridColor_String","consttype": "const char *const", "constval": "gridColor"}
,{
"constname": "k_pch_SteamVR_PlayAreaColor_String","consttype": "const char *const", "constval": "playAreaColor"}
@@ -803,7 +818,9 @@
,{
"constname": "k_pch_SteamVR_RenderTargetMultiplier_Float","consttype": "const char *const", "constval": "renderTargetMultiplier"}
,{
- "constname": "k_pch_SteamVR_AllowReprojection_Bool","consttype": "const char *const", "constval": "allowReprojection"}
+ "constname": "k_pch_SteamVR_AllowAsyncReprojection_Bool","consttype": "const char *const", "constval": "allowAsyncReprojection"}
+,{
+ "constname": "k_pch_SteamVR_AllowReprojection_Bool","consttype": "const char *const", "constval": "allowInterleavedReprojection"}
,{
"constname": "k_pch_SteamVR_ForceReprojection_Bool","consttype": "const char *const", "constval": "forceReprojection"}
,{
@@ -825,6 +842,8 @@
,{
"constname": "k_pch_SteamVR_RetailDemo_Bool","consttype": "const char *const", "constval": "retailDemo"}
,{
+ "constname": "k_pch_SteamVR_IpdOffset_Float","consttype": "const char *const", "constval": "ipdOffset"}
+,{
"constname": "k_pch_Lighthouse_Section","consttype": "const char *const", "constval": "driver_lighthouse"}
,{
"constname": "k_pch_Lighthouse_DisableIMU_Bool","consttype": "const char *const", "constval": "disableimu"}
@@ -865,6 +884,8 @@
,{
"constname": "k_pch_UserInterface_StatusAlwaysOnTop_Bool","consttype": "const char *const", "constval": "StatusAlwaysOnTop"}
,{
+ "constname": "k_pch_UserInterface_MinimizeToTray_Bool","consttype": "const char *const", "constval": "MinimizeToTray"}
+,{
"constname": "k_pch_UserInterface_Screenshots_Bool","consttype": "const char *const", "constval": "screenshots"}
,{
"constname": "k_pch_UserInterface_ScreenshotType_Int","consttype": "const char *const", "constval": "screenshotType"}
@@ -1157,6 +1178,7 @@
{ "fieldname": "m_nSize", "fieldtype": "uint32_t"},
{ "fieldname": "m_nFrameIndex", "fieldtype": "uint32_t"},
{ "fieldname": "m_nNumFramePresents", "fieldtype": "uint32_t"},
+{ "fieldname": "m_nNumMisPresented", "fieldtype": "uint32_t"},
{ "fieldname": "m_nNumDroppedFrames", "fieldtype": "uint32_t"},
{ "fieldname": "m_nReprojectionFlags", "fieldtype": "uint32_t"},
{ "fieldname": "m_flSystemTimeInSeconds", "fieldtype": "double"},
@@ -1202,6 +1224,21 @@
{ "fieldname": "vNormal", "fieldtype": "struct vr::HmdVector3_t"},
{ "fieldname": "vUVs", "fieldtype": "struct vr::HmdVector2_t"},
{ "fieldname": "fDistance", "fieldtype": "float"}]}
+,{"struct": "vr::IntersectionMaskRectangle_t","fields": [
+{ "fieldname": "m_flTopLeftX", "fieldtype": "float"},
+{ "fieldname": "m_flTopLeftY", "fieldtype": "float"},
+{ "fieldname": "m_flWidth", "fieldtype": "float"},
+{ "fieldname": "m_flHeight", "fieldtype": "float"}]}
+,{"struct": "vr::IntersectionMaskCircle_t","fields": [
+{ "fieldname": "m_flCenterX", "fieldtype": "float"},
+{ "fieldname": "m_flCenterY", "fieldtype": "float"},
+{ "fieldname": "m_flRadius", "fieldtype": "float"}]}
+,{"struct": "vr::(anonymous)","fields": [
+{ "fieldname": "m_Rectangle", "fieldtype": "struct vr::IntersectionMaskRectangle_t"},
+{ "fieldname": "m_Circle", "fieldtype": "struct vr::IntersectionMaskCircle_t"}]}
+,{"struct": "vr::VROverlayIntersectionMaskPrimitive_t","fields": [
+{ "fieldname": "m_nPrimitiveType", "fieldtype": "enum vr::EVROverlayIntersectionMaskPrimitiveType"},
+{ "fieldname": "m_Primitive", "fieldtype": "VROverlayIntersectionMaskPrimitive_Data_t"}]}
,{"struct": "vr::RenderModel_ComponentState_t","fields": [
{ "fieldname": "mTrackingToComponentRenderModel", "fieldtype": "struct vr::HmdMatrix34_t"},
{ "fieldname": "mTrackingToComponentLocal", "fieldtype": "struct vr::HmdMatrix34_t"},
@@ -1276,11 +1313,12 @@
,{
"classname": "vr::IVRSystem",
"methodname": "ComputeDistortion",
- "returntype": "struct vr::DistortionCoordinates_t",
+ "returntype": "bool",
"params": [
{ "paramname": "eEye" ,"paramtype": "vr::EVREye"},
{ "paramname": "fU" ,"paramtype": "float"},
-{ "paramname": "fV" ,"paramtype": "float"}
+{ "paramname": "fV" ,"paramtype": "float"},
+{ "paramname": "pDistortionCoordinates" ,"paramtype": "struct vr::DistortionCoordinates_t *"}
]
}
,{
@@ -1516,7 +1554,8 @@
"methodname": "GetHiddenAreaMesh",
"returntype": "struct vr::HiddenAreaMesh_t",
"params": [
-{ "paramname": "eEye" ,"paramtype": "vr::EVREye"}
+{ "paramname": "eEye" ,"paramtype": "vr::EVREye"},
+{ "paramname": "type" ,"paramtype": "vr::EHiddenAreaMeshType"}
]
}
,{
@@ -1525,7 +1564,8 @@
"returntype": "bool",
"params": [
{ "paramname": "unControllerDeviceIndex" ,"paramtype": "vr::TrackedDeviceIndex_t"},
-{ "paramname": "pControllerState" ,"paramtype": "vr::VRControllerState_t *"}
+{ "paramname": "pControllerState" ,"paramtype": "vr::VRControllerState_t *"},
+{ "paramname": "unControllerStateSize" ,"paramtype": "uint32_t"}
]
}
,{
@@ -1536,6 +1576,7 @@
{ "paramname": "eOrigin" ,"paramtype": "vr::ETrackingUniverseOrigin"},
{ "paramname": "unControllerDeviceIndex" ,"paramtype": "vr::TrackedDeviceIndex_t"},
{ "paramname": "pControllerState" ,"paramtype": "vr::VRControllerState_t *"},
+{ "paramname": "unControllerStateSize" ,"paramtype": "uint32_t"},
{ "paramname": "pTrackedDevicePose" ,"paramtype": "struct vr::TrackedDevicePose_t *"}
]
}
@@ -2335,6 +2376,15 @@
}
,{
"classname": "vr::IVRCompositor",
+ "methodname": "GetFrameTimings",
+ "returntype": "uint32_t",
+ "params": [
+{ "paramname": "pTiming" ,"paramtype": "struct vr::Compositor_FrameTiming *"},
+{ "paramname": "nFrames" ,"paramtype": "uint32_t"}
+ ]
+}
+,{
+ "classname": "vr::IVRCompositor",
"methodname": "GetFrameTimeRemaining",
"returntype": "float"
}
@@ -2362,6 +2412,14 @@
}
,{
"classname": "vr::IVRCompositor",
+ "methodname": "GetCurrentFadeColor",
+ "returntype": "struct vr::HmdColor_t",
+ "params": [
+{ "paramname": "bBackground" ,"paramtype": "bool"}
+ ]
+}
+,{
+ "classname": "vr::IVRCompositor",
"methodname": "FadeGrid",
"returntype": "void",
"params": [
@@ -2371,6 +2429,11 @@
}
,{
"classname": "vr::IVRCompositor",
+ "methodname": "GetCurrentGridAlpha",
+ "returntype": "float"
+}
+,{
+ "classname": "vr::IVRCompositor",
"methodname": "SetSkyboxOverride",
"returntype": "vr::EVRCompositorError",
"params": [
@@ -3177,6 +3240,17 @@
]
}
,{
+ "classname": "vr::IVROverlay",
+ "methodname": "SetOverlayIntersectionMask",
+ "returntype": "vr::EVROverlayError",
+ "params": [
+{ "paramname": "ulOverlayHandle" ,"paramtype": "vr::VROverlayHandle_t"},
+{ "paramname": "pMaskPrimitives" ,"paramtype": "struct vr::VROverlayIntersectionMaskPrimitive_t *"},
+{ "paramname": "unNumMaskPrimitives" ,"paramtype": "uint32_t"},
+{ "paramname": "unPrimitiveSize" ,"paramtype": "uint32_t"}
+ ]
+}
+,{
"classname": "vr::IVRRenderModels",
"methodname": "LoadRenderModel_Async",
"returntype": "vr::EVRRenderModelError",
diff --git a/headers/openvr_capi.h b/headers/openvr_capi.h
index fae48f8..6ecbffd 100644
--- a/headers/openvr_capi.h
+++ b/headers/openvr_capi.h
@@ -46,12 +46,13 @@
#if defined( __WIN32 )
typedef char bool;
+#else
+#include <stdbool.h>
#endif
// OpenVR Constants
-static const unsigned int k_unTrackingStringSize = 32;
static const unsigned int k_unMaxDriverDebugResponseSize = 32768;
static const unsigned int k_unTrackedDeviceIndex_Hmd = 0;
static const unsigned int k_unMaxTrackedDeviceCount = 16;
@@ -61,7 +62,7 @@ static const unsigned int k_unMaxPropertyStringSize = 32768;
static const unsigned int k_unControllerStateAxisCount = 5;
static const unsigned long k_ulOverlayHandleInvalid = 0;
static const unsigned int k_unScreenshotHandleInvalid = 0;
-static const char * IVRSystem_Version = "IVRSystem_012";
+static const char * IVRSystem_Version = "IVRSystem_014";
static const char * IVRExtendedDisplay_Version = "IVRExtendedDisplay_001";
static const char * IVRTrackedCamera_Version = "IVRTrackedCamera_003";
static const unsigned int k_unMaxApplicationKeyLength = 128;
@@ -70,10 +71,11 @@ static const char * k_pch_MimeType_GameTheater = "vr/game_theater";
static const char * IVRApplications_Version = "IVRApplications_006";
static const char * IVRChaperone_Version = "IVRChaperone_003";
static const char * IVRChaperoneSetup_Version = "IVRChaperoneSetup_005";
-static const char * IVRCompositor_Version = "IVRCompositor_016";
+static const char * IVRCompositor_Version = "IVRCompositor_018";
static const unsigned int k_unVROverlayMaxKeyLength = 128;
static const unsigned int k_unVROverlayMaxNameLength = 128;
static const unsigned int k_unMaxOverlayCount = 64;
+static const unsigned int k_unMaxOverlayIntersectionMaskPrimitivesCount = 32;
static const char * IVROverlay_Version = "IVROverlay_013";
static const char * k_pch_Controller_Component_GDC2015 = "gdc2015";
static const char * k_pch_Controller_Component_Base = "base";
@@ -98,9 +100,9 @@ static const char * k_pch_SteamVR_SendSystemButtonToAllApps_Bool = "sendSystemBu
static const char * k_pch_SteamVR_LogLevel_Int32 = "loglevel";
static const char * k_pch_SteamVR_IPD_Float = "ipd";
static const char * k_pch_SteamVR_Background_String = "background";
+static const char * k_pch_SteamVR_BackgroundUseDomeProjection_Bool = "backgroundUseDomeProjection";
static const char * k_pch_SteamVR_BackgroundCameraHeight_Float = "backgroundCameraHeight";
static const char * k_pch_SteamVR_BackgroundDomeRadius_Float = "backgroundDomeRadius";
-static const char * k_pch_SteamVR_Environment_String = "environment";
static const char * k_pch_SteamVR_GridColor_String = "gridColor";
static const char * k_pch_SteamVR_PlayAreaColor_String = "playAreaColor";
static const char * k_pch_SteamVR_ShowStage_Bool = "showStage";
@@ -113,7 +115,8 @@ static const char * k_pch_SteamVR_SpeakersForwardYawOffsetDegrees_Float = "speak
static const char * k_pch_SteamVR_BaseStationPowerManagement_Bool = "basestationPowerManagement";
static const char * k_pch_SteamVR_NeverKillProcesses_Bool = "neverKillProcesses";
static const char * k_pch_SteamVR_RenderTargetMultiplier_Float = "renderTargetMultiplier";
-static const char * k_pch_SteamVR_AllowReprojection_Bool = "allowReprojection";
+static const char * k_pch_SteamVR_AllowAsyncReprojection_Bool = "allowAsyncReprojection";
+static const char * k_pch_SteamVR_AllowReprojection_Bool = "allowInterleavedReprojection";
static const char * k_pch_SteamVR_ForceReprojection_Bool = "forceReprojection";
static const char * k_pch_SteamVR_ForceFadeOnBadTracking_Bool = "forceFadeOnBadTracking";
static const char * k_pch_SteamVR_DefaultMirrorView_Int32 = "defaultMirrorView";
@@ -124,6 +127,7 @@ static const char * k_pch_SteamVR_EnableHomeApp = "enableHomeApp";
static const char * k_pch_SteamVR_SetInitialDefaultHomeApp = "setInitialDefaultHomeApp";
static const char * k_pch_SteamVR_CycleBackgroundImageTimeSec_Int32 = "CycleBackgroundImageTimeSec";
static const char * k_pch_SteamVR_RetailDemo_Bool = "retailDemo";
+static const char * k_pch_SteamVR_IpdOffset_Float = "ipdOffset";
static const char * k_pch_Lighthouse_Section = "driver_lighthouse";
static const char * k_pch_Lighthouse_DisableIMU_Bool = "disableimu";
static const char * k_pch_Lighthouse_UseDisambiguation_String = "usedisambiguation";
@@ -144,6 +148,7 @@ static const char * k_pch_Null_SecondsFromVsyncToPhotons_Float = "secondsFromVsy
static const char * k_pch_Null_DisplayFrequency_Float = "displayFrequency";
static const char * k_pch_UserInterface_Section = "userinterface";
static const char * k_pch_UserInterface_StatusAlwaysOnTop_Bool = "StatusAlwaysOnTop";
+static const char * k_pch_UserInterface_MinimizeToTray_Bool = "MinimizeToTray";
static const char * k_pch_UserInterface_Screenshots_Bool = "screenshots";
static const char * k_pch_UserInterface_ScreenshotType_Int = "screenshotType";
static const char * k_pch_Notifications_Section = "notifications";
@@ -292,6 +297,7 @@ typedef enum ETrackedDeviceProperty
ETrackedDeviceProperty_Prop_HasCamera_Bool = 1030,
ETrackedDeviceProperty_Prop_DriverVersion_String = 1031,
ETrackedDeviceProperty_Prop_Firmware_ForceUpdateRequired_Bool = 1032,
+ ETrackedDeviceProperty_Prop_ViveSystemButtonFixRequired_Bool = 1033,
ETrackedDeviceProperty_Prop_ReportsTimeSinceVSync_Bool = 2000,
ETrackedDeviceProperty_Prop_SecondsFromVsyncToPhotons_Float = 2001,
ETrackedDeviceProperty_Prop_DisplayFrequency_Float = 2002,
@@ -329,6 +335,7 @@ typedef enum ETrackedDeviceProperty
ETrackedDeviceProperty_Prop_ScreenshotHorizontalFieldOfViewDegrees_Float = 2034,
ETrackedDeviceProperty_Prop_ScreenshotVerticalFieldOfViewDegrees_Float = 2035,
ETrackedDeviceProperty_Prop_DisplaySuppressed_Bool = 2036,
+ ETrackedDeviceProperty_Prop_DisplayAllowNightMode_Bool = 2037,
ETrackedDeviceProperty_Prop_AttachedDeviceId_String = 3000,
ETrackedDeviceProperty_Prop_SupportedButtons_Uint64 = 3001,
ETrackedDeviceProperty_Prop_Axis0Type_Int32 = 3002,
@@ -539,6 +546,13 @@ typedef enum EVRMouseButton
EVRMouseButton_VRMouseButton_Middle = 4,
} EVRMouseButton;
+typedef enum EHiddenAreaMeshType
+{
+ EHiddenAreaMeshType_k_eHiddenAreaMesh_Standard = 0,
+ EHiddenAreaMeshType_k_eHiddenAreaMesh_Inverse = 1,
+ EHiddenAreaMeshType_k_eHiddenAreaMesh_LineLoop = 2,
+} EHiddenAreaMeshType;
+
typedef enum EVRControllerAxisType
{
EVRControllerAxisType_k_eControllerAxis_None = 0,
@@ -584,6 +598,8 @@ typedef enum EVROverlayError
EVROverlayError_VROverlayError_UnableToLoadFile = 25,
EVROverlayError_VROverlayError_KeyboardAlreadyInUse = 26,
EVROverlayError_VROverlayError_NoNeighbor = 27,
+ EVROverlayError_VROverlayError_TooManyMaskPrimitives = 29,
+ EVROverlayError_VROverlayError_BadMaskPrimitive = 30,
} EVROverlayError;
typedef enum EVRApplicationType
@@ -826,6 +842,7 @@ typedef enum EVRCompositorError
EVRCompositorError_VRCompositorError_TextureUsesUnsupportedFormat = 105,
EVRCompositorError_VRCompositorError_SharedTexturesNotSupported = 106,
EVRCompositorError_VRCompositorError_IndexOutOfRange = 107,
+ EVRCompositorError_VRCompositorError_AlreadySubmitted = 108,
} EVRCompositorError;
typedef enum VROverlayInputMethod
@@ -883,6 +900,12 @@ typedef enum EOverlayDirection
EOverlayDirection_OverlayDirection_Count = 4,
} EOverlayDirection;
+typedef enum EVROverlayIntersectionMaskPrimitiveType
+{
+ EVROverlayIntersectionMaskPrimitiveType_OverlayIntersectionPrimitiveType_Rectangle = 0,
+ EVROverlayIntersectionMaskPrimitiveType_OverlayIntersectionPrimitiveType_Circle = 1,
+} EVROverlayIntersectionMaskPrimitiveType;
+
typedef enum EVRRenderModelError
{
EVRRenderModelError_VRRenderModelError_None = 0,
@@ -1251,6 +1274,7 @@ typedef struct Compositor_FrameTiming
uint32_t m_nSize;
uint32_t m_nFrameIndex;
uint32_t m_nNumFramePresents;
+ uint32_t m_nNumMisPresented;
uint32_t m_nNumDroppedFrames;
uint32_t m_nReprojectionFlags;
double m_flSystemTimeInSeconds;
@@ -1307,6 +1331,21 @@ typedef struct VROverlayIntersectionResults_t
float fDistance;
} VROverlayIntersectionResults_t;
+typedef struct IntersectionMaskRectangle_t
+{
+ float m_flTopLeftX;
+ float m_flTopLeftY;
+ float m_flWidth;
+ float m_flHeight;
+} IntersectionMaskRectangle_t;
+
+typedef struct IntersectionMaskCircle_t
+{
+ float m_flCenterX;
+ float m_flCenterY;
+ float m_flRadius;
+} IntersectionMaskCircle_t;
+
typedef struct RenderModel_ComponentState_t
{
struct HmdMatrix34_t mTrackingToComponentRenderModel;
@@ -1396,6 +1435,19 @@ struct VREvent_t
};
+typedef union
+{
+ IntersectionMaskRectangle_t m_Rectangle;
+ IntersectionMaskCircle_t m_Circle;
+} VROverlayIntersectionMaskPrimitive_Data_t;
+
+struct VROverlayIntersectionMaskPrimitive_t
+{
+ EVROverlayIntersectionMaskPrimitiveType m_nPrimitiveType;
+ VROverlayIntersectionMaskPrimitive_Data_t m_Primitive;
+};
+
+
// OpenVR Function Pointer Tables
struct VR_IVRSystem_FnTable
@@ -1403,7 +1455,7 @@ struct VR_IVRSystem_FnTable
void (OPENVR_FNTABLE_CALLTYPE *GetRecommendedRenderTargetSize)(uint32_t * pnWidth, uint32_t * pnHeight);
struct HmdMatrix44_t (OPENVR_FNTABLE_CALLTYPE *GetProjectionMatrix)(EVREye eEye, float fNearZ, float fFarZ, EGraphicsAPIConvention eProjType);
void (OPENVR_FNTABLE_CALLTYPE *GetProjectionRaw)(EVREye eEye, float * pfLeft, float * pfRight, float * pfTop, float * pfBottom);
- struct DistortionCoordinates_t (OPENVR_FNTABLE_CALLTYPE *ComputeDistortion)(EVREye eEye, float fU, float fV);
+ bool (OPENVR_FNTABLE_CALLTYPE *ComputeDistortion)(EVREye eEye, float fU, float fV, struct DistortionCoordinates_t * pDistortionCoordinates);
struct HmdMatrix34_t (OPENVR_FNTABLE_CALLTYPE *GetEyeToHeadTransform)(EVREye eEye);
bool (OPENVR_FNTABLE_CALLTYPE *GetTimeSinceLastVsync)(float * pfSecondsSinceLastVsync, uint64_t * pulFrameCounter);
int32_t (OPENVR_FNTABLE_CALLTYPE *GetD3D9AdapterIndex)();
@@ -1431,9 +1483,9 @@ struct VR_IVRSystem_FnTable
bool (OPENVR_FNTABLE_CALLTYPE *PollNextEvent)(struct VREvent_t * pEvent, uint32_t uncbVREvent);
bool (OPENVR_FNTABLE_CALLTYPE *PollNextEventWithPose)(ETrackingUniverseOrigin eOrigin, struct VREvent_t * pEvent, uint32_t uncbVREvent, TrackedDevicePose_t * pTrackedDevicePose);
char * (OPENVR_FNTABLE_CALLTYPE *GetEventTypeNameFromEnum)(EVREventType eType);
- struct HiddenAreaMesh_t (OPENVR_FNTABLE_CALLTYPE *GetHiddenAreaMesh)(EVREye eEye);
- bool (OPENVR_FNTABLE_CALLTYPE *GetControllerState)(TrackedDeviceIndex_t unControllerDeviceIndex, VRControllerState_t * pControllerState);
- bool (OPENVR_FNTABLE_CALLTYPE *GetControllerStateWithPose)(ETrackingUniverseOrigin eOrigin, TrackedDeviceIndex_t unControllerDeviceIndex, VRControllerState_t * pControllerState, struct TrackedDevicePose_t * pTrackedDevicePose);
+ struct HiddenAreaMesh_t (OPENVR_FNTABLE_CALLTYPE *GetHiddenAreaMesh)(EVREye eEye, EHiddenAreaMeshType type);
+ bool (OPENVR_FNTABLE_CALLTYPE *GetControllerState)(TrackedDeviceIndex_t unControllerDeviceIndex, VRControllerState_t * pControllerState, uint32_t unControllerStateSize);
+ bool (OPENVR_FNTABLE_CALLTYPE *GetControllerStateWithPose)(ETrackingUniverseOrigin eOrigin, TrackedDeviceIndex_t unControllerDeviceIndex, VRControllerState_t * pControllerState, uint32_t unControllerStateSize, struct TrackedDevicePose_t * pTrackedDevicePose);
void (OPENVR_FNTABLE_CALLTYPE *TriggerHapticPulse)(TrackedDeviceIndex_t unControllerDeviceIndex, uint32_t unAxisId, unsigned short usDurationMicroSec);
char * (OPENVR_FNTABLE_CALLTYPE *GetButtonIdNameFromEnum)(EVRButtonId eButtonId);
char * (OPENVR_FNTABLE_CALLTYPE *GetControllerAxisTypeNameFromEnum)(EVRControllerAxisType eAxisType);
@@ -1550,10 +1602,13 @@ struct VR_IVRCompositor_FnTable
void (OPENVR_FNTABLE_CALLTYPE *ClearLastSubmittedFrame)();
void (OPENVR_FNTABLE_CALLTYPE *PostPresentHandoff)();
bool (OPENVR_FNTABLE_CALLTYPE *GetFrameTiming)(struct Compositor_FrameTiming * pTiming, uint32_t unFramesAgo);
+ uint32_t (OPENVR_FNTABLE_CALLTYPE *GetFrameTimings)(struct Compositor_FrameTiming * pTiming, uint32_t nFrames);
float (OPENVR_FNTABLE_CALLTYPE *GetFrameTimeRemaining)();
void (OPENVR_FNTABLE_CALLTYPE *GetCumulativeStats)(struct Compositor_CumulativeStats * pStats, uint32_t nStatsSizeInBytes);
void (OPENVR_FNTABLE_CALLTYPE *FadeToColor)(float fSeconds, float fRed, float fGreen, float fBlue, float fAlpha, bool bBackground);
+ struct HmdColor_t (OPENVR_FNTABLE_CALLTYPE *GetCurrentFadeColor)(bool bBackground);
void (OPENVR_FNTABLE_CALLTYPE *FadeGrid)(float fSeconds, bool bFadeIn);
+ float (OPENVR_FNTABLE_CALLTYPE *GetCurrentGridAlpha)();
EVRCompositorError (OPENVR_FNTABLE_CALLTYPE *SetSkyboxOverride)(struct Texture_t * pTextures, uint32_t unTextureCount);
void (OPENVR_FNTABLE_CALLTYPE *ClearSkyboxOverride)();
void (OPENVR_FNTABLE_CALLTYPE *CompositorBringToFront)();
@@ -1652,6 +1707,7 @@ struct VR_IVROverlay_FnTable
void (OPENVR_FNTABLE_CALLTYPE *HideKeyboard)();
void (OPENVR_FNTABLE_CALLTYPE *SetKeyboardTransformAbsolute)(ETrackingUniverseOrigin eTrackingOrigin, struct HmdMatrix34_t * pmatTrackingOriginToKeyboardTransform);
void (OPENVR_FNTABLE_CALLTYPE *SetKeyboardPositionForOverlay)(VROverlayHandle_t ulOverlayHandle, struct HmdRect2_t avoidRect);
+ EVROverlayError (OPENVR_FNTABLE_CALLTYPE *SetOverlayIntersectionMask)(VROverlayHandle_t ulOverlayHandle, struct VROverlayIntersectionMaskPrimitive_t * pMaskPrimitives, uint32_t unNumMaskPrimitives, uint32_t unPrimitiveSize);
};
struct VR_IVRRenderModels_FnTable
diff --git a/headers/openvr_driver.h b/headers/openvr_driver.h
index 643c117..ae778b8 100644
--- a/headers/openvr_driver.h
+++ b/headers/openvr_driver.h
@@ -146,7 +146,6 @@ enum ETrackingResult
TrackingResult_Running_OutOfRange = 201,
};
-static const uint32_t k_unTrackingStringSize = 32;
static const uint32_t k_unMaxDriverDebugResponseSize = 32768;
/** Used to pass device IDs to API calls */
@@ -241,6 +240,7 @@ enum ETrackedDeviceProperty
Prop_HasCamera_Bool = 1030,
Prop_DriverVersion_String = 1031,
Prop_Firmware_ForceUpdateRequired_Bool = 1032,
+ Prop_ViveSystemButtonFixRequired_Bool = 1033,
// Properties that are unique to TrackedDeviceClass_HMD
Prop_ReportsTimeSinceVSync_Bool = 2000,
@@ -280,6 +280,7 @@ enum ETrackedDeviceProperty
Prop_ScreenshotHorizontalFieldOfViewDegrees_Float = 2034,
Prop_ScreenshotVerticalFieldOfViewDegrees_Float = 2035,
Prop_DisplaySuppressed_Bool = 2036,
+ Prop_DisplayAllowNightMode_Bool = 2037,
// Properties that are unique to TrackedDeviceClass_Controller
Prop_AttachedDeviceId_String = 3000,
@@ -702,7 +703,7 @@ struct VREvent_EditingCameraSurface_t
uint32_t nVisualMode;
};
-/** If you change this you must manually update openvr_interop.cs.py */
+/** NOTE!!! If you change this you MUST manually update openvr_interop.cs.py */
typedef union
{
VREvent_Reserved_t reserved;
@@ -749,6 +750,14 @@ struct HiddenAreaMesh_t
};
+enum EHiddenAreaMeshType
+{
+ k_eHiddenAreaMesh_Standard = 0,
+ k_eHiddenAreaMesh_Inverse = 1,
+ k_eHiddenAreaMesh_LineLoop = 2,
+};
+
+
/** Identifies what kind of axis is on the controller at index n. Read this type
* with pVRSystem->Get( nControllerDeviceIndex, Prop_Axis0Type_Int32 + n );
*/
@@ -832,26 +841,28 @@ static const VROverlayHandle_t k_ulOverlayHandleInvalid = 0;
/** Errors that can occur around VR overlays */
enum EVROverlayError
{
- VROverlayError_None = 0,
-
- VROverlayError_UnknownOverlay = 10,
- VROverlayError_InvalidHandle = 11,
- VROverlayError_PermissionDenied = 12,
- VROverlayError_OverlayLimitExceeded = 13, // No more overlays could be created because the maximum number already exist
- VROverlayError_WrongVisibilityType = 14,
- VROverlayError_KeyTooLong = 15,
- VROverlayError_NameTooLong = 16,
- VROverlayError_KeyInUse = 17,
- VROverlayError_WrongTransformType = 18,
- VROverlayError_InvalidTrackedDevice = 19,
- VROverlayError_InvalidParameter = 20,
- VROverlayError_ThumbnailCantBeDestroyed = 21,
- VROverlayError_ArrayTooSmall = 22,
- VROverlayError_RequestFailed = 23,
- VROverlayError_InvalidTexture = 24,
- VROverlayError_UnableToLoadFile = 25,
- VROverlayError_KeyboardAlreadyInUse = 26,
- VROverlayError_NoNeighbor = 27,
+ VROverlayError_None = 0,
+
+ VROverlayError_UnknownOverlay = 10,
+ VROverlayError_InvalidHandle = 11,
+ VROverlayError_PermissionDenied = 12,
+ VROverlayError_OverlayLimitExceeded = 13, // No more overlays could be created because the maximum number already exist
+ VROverlayError_WrongVisibilityType = 14,
+ VROverlayError_KeyTooLong = 15,
+ VROverlayError_NameTooLong = 16,
+ VROverlayError_KeyInUse = 17,
+ VROverlayError_WrongTransformType = 18,
+ VROverlayError_InvalidTrackedDevice = 19,
+ VROverlayError_InvalidParameter = 20,
+ VROverlayError_ThumbnailCantBeDestroyed = 21,
+ VROverlayError_ArrayTooSmall = 22,
+ VROverlayError_RequestFailed = 23,
+ VROverlayError_InvalidTexture = 24,
+ VROverlayError_UnableToLoadFile = 25,
+ VROverlayError_KeyboardAlreadyInUse = 26,
+ VROverlayError_NoNeighbor = 27,
+ VROverlayError_TooManyMaskPrimitives = 29,
+ VROverlayError_BadMaskPrimitive = 30,
};
/** enum values to pass in to VR_Init to identify whether the application will
@@ -1260,9 +1271,9 @@ namespace vr
static const char * const k_pch_SteamVR_LogLevel_Int32 = "loglevel";
static const char * const k_pch_SteamVR_IPD_Float = "ipd";
static const char * const k_pch_SteamVR_Background_String = "background";
+ static const char * const k_pch_SteamVR_BackgroundUseDomeProjection_Bool = "backgroundUseDomeProjection";
static const char * const k_pch_SteamVR_BackgroundCameraHeight_Float = "backgroundCameraHeight";
static const char * const k_pch_SteamVR_BackgroundDomeRadius_Float = "backgroundDomeRadius";
- static const char * const k_pch_SteamVR_Environment_String = "environment";
static const char * const k_pch_SteamVR_GridColor_String = "gridColor";
static const char * const k_pch_SteamVR_PlayAreaColor_String = "playAreaColor";
static const char * const k_pch_SteamVR_ShowStage_Bool = "showStage";
@@ -1275,7 +1286,8 @@ namespace vr
static const char * const k_pch_SteamVR_BaseStationPowerManagement_Bool = "basestationPowerManagement";
static const char * const k_pch_SteamVR_NeverKillProcesses_Bool = "neverKillProcesses";
static const char * const k_pch_SteamVR_RenderTargetMultiplier_Float = "renderTargetMultiplier";
- static const char * const k_pch_SteamVR_AllowReprojection_Bool = "allowReprojection";
+ static const char * const k_pch_SteamVR_AllowAsyncReprojection_Bool = "allowAsyncReprojection";
+ static const char * const k_pch_SteamVR_AllowReprojection_Bool = "allowInterleavedReprojection";
static const char * const k_pch_SteamVR_ForceReprojection_Bool = "forceReprojection";
static const char * const k_pch_SteamVR_ForceFadeOnBadTracking_Bool = "forceFadeOnBadTracking";
static const char * const k_pch_SteamVR_DefaultMirrorView_Int32 = "defaultMirrorView";
@@ -1286,6 +1298,7 @@ namespace vr
static const char * const k_pch_SteamVR_SetInitialDefaultHomeApp = "setInitialDefaultHomeApp";
static const char * const k_pch_SteamVR_CycleBackgroundImageTimeSec_Int32 = "CycleBackgroundImageTimeSec";
static const char * const k_pch_SteamVR_RetailDemo_Bool = "retailDemo";
+ static const char * const k_pch_SteamVR_IpdOffset_Float = "ipdOffset";
//-----------------------------------------------------------------------------
@@ -1319,6 +1332,7 @@ namespace vr
// user interface keys
static const char * const k_pch_UserInterface_Section = "userinterface";
static const char * const k_pch_UserInterface_StatusAlwaysOnTop_Bool = "StatusAlwaysOnTop";
+ static const char * const k_pch_UserInterface_MinimizeToTray_Bool = "MinimizeToTray";
static const char * const k_pch_UserInterface_Screenshots_Bool = "screenshots";
static const char * const k_pch_UserInterface_ScreenshotType_Int = "screenshotType";
@@ -1542,9 +1556,8 @@ public:
/** Returns a string property. If the property is not available this function will return 0 and pError will be
* set to an error. Otherwise it returns the length of the number of bytes necessary to hold this string including
- * the trailing null. If the buffer is too small the error will be TrackedProp_BufferTooSmall. Strings will
- * generally fit in buffers of k_unTrackingStringSize characters. Drivers may not return strings longer than
- * k_unMaxPropertyStringSize. */
+ * the trailing null. If the buffer is too small the error will be TrackedProp_BufferTooSmall. Drivers may not
+ * return strings longer than k_unMaxPropertyStringSize. */
virtual uint32_t GetStringTrackedDeviceProperty( ETrackedDeviceProperty prop, char *pchValue, uint32_t unBufferSize, ETrackedPropertyError *pError ) = 0;
};
@@ -1786,6 +1799,10 @@ public:
/** Returns true if SteamVR is exiting */
virtual bool IsExiting() = 0;
+
+ /** Returns true and fills the event with the next event on the queue if there is one. If there are no events
+ * this method returns false. uncbVREvent should be the size in bytes of the VREvent_t struct */
+ virtual bool PollNextEvent( VREvent_t *pEvent, uint32_t uncbVREvent ) = 0;
};
@@ -1876,7 +1893,7 @@ public:
virtual uint32_t GetStringTrackedDeviceProperty( vr::TrackedDeviceIndex_t unDeviceIndex, ETrackedDeviceProperty prop, char *pchValue, uint32_t unBufferSize, ETrackedPropertyError *pError = 0L ) = 0;
/** always returns a pointer to a valid interface pointer of IVRSettings */
- virtual IVRSettings *GetSettings( const char *pchInterfaceVersion ) = 0;
+ virtual void *GetGenericInterface( const char *pchInterfaceVersion ) = 0;
/** Client drivers in watchdog mode should call this when they have received a signal from hardware that should
* cause SteamVR to start */
@@ -1927,14 +1944,14 @@ public:
* This will improve perf by letting the GPU early-reject pixels the user will never see before running the pixel shader.
* NOTE: Render this mesh with backface culling disabled since the winding order of the vertices can be different per-HMD or per-eye.
*/
- virtual HiddenAreaMesh_t GetHiddenAreaMesh( EVREye eEye ) = 0;
+ virtual HiddenAreaMesh_t GetHiddenAreaMesh( EVREye eEye, EHiddenAreaMeshType type ) = 0;
/** Get the MC image for the current HMD.
* Returns the size in bytes of the buffer required to hold the specified resource. */
virtual uint32_t GetMCImage( uint32_t *pImgWidth, uint32_t *pImgHeight, uint32_t *pChannels, void *pDataBuffer, uint32_t unBufferLen ) = 0;
};
-static const char *IClientTrackedDeviceProvider_Version = "IClientTrackedDeviceProvider_004";
+static const char *IClientTrackedDeviceProvider_Version = "IClientTrackedDeviceProvider_005";
}
diff --git a/lib/linux64/libopenvr_api.so b/lib/linux64/libopenvr_api.so
index d8ddc31..d3b8cc7 100755
--- a/lib/linux64/libopenvr_api.so
+++ b/lib/linux64/libopenvr_api.so
Binary files differ
diff --git a/lib/win32/openvr_api.lib b/lib/win32/openvr_api.lib
index 8322d9c..ca1946a 100644
--- a/lib/win32/openvr_api.lib
+++ b/lib/win32/openvr_api.lib
Binary files differ
diff --git a/lib/win64/openvr_api.lib b/lib/win64/openvr_api.lib
index 3ede696..89e0784 100644
--- a/lib/win64/openvr_api.lib
+++ b/lib/win64/openvr_api.lib
Binary files differ
diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt
new file mode 100644
index 0000000..3f50eb4
--- /dev/null
+++ b/samples/CMakeLists.txt
@@ -0,0 +1,213 @@
+cmake_minimum_required(VERSION 3.0.2)
+
+project(openvr_samples)
+
+# -----------------------------------------------------------------------------
+## SYSTEM PROPERTIES ##
+
+# If not set, determines the running platform architecture.
+if(NOT PLATFORM)
+ if(CMAKE_SIZEOF_VOID_P MATCHES 8)
+ set(PLATFORM 64)
+ else()
+ set(PLATFORM 32)
+ endif()
+endif()
+message(STATUS "Compilation set for ${PLATFORM}bits architectures.")
+
+if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
+ add_definitions(-DLINUX)
+ set(ARCH_TARGET linux64)
+
+ if(${PLATFORM} MATCHES 32)
+ message(WARNING "OpenVR x86 binaries not provided on GNU/Linux.")
+ endif()
+elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
+ add_definitions(-DOSX)
+ set(ARCH_TARGET osx32)
+
+ if(${PLATFORM} MATCHES 64)
+ message(WARNING "OpenVR x64 binaries not provided on OSX.")
+ endif()
+elseif(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
+ add_definitions(-D_WIN32)
+ set(ARCH_TARGET win${PLATFORM})
+
+ # Binaries path for thirdparties are not generics so we try to guess their suffixes.
+ set(WINDOWS_PATH_SUFFIXES win${PLATFORM} Win${PLATFORM} x${PLATFORM})
+
+ if(${PLATFORM} MATCHES 64)
+ message(WARNING "SDL x64 runtime binaries not provided on Windows.")
+ endif()
+endif()
+
+# -----------------------------------------------------------------------------
+## PATHS ##
+
+set(THIRDPARTY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/thirdparty)
+set(SHARED_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/shared)
+
+# Check that the steamVR SDK is installed
+# (needed to prevent a segfault in OpenVR).
+if(CMAKE_HOST_UNIX)
+ find_file(OPENVRPATHS openvrpaths.vrpath PATHS $ENV{HOME}/.config/openvr)
+ if(${OPENVRPATHS} MATCHES OPENVRPATHS-NOTFOUND)
+ message(FATAL_ERROR "${OPENVRPATHS} Please install SteamVR SDK to continue..")
+ endif()
+endif()
+
+# Default output directory.
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/bin/${ARCH_TARGET})
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/bin/${ARCH_TARGET})
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/bin/${ARCH_TARGET})
+
+# Force output directory destination, especially for MSVC (@so7747857).
+function(setTargetOutputDirectory target)
+ foreach(type RUNTIME LIBRARY ARCHIVE)
+ set_target_properties(${target} PROPERTIES
+ ${type}_OUTPUT_DIRECTORY ${CMAKE_${type}_OUTPUT_DIRECTORY}
+ ${type}_OUTPUT_DIRECTORY_DEBUG ${CMAKE_${type}_OUTPUT_DIRECTORY}
+ ${type}_OUTPUT_DIRECTORY_RELEASE ${CMAKE_${type}_OUTPUT_DIRECTORY}
+ )
+ endforeach()
+endfunction()
+
+# -----------------------------------------------------------------------------
+## COMPILER DETECTION ##
+
+if( (${CMAKE_CXX_COMPILER_ID} MATCHES "GNU")
+ OR (${CMAKE_CXX_COMPILER_ID} MATCHES "Clang"))
+ # Better to use the prebuilt GNU preprocessor define __GNUC__,
+ # kept for legacy reason with the sample code.
+ add_definitions(-DGNUC)
+
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -include ${SHARED_SRC_DIR}/compat.h")
+ set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -Wextra -pedantic -g")
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2")
+
+ # Handles x86 compilation support on x64 arch.
+ if(${PLATFORM} MATCHES 32)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32")
+ set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -m32")
+ endif()
+elseif(${CMAKE_CXX_COMPILER_ID} MATCHES "MSVC")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Za")
+ set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /w2 /DEBUG")
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MP /INCREMENTAL:NO")
+else()
+ message(FATAL_ERROR "Unsupported compiler.")
+endif()
+
+# -----------------------------------------------------------------------------
+## LIBRARIES ##
+
+## OpenGL / GLU
+find_package(OpenGL REQUIRED)
+
+## GLEW 1.11
+if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
+ # On GNU/Linux, glew can be found on the package manager.
+ find_package(GLEW 1.11 REQUIRED)
+else()
+ # Otherwise, use the shipped binaries.
+ find_library(GLEW_LIBRARIES
+ NAMES
+ GLEW
+ glew32
+ PATHS
+ ${THIRDPARTY_DIR}/glew/glew-1.11.0/lib/Release
+ PATH_SUFFIXES
+ osx32
+ ${WINDOWS_PATH_SUFFIXES}
+ )
+ set(GLEW_INCLUDE_DIR ${THIRDPARTY_DIR}/glew/glew-1.11.0/include)
+endif()
+
+## SDL 2
+foreach(lib SDL2 SDL2main)
+ find_library(${lib}_LIBRARY
+ NAMES
+ ${lib}
+ PATHS
+ ${THIRDPARTY_DIR}/sdl2-2.0.3/bin
+ PATH_SUFFIXES
+ linux32
+ osx32
+ ${WINDOWS_PATH_SUFFIXES}
+ )
+ list(APPEND SDL2_LIBRARIES ${${lib}_LIBRARY})
+endforeach()
+set(SDL2_INCLUDE_DIR ${THIRDPARTY_DIR}/sdl2-2.0.3/include)
+
+## Qt 5
+## Important :
+## Remember to set CMAKE_PREFIX_PATH to Qt5 cmake modules path for your targeted platform
+## or set them here manually (not portable).
+# if(CMAKE_HOST_UNIX)
+# list(APPEND CMAKE_PREFIX_PATH "/opt/Qt/5.6/gcc_64/lib/cmake")
+# else()
+# if(${PLATFORM} MATCHES 64)
+# set(suffix "_64")
+# endif
+# list(APPEND CMAKE_PREFIX_PATH "C:/Qt/5.6/msvc2013${suffix}/lib/cmake")
+# endif()
+
+# Set CMake to run moc automatically has needed.
+set(CMAKE_AUTOMOC ON)
+# Set CMake to handle *.ui generation to avoid using QT5_WRAP_UI() macro.
+set(CMAKE_AUTOUIC ON)
+# Add the build dir to include paths to find UI's headers.
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+
+# Find Qt5 libraries.
+foreach(module Core Gui Widgets)
+ find_package(Qt5 REQUIRED COMPONENTS ${module})
+ list(APPEND QT_INCLUDE_DIRS "${Qt5${module}_INCLUDE_DIRS}")
+ list(APPEND QT_LIBRARIES "${Qt5${module}_LIBRARIES}")
+ list(APPEND QT_FLAGS "${Qt5${module}_EXECUTABLE_COMPILE_FLAGS}")
+ list(APPEND QT_DEFINITIONS "${Qt5${module}_DEFINITIONS}")
+endforeach()
+
+## OpenVR API path
+find_library(OPENVR_LIBRARIES
+ NAMES
+ openvr_api
+ PATHS
+ ${CMAKE_CURRENT_SOURCE_DIR}/../bin
+ ${CMAKE_CURRENT_SOURCE_DIR}/../lib
+ PATH_SUFFIXES
+ linux64
+ osx32
+ ${WINDOWS_PATH_SUFFIXES}
+ NO_DEFAULT_PATH
+ NO_CMAKE_FIND_ROOT_PATH
+)
+set(OPENVR_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../headers)
+
+
+# -----------------------------------------------------------------------------
+## SHARED SOURCES ##
+
+file(GLOB SHARED_SRC_FILES
+ ${SHARED_SRC_DIR}/*.cpp
+ ${SHARED_SRC_DIR}/*.h
+)
+
+include_directories(
+ .
+ ${OPENGL_INCLUDE_DIR}
+ ${GLEW_INCLUDE_DIR}
+ ${SDL2_INCLUDE_DIR}
+ ${QT_INCLUDE_DIRS}
+ ${OPENVR_INCLUDE_DIR}
+)
+
+# -----------------------------------------------------------------------------
+## SUBDIRECTORIES ##
+
+add_subdirectory(driver_sample)
+add_subdirectory(hellovr_opengl)
+add_subdirectory(helloworldoverlay)
+add_subdirectory(tracked_camera_openvr_sample)
+
+# ----------------------------------------------------------------------------- \ No newline at end of file
diff --git a/samples/README.md b/samples/README.md
new file mode 100644
index 0000000..da63c05
--- /dev/null
+++ b/samples/README.md
@@ -0,0 +1,70 @@
+# OpenVR Samples: CMake build guide.
+
+## Support
+
+| Configuration | 32 | 64 |
+| ----------------------- |:---------:|----------:|
+| GNU/Linux (gcc 4.8+) | OK | OK |
+| Windows (msvc 12) | OK | OK |
+| OSX (clang) | ~ | ~ |
+
+
+## Dependencies
+
+* Qt 5.x
+* GLEW 1.11+
+* SDL2
+* OpenVR
+
+The only general external dependency is Qt5.<br/>
+On GNU/Linux, you will need GLEW 1.11 (available on most package manager).<br/>
+On Windows x64, you will need the SDL2 runtime library.
+
+## Build
+
+**Important:**<br/>
+*you might need to specify Qt5 cmake module path manually when generating the cache for the first time using the __CMAKE_PREFIX_PATH__ macro (see examples below).*
+
+We will use the command-line on Unix and [Git Bash](https://git-for-windows.github.io/) on Windows.
+
+First, move from the repository root to the samples directory to create a build directory:
+```
+cd samples
+mkdir build; cd build
+```
+
+Then, depending on your system:
+
+### Unix
+
+Generate the CMake cache using Makefile:
+```
+cmake .. -G Makefile -DCMAKE_PREFIX_PATH=/opt/Qt/5.6/gcc_64/lib/cmake -DCMAKE_BUILD_TYPE=Release
+```
+
+To build type:
+```
+make -j4
+```
+
+
+### Windows
+
+Generate the CMake cache using MSVC 12 for x64:
+```
+cmake .. -G "Visual Studio 12 2013 Win64" -DCMAKE_PREFIX_PATH=C:/Qt/5.6/msvc2013_64/lib/cmake
+```
+
+Alternatively, you can force the compilation on x86 architectures by using the **PLATFORM** property (*be sure to use the right generator and Qt binaries*):
+```
+cmake .. -G "Visual Studio 12 2013" -DCMAKE_PREFIX_PATH=C:/Qt/5.6/msvc2013/lib/cmake -DPLATFORM=32
+```
+
+To build, simply type:
+```
+cmake --build . --target all --config Release
+```
+
+*Note : using CMake, the build configuration type (ie. Debug, Release) is set at Build Time with MSVC and at Cache Generation Time with Makefile.*
+
+---
diff --git a/samples/bin/linux64/libopenvr_api.so b/samples/bin/linux64/libopenvr_api.so
index 692a87c..a7d57c6 100644
--- a/samples/bin/linux64/libopenvr_api.so
+++ b/samples/bin/linux64/libopenvr_api.so
Binary files differ
diff --git a/samples/bin/osx32/libopenvr_api.dylib b/samples/bin/osx32/libopenvr_api.dylib
index 81ff559..2ac282b 100644
--- a/samples/bin/osx32/libopenvr_api.dylib
+++ b/samples/bin/osx32/libopenvr_api.dylib
Binary files differ
diff --git a/samples/bin/win32/openvr_api.dll b/samples/bin/win32/openvr_api.dll
index 2dd3fbe..0b0cc0e 100644
--- a/samples/bin/win32/openvr_api.dll
+++ b/samples/bin/win32/openvr_api.dll
Binary files differ
diff --git a/samples/bin/win64/openvr_api.dll b/samples/bin/win64/openvr_api.dll
index 9ae4922..8b33ebb 100644
--- a/samples/bin/win64/openvr_api.dll
+++ b/samples/bin/win64/openvr_api.dll
Binary files differ
diff --git a/samples/driver_sample/CMakeLists.txt b/samples/driver_sample/CMakeLists.txt
new file mode 100644
index 0000000..1b1908c
--- /dev/null
+++ b/samples/driver_sample/CMakeLists.txt
@@ -0,0 +1,16 @@
+set(TARGET_NAME driver_sample)
+
+add_library(${TARGET_NAME} SHARED
+ driverlog.cpp
+ driverlog.h
+ driver_sample.cpp
+)
+
+add_definitions(-DDRIVER_SAMPLE_EXPORTS)
+
+target_link_libraries(${TARGET_NAME}
+ ${OPENVR_LIBRARIES}
+ ${CMAKE_DL_LIBS}
+)
+
+setTargetOutputDirectory(${TARGET_NAME})
diff --git a/samples/driver_sample/driver_sample.cpp b/samples/driver_sample/driver_sample.cpp
index b666d4d..1c7290c 100644
--- a/samples/driver_sample/driver_sample.cpp
+++ b/samples/driver_sample/driver_sample.cpp
@@ -17,7 +17,7 @@ using namespace vr;
#if defined(_WIN32)
#define HMD_DLL_EXPORT extern "C" __declspec( dllexport )
#define HMD_DLL_IMPORT extern "C" __declspec( dllimport )
-#elif defined(GNUC) || defined(COMPILER_GCC)
+#elif defined(__GNUC__) || defined(COMPILER_GCC) || defined(__APPLE__)
#define HMD_DLL_EXPORT extern "C" __attribute__((visibility("default")))
#define HMD_DLL_IMPORT extern "C"
#else
@@ -84,7 +84,7 @@ public:
virtual void Cleanup() ;
virtual bool BIsHmdPresent( const char *pchUserDriverConfigDir ) ;
virtual EVRInitError SetDisplayId( const char *pchDisplayId ) { return VRInitError_None; } // Null doesn't care
- virtual HiddenAreaMesh_t GetHiddenAreaMesh( EVREye eEye ) ;
+ virtual HiddenAreaMesh_t GetHiddenAreaMesh( EVREye eEye, EHiddenAreaMeshType type );
virtual uint32_t GetMCImage( uint32_t *pImgWidth, uint32_t *pImgHeight, uint32_t *pChannels, void *pDataBuffer, uint32_t unBufferLen ) { return 0; }
void WatchdogWakeUp();
@@ -133,11 +133,11 @@ EVRInitError CClientDriver_Sample::Init( vr::EClientDriverMode eDriverMode, vr::
{
if ( m_pClientDriverHost )
{
- IVRSettings *pSettings = m_pClientDriverHost->GetSettings( vr::IVRSettings_Version );
+ IVRSettings *pSettings = (IVRSettings *) m_pClientDriverHost->GetGenericInterface( IVRSettings_Version );
if ( !m_bEnableNullDriver && pSettings )
{
- m_bEnableNullDriver = pSettings->GetBool( k_pch_Sample_Section, k_pch_Sample_EnableSampleDriver_Bool, false );
+ m_bEnableNullDriver = pSettings->GetBool( k_pch_Sample_Section, k_pch_Sample_EnableSampleDriver_Bool);
}
}
m_bInit = true;
@@ -199,7 +199,7 @@ bool CClientDriver_Sample::BIsHmdPresent( const char *pchUserDriverConfigDir )
// ------------------------------------------------------------------------------------------
// Purpose: Return a mesh that contains the hidden area for the current HMD
// ------------------------------------------------------------------------------------------
-HiddenAreaMesh_t CClientDriver_Sample::GetHiddenAreaMesh( EVREye eEye )
+HiddenAreaMesh_t CClientDriver_Sample::GetHiddenAreaMesh( EVREye eEye, EHiddenAreaMeshType type )
{
// Null doesn't do visible area meshes
vr::HiddenAreaMesh_t mesh;
@@ -224,23 +224,23 @@ public:
if ( pSettings )
{
DriverLog( "Using settings values\n" );
- m_flIPD = pSettings->GetFloat( k_pch_SteamVR_Section, k_pch_SteamVR_IPD_Float, 0.063f );
+ m_flIPD = pSettings->GetFloat( k_pch_SteamVR_Section, k_pch_SteamVR_IPD_Float );
char buf[1024];
- pSettings->GetString( k_pch_Sample_Section, k_pch_Sample_SerialNumber_String, buf, sizeof(buf), "SAMPLE1234" );
+ pSettings->GetString( k_pch_Sample_Section, k_pch_Sample_SerialNumber_String, buf, sizeof(buf));
m_sSerialNumber = buf;
- pSettings->GetString( k_pch_Sample_Section, k_pch_Sample_ModelNumber_String, buf, sizeof(buf), "ED209" );
+ pSettings->GetString( k_pch_Sample_Section, k_pch_Sample_ModelNumber_String, buf, sizeof(buf));
m_sSerialNumber = buf;
- m_nWindowX = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_WindowX_Int32, 0 );
- m_nWindowY = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_WindowY_Int32, 0 );
- m_nWindowWidth = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_WindowWidth_Int32, 1920 );
- m_nWindowHeight = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_WindowHeight_Int32, 1080 );
- m_nRenderWidth = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_RenderWidth_Int32, 1344 );
- m_nRenderHeight = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_RenderHeight_Int32, 1512 );
- m_flSecondsFromVsyncToPhotons = pSettings->GetFloat( k_pch_Sample_Section, k_pch_Sample_SecondsFromVsyncToPhotons_Float, 0.0 );
- m_flDisplayFrequency = pSettings->GetFloat( k_pch_Sample_Section, k_pch_Sample_DisplayFrequency_Float, 0.0 );
+ m_nWindowX = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_WindowX_Int32);
+ m_nWindowY = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_WindowY_Int32);
+ m_nWindowWidth = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_WindowWidth_Int32);
+ m_nWindowHeight = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_WindowHeight_Int32);
+ m_nRenderWidth = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_RenderWidth_Int32);
+ m_nRenderHeight = pSettings->GetInt32( k_pch_Sample_Section, k_pch_Sample_RenderHeight_Int32);
+ m_flSecondsFromVsyncToPhotons = pSettings->GetFloat( k_pch_Sample_Section, k_pch_Sample_SecondsFromVsyncToPhotons_Float);
+ m_flDisplayFrequency = pSettings->GetFloat( k_pch_Sample_Section, k_pch_Sample_DisplayFrequency_Float);
}
else
{
@@ -287,6 +287,10 @@ public:
m_unObjectId = vr::k_unTrackedDeviceIndexInvalid;
}
+ virtual void EnterStandby()
+ {
+ }
+
void *GetComponent( const char *pchComponentNameAndVersion )
{
if ( !_stricmp( pchComponentNameAndVersion, vr::IVRDisplayComponent_Version ) )
@@ -585,7 +589,7 @@ EVRInitError CServerDriver_Sample::Init( IDriverLog *pDriverLog, vr::IServerDriv
IVRSettings *pSettings = pDriverHost ? pDriverHost->GetSettings( vr::IVRSettings_Version ) : NULL;
- m_bEnableNullDriver = pSettings && pSettings->GetBool( k_pch_Sample_Section, k_pch_Sample_EnableSampleDriver_Bool, false );
+ m_bEnableNullDriver = pSettings && pSettings->GetBool( k_pch_Sample_Section, k_pch_Sample_EnableSampleDriver_Bool );
if ( !m_bEnableNullDriver )
return VRInitError_Init_HmdNotFound;
diff --git a/samples/hellovr_opengl/CMakeLists.txt b/samples/hellovr_opengl/CMakeLists.txt
new file mode 100644
index 0000000..253030e
--- /dev/null
+++ b/samples/hellovr_opengl/CMakeLists.txt
@@ -0,0 +1,16 @@
+set(TARGET_NAME hellovr_opengl)
+
+add_executable(${TARGET_NAME}
+ ${SHARED_SRC_FILES}
+ hellovr_opengl_main.cpp
+)
+
+target_link_libraries(${TARGET_NAME}
+ ${OPENGL_LIBRARIES}
+ ${GLEW_LIBRARIES}
+ ${SDL2_LIBRARIES}
+ ${OPENVR_LIBRARIES}
+ ${CMAKE_DL_LIBS}
+)
+
+setTargetOutputDirectory(${TARGET_NAME})
diff --git a/samples/hellovr_opengl/hellovr_opengl_main.cpp b/samples/hellovr_opengl/hellovr_opengl_main.cpp
index 55aef13..64d1d47 100644
--- a/samples/hellovr_opengl/hellovr_opengl_main.cpp
+++ b/samples/hellovr_opengl/hellovr_opengl_main.cpp
@@ -3,7 +3,7 @@
#include <SDL.h>
#include <GL/glew.h>
#include <SDL_opengl.h>
-#include <gl/glu.h>
+#include <GL/glu.h>
#include <stdio.h>
#include <string>
#include <cstdlib>
@@ -18,6 +18,10 @@
#include "unistd.h"
#endif
+#ifndef _WIN32
+#define APIENTRY
+#endif
+
void ThreadSleep( unsigned long nMilliseconds )
{
#if defined(_WIN32)
@@ -77,14 +81,14 @@ public:
void AddCubeToScene( Matrix4 mat, std::vector<float> &vertdata );
void AddCubeVertex( float fl0, float fl1, float fl2, float fl3, float fl4, std::vector<float> &vertdata );
- void DrawControllers();
+ void RenderControllerAxes();
bool SetupStereoRenderTargets();
- void SetupDistortion();
+ void SetupCompanionWindow();
void SetupCameras();
void RenderStereoTargets();
- void RenderDistortion();
+ void RenderCompanionWindow();
void RenderScene( vr::Hmd_Eye nEye );
Matrix4 GetHMDMatrixProjectionEye( vr::Hmd_Eye nEye );
@@ -116,9 +120,9 @@ private:
bool m_rbShowTrackedDevice[ vr::k_unMaxTrackedDeviceCount ];
private: // SDL bookkeeping
- SDL_Window *m_pWindow;
- uint32_t m_nWindowWidth;
- uint32_t m_nWindowHeight;
+ SDL_Window *m_pCompanionWindow;
+ uint32_t m_nCompanionWindowWidth;
+ uint32_t m_nCompanionWindowHeight;
SDL_GLContext m_pContext;
@@ -149,10 +153,10 @@ private: // OpenGL bookkeeping
GLuint m_glSceneVertBuffer;
GLuint m_unSceneVAO;
- GLuint m_unLensVAO;
- GLuint m_glIDVertBuffer;
- GLuint m_glIDIndexBuffer;
- unsigned int m_uiIndexSize;
+ GLuint m_unCompanionWindowVAO;
+ GLuint m_glCompanionWindowIDVertBuffer;
+ GLuint m_glCompanionWindowIDIndexBuffer;
+ unsigned int m_uiCompanionWindowIndexSize;
GLuint m_glControllerVertBuffer;
GLuint m_unControllerVAO;
@@ -172,16 +176,16 @@ private: // OpenGL bookkeeping
Vector2 texCoord;
};
- struct VertexDataLens
+ struct VertexDataWindow
{
Vector2 position;
- Vector2 texCoordRed;
- Vector2 texCoordGreen;
- Vector2 texCoordBlue;
+ Vector2 texCoord;
+
+ VertexDataWindow( const Vector2 & pos, const Vector2 tex ) : position(pos), texCoord(tex) { }
};
GLuint m_unSceneProgramID;
- GLuint m_unLensProgramID;
+ GLuint m_unCompanionWindowProgramID;
GLuint m_unControllerTransformProgramID;
GLuint m_unRenderModelProgramID;
@@ -210,7 +214,8 @@ private: // OpenGL bookkeeping
};
//-----------------------------------------------------------------------------
-// Purpose:
+// Purpose: Outputs a set of optional arguments to debugging output, using
+// the printf format setting specified in fmt*.
//-----------------------------------------------------------------------------
void dprintf( const char *fmt, ... )
{
@@ -231,12 +236,12 @@ void dprintf( const char *fmt, ... )
// Purpose: Constructor
//-----------------------------------------------------------------------------
CMainApplication::CMainApplication( int argc, char *argv[] )
- : m_pWindow(NULL)
+ : m_pCompanionWindow(NULL)
, m_pContext(NULL)
- , m_nWindowWidth( 1280 )
- , m_nWindowHeight( 720 )
+ , m_nCompanionWindowWidth( 640 )
+ , m_nCompanionWindowHeight( 320 )
, m_unSceneProgramID( 0 )
- , m_unLensProgramID( 0 )
+ , m_unCompanionWindowProgramID( 0 )
, m_unControllerTransformProgramID( 0 )
, m_unRenderModelProgramID( 0 )
, m_pHMD( NULL )
@@ -248,7 +253,6 @@ CMainApplication::CMainApplication( int argc, char *argv[] )
, m_bGlFinishHack( true )
, m_glControllerVertBuffer( 0 )
, m_unControllerVAO( 0 )
- , m_unLensVAO( 0 )
, m_unSceneVAO( 0 )
, m_nSceneMatrixLocation( -1 )
, m_nControllerMatrixLocation( -1 )
@@ -362,8 +366,6 @@ bool CMainApplication::BInit()
int nWindowPosX = 700;
int nWindowPosY = 100;
- m_nWindowWidth = 1280;
- m_nWindowHeight = 720;
Uint32 unWindowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 4 );
@@ -376,14 +378,14 @@ bool CMainApplication::BInit()
if( m_bDebugOpenGL )
SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG );
- m_pWindow = SDL_CreateWindow( "hellovr_sdl", nWindowPosX, nWindowPosY, m_nWindowWidth, m_nWindowHeight, unWindowFlags );
- if (m_pWindow == NULL)
+ m_pCompanionWindow = SDL_CreateWindow( "hellovr", nWindowPosX, nWindowPosY, m_nCompanionWindowWidth, m_nCompanionWindowHeight, unWindowFlags );
+ if (m_pCompanionWindow == NULL)
{
printf( "%s - Window could not be created! SDL Error: %s\n", __FUNCTION__, SDL_GetError() );
return false;
}
- m_pContext = SDL_GL_CreateContext(m_pWindow);
+ m_pContext = SDL_GL_CreateContext(m_pCompanionWindow);
if (m_pContext == NULL)
{
printf( "%s - OpenGL context could not be created! SDL Error: %s\n", __FUNCTION__, SDL_GetError() );
@@ -412,8 +414,8 @@ bool CMainApplication::BInit()
m_strDriver = GetTrackedDeviceString( m_pHMD, vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_TrackingSystemName_String );
m_strDisplay = GetTrackedDeviceString( m_pHMD, vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_SerialNumber_String );
- std::string strWindowTitle = "hellovr_sdl - " + m_strDriver + " " + m_strDisplay;
- SDL_SetWindowTitle( m_pWindow, strWindowTitle.c_str() );
+ std::string strWindowTitle = "hellovr - " + m_strDriver + " " + m_strDisplay;
+ SDL_SetWindowTitle( m_pCompanionWindow, strWindowTitle.c_str() );
// cube array
m_iSceneVolumeWidth = m_iSceneVolumeInit;
@@ -449,7 +451,9 @@ bool CMainApplication::BInit()
//-----------------------------------------------------------------------------
-// Purpose:
+// Purpose: Outputs the string in message to debugging output.
+// All other parameters are ignored.
+// Does not return any meaningful value or reference.
//-----------------------------------------------------------------------------
void APIENTRY DebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const char* message, const void* userParam)
{
@@ -458,7 +462,10 @@ void APIENTRY DebugCallback(GLenum source, GLenum type, GLuint id, GLenum severi
//-----------------------------------------------------------------------------
-// Purpose:
+// Purpose: Initialize OpenGL. Returns true if OpenGL has been successfully
+// initialized, false if shaders could not be created.
+// If failure occurred in a module other than shaders, the function
+// may return true or throw an error.
//-----------------------------------------------------------------------------
bool CMainApplication::BInitGL()
{
@@ -476,8 +483,7 @@ bool CMainApplication::BInitGL()
SetupScene();
SetupCameras();
SetupStereoRenderTargets();
- SetupDistortion();
-
+ SetupCompanionWindow();
SetupRenderModels();
return true;
@@ -485,7 +491,8 @@ bool CMainApplication::BInitGL()
//-----------------------------------------------------------------------------
-// Purpose:
+// Purpose: Initialize Compositor. Returns true if the compositor was
+// successfully initialized, false otherwise.
//-----------------------------------------------------------------------------
bool CMainApplication::BInitCompositor()
{
@@ -523,8 +530,6 @@ void CMainApplication::Shutdown()
glDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_FALSE );
glDebugMessageCallback(nullptr, nullptr);
glDeleteBuffers(1, &m_glSceneVertBuffer);
- glDeleteBuffers(1, &m_glIDVertBuffer);
- glDeleteBuffers(1, &m_glIDIndexBuffer);
if ( m_unSceneProgramID )
{
@@ -538,9 +543,9 @@ void CMainApplication::Shutdown()
{
glDeleteProgram( m_unRenderModelProgramID );
}
- if ( m_unLensProgramID )
+ if ( m_unCompanionWindowProgramID )
{
- glDeleteProgram( m_unLensProgramID );
+ glDeleteProgram( m_unCompanionWindowProgramID );
}
glDeleteRenderbuffers( 1, &leftEyeDesc.m_nDepthBufferId );
@@ -555,9 +560,9 @@ void CMainApplication::Shutdown()
glDeleteTextures( 1, &rightEyeDesc.m_nResolveTextureId );
glDeleteFramebuffers( 1, &rightEyeDesc.m_nResolveFramebufferId );
- if( m_unLensVAO != 0 )
+ if( m_unCompanionWindowVAO != 0 )
{
- glDeleteVertexArrays( 1, &m_unLensVAO );
+ glDeleteVertexArrays( 1, &m_unCompanionWindowVAO );
}
if( m_unSceneVAO != 0 )
{
@@ -569,10 +574,10 @@ void CMainApplication::Shutdown()
}
}
- if( m_pWindow )
+ if( m_pCompanionWindow )
{
- SDL_DestroyWindow(m_pWindow);
- m_pWindow = NULL;
+ SDL_DestroyWindow(m_pCompanionWindow);
+ m_pCompanionWindow = NULL;
}
SDL_Quit();
@@ -617,7 +622,7 @@ bool CMainApplication::HandleInput()
for( vr::TrackedDeviceIndex_t unDevice = 0; unDevice < vr::k_unMaxTrackedDeviceCount; unDevice++ )
{
vr::VRControllerState_t state;
- if( m_pHMD->GetControllerState( unDevice, &state ) )
+ if( m_pHMD->GetControllerState( unDevice, &state, sizeof(state) ) )
{
m_rbShowTrackedDevice[ unDevice ] = state.ulButtonPressed == 0;
}
@@ -682,9 +687,9 @@ void CMainApplication::RenderFrame()
// for now as fast as possible
if ( m_pHMD )
{
- DrawControllers();
+ RenderControllerAxes();
RenderStereoTargets();
- RenderDistortion();
+ RenderCompanionWindow();
vr::Texture_t leftEyeTexture = {(void*)leftEyeDesc.m_nResolveTextureId, vr::API_OpenGL, vr::ColorSpace_Gamma };
vr::VRCompositor()->Submit(vr::Eye_Left, &leftEyeTexture );
@@ -703,7 +708,7 @@ void CMainApplication::RenderFrame()
// SwapWindow
{
- SDL_GL_SwapWindow( m_pWindow );
+ SDL_GL_SwapWindow( m_pCompanionWindow );
}
// Clear
@@ -896,55 +901,35 @@ bool CMainApplication::CreateAllShaders()
return false;
}
- m_unLensProgramID = CompileGLShader(
- "Distortion",
+ m_unCompanionWindowProgramID = CompileGLShader(
+ "CompanionWindow",
// vertex shader
"#version 410 core\n"
"layout(location = 0) in vec4 position;\n"
- "layout(location = 1) in vec2 v2UVredIn;\n"
- "layout(location = 2) in vec2 v2UVGreenIn;\n"
- "layout(location = 3) in vec2 v2UVblueIn;\n"
- "noperspective out vec2 v2UVred;\n"
- "noperspective out vec2 v2UVgreen;\n"
- "noperspective out vec2 v2UVblue;\n"
+ "layout(location = 1) in vec2 v2UVIn;\n"
+ "noperspective out vec2 v2UV;\n"
"void main()\n"
"{\n"
- " v2UVred = v2UVredIn;\n"
- " v2UVgreen = v2UVGreenIn;\n"
- " v2UVblue = v2UVblueIn;\n"
+ " v2UV = v2UVIn;\n"
" gl_Position = position;\n"
"}\n",
// fragment shader
"#version 410 core\n"
"uniform sampler2D mytexture;\n"
-
- "noperspective in vec2 v2UVred;\n"
- "noperspective in vec2 v2UVgreen;\n"
- "noperspective in vec2 v2UVblue;\n"
-
+ "noperspective in vec2 v2UV;\n"
"out vec4 outputColor;\n"
-
"void main()\n"
"{\n"
- " float fBoundsCheck = ( (dot( vec2( lessThan( v2UVgreen.xy, vec2(0.05, 0.05)) ), vec2(1.0, 1.0))+dot( vec2( greaterThan( v2UVgreen.xy, vec2( 0.95, 0.95)) ), vec2(1.0, 1.0))) );\n"
- " if( fBoundsCheck > 1.0 )\n"
- " { outputColor = vec4( 0, 0, 0, 1.0 ); }\n"
- " else\n"
- " {\n"
- " float red = texture(mytexture, v2UVred).x;\n"
- " float green = texture(mytexture, v2UVgreen).y;\n"
- " float blue = texture(mytexture, v2UVblue).z;\n"
- " outputColor = vec4( red, green, blue, 1.0 ); }\n"
+ " outputColor = texture(mytexture, v2UV);\n"
"}\n"
);
-
return m_unSceneProgramID != 0
&& m_unControllerTransformProgramID != 0
&& m_unRenderModelProgramID != 0
- && m_unLensProgramID != 0;
+ && m_unCompanionWindowProgramID != 0;
}
@@ -1028,8 +1013,6 @@ void CMainApplication::SetupScene()
glBindBuffer( GL_ARRAY_BUFFER, m_glSceneVertBuffer );
glBufferData( GL_ARRAY_BUFFER, sizeof(float) * vertdataarray.size(), &vertdataarray[0], GL_STATIC_DRAW);
- glBindBuffer( GL_ARRAY_BUFFER, m_glSceneVertBuffer );
-
GLsizei stride = sizeof(VertexDataScene);
uintptr_t offset = 0;
@@ -1124,7 +1107,7 @@ void CMainApplication::AddCubeToScene( Matrix4 mat, std::vector<float> &vertdata
//-----------------------------------------------------------------------------
// Purpose: Draw all of the controllers as X/Y/Z lines
//-----------------------------------------------------------------------------
-void CMainApplication::DrawControllers()
+void CMainApplication::RenderControllerAxes()
{
// don't draw controllers if somebody else has input focus
if( m_pHMD->IsInputFocusCapturedByAnotherProcess() )
@@ -1236,7 +1219,8 @@ void CMainApplication::SetupCameras()
//-----------------------------------------------------------------------------
-// Purpose:
+// Purpose: Creates a frame buffer. Returns true if the buffer was set up.
+// Returns false if the setup failed.
//-----------------------------------------------------------------------------
bool CMainApplication::CreateFrameBuffer( int nWidth, int nHeight, FramebufferDesc &framebufferDesc )
{
@@ -1296,131 +1280,49 @@ bool CMainApplication::SetupStereoRenderTargets()
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
-void CMainApplication::SetupDistortion()
+void CMainApplication::SetupCompanionWindow()
{
if ( !m_pHMD )
return;
- GLushort m_iLensGridSegmentCountH = 43;
- GLushort m_iLensGridSegmentCountV = 43;
-
- float w = (float)( 1.0/float(m_iLensGridSegmentCountH-1));
- float h = (float)( 1.0/float(m_iLensGridSegmentCountV-1));
+ std::vector<VertexDataWindow> vVerts;
- float u, v = 0;
+ // left eye verts
+ vVerts.push_back( VertexDataWindow( Vector2(-1, -1), Vector2(0, 1)) );
+ vVerts.push_back( VertexDataWindow( Vector2(0, -1), Vector2(1, 1)) );
+ vVerts.push_back( VertexDataWindow( Vector2(-1, 1), Vector2(0, 0)) );
+ vVerts.push_back( VertexDataWindow( Vector2(0, 1), Vector2(1, 0)) );
- std::vector<VertexDataLens> vVerts(0);
- VertexDataLens vert;
-
- //left eye distortion verts
- float Xoffset = -1;
- for( int y=0; y<m_iLensGridSegmentCountV; y++ )
- {
- for( int x=0; x<m_iLensGridSegmentCountH; x++ )
- {
- u = x*w; v = 1-y*h;
- vert.position = Vector2( Xoffset+u, -1+2*y*h );
+ // right eye verts
+ vVerts.push_back( VertexDataWindow( Vector2(0, -1), Vector2(0, 1)) );
+ vVerts.push_back( VertexDataWindow( Vector2(1, -1), Vector2(1, 1)) );
+ vVerts.push_back( VertexDataWindow( Vector2(0, 1), Vector2(0, 0)) );
+ vVerts.push_back( VertexDataWindow( Vector2(1, 1), Vector2(1, 0)) );
- vr::DistortionCoordinates_t dc0 = m_pHMD->ComputeDistortion(vr::Eye_Left, u, v);
+ GLushort vIndices[] = { 0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6};
+ m_uiCompanionWindowIndexSize = _countof(vIndices);
- vert.texCoordRed = Vector2(dc0.rfRed[0], 1 - dc0.rfRed[1]);
- vert.texCoordGreen = Vector2(dc0.rfGreen[0], 1 - dc0.rfGreen[1]);
- vert.texCoordBlue = Vector2(dc0.rfBlue[0], 1 - dc0.rfBlue[1]);
-
- vVerts.push_back( vert );
- }
- }
-
- //right eye distortion verts
- Xoffset = 0;
- for( int y=0; y<m_iLensGridSegmentCountV; y++ )
- {
- for( int x=0; x<m_iLensGridSegmentCountH; x++ )
- {
- u = x*w; v = 1-y*h;
- vert.position = Vector2( Xoffset+u, -1+2*y*h );
+ glGenVertexArrays( 1, &m_unCompanionWindowVAO );
+ glBindVertexArray( m_unCompanionWindowVAO );
- vr::DistortionCoordinates_t dc0 = m_pHMD->ComputeDistortion( vr::Eye_Right, u, v );
+ glGenBuffers( 1, &m_glCompanionWindowIDVertBuffer );
+ glBindBuffer( GL_ARRAY_BUFFER, m_glCompanionWindowIDVertBuffer );
+ glBufferData( GL_ARRAY_BUFFER, vVerts.size()*sizeof(VertexDataWindow), &vVerts[0], GL_STATIC_DRAW );
- vert.texCoordRed = Vector2(dc0.rfRed[0], 1 - dc0.rfRed[1]);
- vert.texCoordGreen = Vector2(dc0.rfGreen[0], 1 - dc0.rfGreen[1]);
- vert.texCoordBlue = Vector2(dc0.rfBlue[0], 1 - dc0.rfBlue[1]);
-
- vVerts.push_back( vert );
- }
- }
-
- std::vector<GLushort> vIndices;
- GLushort a,b,c,d;
-
- GLushort offset = 0;
- for( GLushort y=0; y<m_iLensGridSegmentCountV-1; y++ )
- {
- for( GLushort x=0; x<m_iLensGridSegmentCountH-1; x++ )
- {
- a = m_iLensGridSegmentCountH*y+x +offset;
- b = m_iLensGridSegmentCountH*y+x+1 +offset;
- c = (y+1)*m_iLensGridSegmentCountH+x+1 +offset;
- d = (y+1)*m_iLensGridSegmentCountH+x +offset;
- vIndices.push_back( a );
- vIndices.push_back( b );
- vIndices.push_back( c );
-
- vIndices.push_back( a );
- vIndices.push_back( c );
- vIndices.push_back( d );
- }
- }
-
- offset = (m_iLensGridSegmentCountH)*(m_iLensGridSegmentCountV);
- for( GLushort y=0; y<m_iLensGridSegmentCountV-1; y++ )
- {
- for( GLushort x=0; x<m_iLensGridSegmentCountH-1; x++ )
- {
- a = m_iLensGridSegmentCountH*y+x +offset;
- b = m_iLensGridSegmentCountH*y+x+1 +offset;
- c = (y+1)*m_iLensGridSegmentCountH+x+1 +offset;
- d = (y+1)*m_iLensGridSegmentCountH+x +offset;
- vIndices.push_back( a );
- vIndices.push_back( b );
- vIndices.push_back( c );
-
- vIndices.push_back( a );
- vIndices.push_back( c );
- vIndices.push_back( d );
- }
- }
- m_uiIndexSize = vIndices.size();
-
- glGenVertexArrays( 1, &m_unLensVAO );
- glBindVertexArray( m_unLensVAO );
-
- glGenBuffers( 1, &m_glIDVertBuffer );
- glBindBuffer( GL_ARRAY_BUFFER, m_glIDVertBuffer );
- glBufferData( GL_ARRAY_BUFFER, vVerts.size()*sizeof(VertexDataLens), &vVerts[0], GL_STATIC_DRAW );
-
- glGenBuffers( 1, &m_glIDIndexBuffer );
- glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_glIDIndexBuffer );
- glBufferData( GL_ELEMENT_ARRAY_BUFFER, vIndices.size()*sizeof(GLushort), &vIndices[0], GL_STATIC_DRAW );
+ glGenBuffers( 1, &m_glCompanionWindowIDIndexBuffer );
+ glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_glCompanionWindowIDIndexBuffer );
+ glBufferData( GL_ELEMENT_ARRAY_BUFFER, m_uiCompanionWindowIndexSize*sizeof(GLushort), &vIndices[0], GL_STATIC_DRAW );
glEnableVertexAttribArray( 0 );
- glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexDataLens), (void *)offsetof( VertexDataLens, position ) );
+ glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexDataWindow), (void *)offsetof( VertexDataWindow, position ) );
glEnableVertexAttribArray( 1 );
- glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(VertexDataLens), (void *)offsetof( VertexDataLens, texCoordRed ) );
-
- glEnableVertexAttribArray(2);
- glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(VertexDataLens), (void *)offsetof( VertexDataLens, texCoordGreen ) );
-
- glEnableVertexAttribArray(3);
- glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(VertexDataLens), (void *)offsetof( VertexDataLens, texCoordBlue ) );
+ glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(VertexDataWindow), (void *)offsetof( VertexDataWindow, texCoord ) );
glBindVertexArray( 0 );
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
- glDisableVertexAttribArray(2);
- glDisableVertexAttribArray(3);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
@@ -1432,7 +1334,7 @@ void CMainApplication::SetupDistortion()
//-----------------------------------------------------------------------------
void CMainApplication::RenderStereoTargets()
{
- glClearColor( 0.15f, 0.15f, 0.18f, 1.0f ); // nice background color, but not black
+ glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
glEnable( GL_MULTISAMPLE );
// Left Eye
@@ -1476,7 +1378,7 @@ void CMainApplication::RenderStereoTargets()
//-----------------------------------------------------------------------------
-// Purpose:
+// Purpose: Renders a scene with respect to nEye.
//-----------------------------------------------------------------------------
void CMainApplication::RenderScene( vr::Hmd_Eye nEye )
{
@@ -1534,29 +1436,29 @@ void CMainApplication::RenderScene( vr::Hmd_Eye nEye )
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
-void CMainApplication::RenderDistortion()
+void CMainApplication::RenderCompanionWindow()
{
glDisable(GL_DEPTH_TEST);
- glViewport( 0, 0, m_nWindowWidth, m_nWindowHeight );
+ glViewport( 0, 0, m_nCompanionWindowWidth, m_nCompanionWindowHeight );
- glBindVertexArray( m_unLensVAO );
- glUseProgram( m_unLensProgramID );
+ glBindVertexArray( m_unCompanionWindowVAO );
+ glUseProgram( m_unCompanionWindowProgramID );
- //render left lens (first half of index array )
+ // render left eye (first half of index array )
glBindTexture(GL_TEXTURE_2D, leftEyeDesc.m_nResolveTextureId );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
- glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
- glDrawElements( GL_TRIANGLES, m_uiIndexSize/2, GL_UNSIGNED_SHORT, 0 );
+ glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
+ glDrawElements( GL_TRIANGLES, m_uiCompanionWindowIndexSize/2, GL_UNSIGNED_SHORT, 0 );
- //render right lens (second half of index array )
+ // render right eye (second half of index array )
glBindTexture(GL_TEXTURE_2D, rightEyeDesc.m_nResolveTextureId );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
- glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
- glDrawElements( GL_TRIANGLES, m_uiIndexSize/2, GL_UNSIGNED_SHORT, (const void *)(m_uiIndexSize) );
+ glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
+ glDrawElements( GL_TRIANGLES, m_uiCompanionWindowIndexSize/2, GL_UNSIGNED_SHORT, (const void *)(m_uiCompanionWindowIndexSize) );
glBindVertexArray( 0 );
glUseProgram( 0 );
@@ -1564,7 +1466,7 @@ void CMainApplication::RenderDistortion()
//-----------------------------------------------------------------------------
-// Purpose:
+// Purpose: Gets a Matrix Projection Eye with respect to nEye.
//-----------------------------------------------------------------------------
Matrix4 CMainApplication::GetHMDMatrixProjectionEye( vr::Hmd_Eye nEye )
{
@@ -1583,7 +1485,7 @@ Matrix4 CMainApplication::GetHMDMatrixProjectionEye( vr::Hmd_Eye nEye )
//-----------------------------------------------------------------------------
-// Purpose:
+// Purpose: Gets an HMDMatrixPoseEye with respect to nEye.
//-----------------------------------------------------------------------------
Matrix4 CMainApplication::GetHMDMatrixPoseEye( vr::Hmd_Eye nEye )
{
@@ -1603,7 +1505,8 @@ Matrix4 CMainApplication::GetHMDMatrixPoseEye( vr::Hmd_Eye nEye )
//-----------------------------------------------------------------------------
-// Purpose:
+// Purpose: Gets a Current View Projection Matrix with respect to nEye,
+// which may be an Eye_Left or an Eye_Right.
//-----------------------------------------------------------------------------
Matrix4 CMainApplication::GetCurrentViewProjectionMatrix( vr::Hmd_Eye nEye )
{
@@ -1657,7 +1560,8 @@ void CMainApplication::UpdateHMDMatrixPose()
if ( m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].bPoseIsValid )
{
- m_mat4HMDPose = m_rmat4DevicePose[vr::k_unTrackedDeviceIndex_Hmd].invert();
+ m_mat4HMDPose = m_rmat4DevicePose[vr::k_unTrackedDeviceIndex_Hmd];
+ m_mat4HMDPose.invert();
}
}
diff --git a/samples/helloworldoverlay/CMakeLists.txt b/samples/helloworldoverlay/CMakeLists.txt
new file mode 100644
index 0000000..c2f7b0e
--- /dev/null
+++ b/samples/helloworldoverlay/CMakeLists.txt
@@ -0,0 +1,28 @@
+set(TARGET_NAME helloworldoverlay)
+
+add_executable(${TARGET_NAME}
+ ${SHARED_SRC_FILES}
+ main.cpp
+ openvroverlaycontroller.cpp
+ openvroverlaycontroller.h
+ overlaywidget.cpp
+ overlaywidget.h
+)
+
+add_definitions(${QT_DEFINITIONS})
+if(NOT "${CMAKE_BUILD_TYPE}" EQUAL "Debug")
+ add_definitions(-DQT_NO_DEBUG)
+endif()
+
+target_link_libraries(${TARGET_NAME}
+ ${QT_LIBRARIES}
+ ${OPENVR_LIBRARIES}
+ ${CMAKE_DL_LIBS}
+)
+
+set_target_properties(${TARGET_NAME}
+ PROPERTIES
+ COMPILE_FLAGS "${QT_FLAGS}"
+)
+
+setTargetOutputDirectory(${TARGET_NAME}) \ No newline at end of file
diff --git a/samples/helloworldoverlay/helloworldoverlay.pro b/samples/helloworldoverlay/helloworldoverlay.pro
index c82eeff..aee8a6d 100644
--- a/samples/helloworldoverlay/helloworldoverlay.pro
+++ b/samples/helloworldoverlay/helloworldoverlay.pro
@@ -5,6 +5,7 @@
#-------------------------------------------------
QT += core gui
+CONFIG += c++11
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
diff --git a/samples/helloworldoverlay/openvroverlaycontroller.h b/samples/helloworldoverlay/openvroverlaycontroller.h
index 3c6be77..df67c30 100644
--- a/samples/helloworldoverlay/openvroverlaycontroller.h
+++ b/samples/helloworldoverlay/openvroverlaycontroller.h
@@ -19,6 +19,7 @@
#include <QtGui/QOpenGLContext>
#include <QtWidgets/QGraphicsScene>
#include <QOffscreenSurface>
+class QOpenGLFramebufferObject;
class COpenVROverlayController : public QObject
{
diff --git a/samples/shared/compat.h b/samples/shared/compat.h
new file mode 100644
index 0000000..0163b08
--- /dev/null
+++ b/samples/shared/compat.h
@@ -0,0 +1,27 @@
+#ifndef OPENVR_SAMPLES_SHARED_COMPAT_H_
+#define OPENVR_SAMPLES_SHARED_COMPAT_H_
+
+#include <cstdio>
+#include <cstring>
+#include <cassert>
+
+// Handle non standard code.
+#ifndef _WIN32
+
+#include <cstdbool>
+#include <unistd.h>
+
+#define sprintf_s snprintf
+#define vsprintf_s sprintf
+#define _stricmp strcmp
+#define stricmp strcmp
+#define strcpy_s(dst, n, src) int(strncpy(dst, src, n) != nullptr)
+#define fopen_s(fd, path, mode) int((*fd = fopen(path, mode)) != nullptr)
+#define _vsnprintf_s(buffer, size, fmt, ap) vsnprintf(buffer, size, fmt, ap)
+#define OutputDebugStringA(x) fprintf(stderr, "%s\n", x)
+
+typedef int errno_t;
+
+#endif // _WIN32
+
+#endif // OPENVR_SAMPLES_SHARED_COMPAT_H_ \ No newline at end of file
diff --git a/samples/tracked_camera_openvr_sample/CMakeLists.txt b/samples/tracked_camera_openvr_sample/CMakeLists.txt
new file mode 100644
index 0000000..15281a2
--- /dev/null
+++ b/samples/tracked_camera_openvr_sample/CMakeLists.txt
@@ -0,0 +1,26 @@
+set(TARGET_NAME tracked_camera_openvr_sample)
+
+add_executable(${TARGET_NAME}
+ ${SHARED_SRC_FILES}
+ main.cpp
+ tracked_camera_openvr_sample.cpp
+ tracked_camera_openvr_sample.h
+)
+
+add_definitions(${QT_DEFINITIONS})
+if(NOT "${CMAKE_BUILD_TYPE}" EQUAL "Debug")
+ add_definitions(-DQT_NO_DEBUG)
+endif()
+
+target_link_libraries(${TARGET_NAME}
+ ${QT_LIBRARIES}
+ ${OPENVR_LIBRARIES}
+ ${CMAKE_DL_LIBS}
+)
+
+set_target_properties(${TARGET_NAME}
+ PROPERTIES
+ COMPILE_FLAGS "${QT_FLAGS}"
+)
+
+setTargetOutputDirectory(${TARGET_NAME}) \ No newline at end of file
diff --git a/samples/tracked_camera_openvr_sample/tracked_camera_openvr_sample.cpp b/samples/tracked_camera_openvr_sample/tracked_camera_openvr_sample.cpp
index aa18c89..564df43 100644
--- a/samples/tracked_camera_openvr_sample/tracked_camera_openvr_sample.cpp
+++ b/samples/tracked_camera_openvr_sample/tracked_camera_openvr_sample.cpp
@@ -292,6 +292,8 @@ void CQTrackedCameraOpenVRTest::LogMessage( ELogLevel nLogLevel, const char *pMe
m_pMessageText->insertPlainText( formattedMessage );
m_pMessageText->moveCursor( QTextCursor::End, QTextCursor::MoveAnchor );
}
+
+ fprintf(stderr, "%s", formattedMessage);
}
//-----------------------------------------------------------------------------
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
new file mode 100644
index 0000000..24f80c6
--- /dev/null
+++ b/src/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 2.8)
+
+project(openvr_api)
+
+IF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
+ add_definitions(-DOSX -DPOSIX)
+ set_source_files_properties(vrcommon/pathtools_public.cpp vrcommon/vrpathregistry_public.cpp PROPERTIES COMPILE_FLAGS "-x objective-c++")
+ENDIF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
+
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
+include_directories(. ../headers)
+add_library(openvr_api STATIC openvr_api_public.cpp jsoncpp.cpp vrcommon/dirtools_public.cpp vrcommon/envvartools_public.cpp vrcommon/pathtools_public.cpp vrcommon/sharedlibtools_public.cpp vrcommon/hmderrors_public.cpp vrcommon/vrpathregistry_public.cpp vrcommon/strtools_public.cpp vrcommon/vrpathregistry_public.cpp)
+
+install(TARGETS openvr_api DESTINATION lib) \ No newline at end of file
diff --git a/src/README b/src/README
new file mode 100644
index 0000000..953e105
--- /dev/null
+++ b/src/README
@@ -0,0 +1,35 @@
+This is the source code for the OpenVR API client binding library which connects
+OpenVR applications to the SteamVR runtime, taking into account the version
+of the OpenVR interface they were compiled against.
+
+The client binding library - openvr_api.dll on Windows, openvr_api.so on
+Linux, and openvr_api.dylib on macOS - knows how to find and read the
+SteamVR runtime installation information which allows it to find and
+dynamically connect to the installed runtime. In combination with the
+interface version identifiers from /include/openvr.h which are baked
+into applications at the time they are built, the OpenVR API client
+binding library captures and conveys to the SteamVR runtime the version
+of the OpenVR API interface behavior that the application expects.
+
+Applications carry with them a private/local copy of the client binding
+library when they ship, and they should install it locally to their
+application. Applications should not install the client binding library
+globally or attempt to link to a globally installed client binding library.
+Doing so negates at least part of the ability for the client binding library
+to accurately reflect the version of the OpenVR API that the application
+was built against, and so hinders compatibility support in the face of
+API changes.
+
+Most applications should simply link to and redistribute with their application
+the pre-built client binding library found in the /bin directory of this
+repository. Some small number of applications which have specific requirements
+around redistributing only binaries they build themselves should build
+the client library from this source and either statically link it into
+their application or redistribute the binary they build.
+
+This is a cmake project, to build it use the version of cmake appropriate
+for your platform. For example, to build on a POSIX system simply perform
+
+ cd src; mkdir _build; cd _build; cmake ..; make
+
+and you will end up with the static library /src/_build/libopenvr_api.a \ No newline at end of file
diff --git a/src/ivrclientcore.h b/src/ivrclientcore.h
new file mode 100644
index 0000000..b4c6f3a
--- /dev/null
+++ b/src/ivrclientcore.h
@@ -0,0 +1,35 @@
+//========= Copyright Valve Corporation ============//
+#pragma once
+
+namespace vr
+{
+
+class IVRClientCore
+{
+public:
+ /** Initializes the system */
+ virtual EVRInitError Init( vr::EVRApplicationType eApplicationType ) = 0;
+
+ /** cleans up everything in vrclient.dll and prepares the DLL to be unloaded */
+ virtual void Cleanup() = 0;
+
+ /** checks to see if the specified interface/version is supported in this vrclient.dll */
+ virtual EVRInitError IsInterfaceVersionValid( const char *pchInterfaceVersion ) = 0;
+
+ /** Retrieves any interface from vrclient.dll */
+ virtual void *GetGenericInterface( const char *pchNameAndVersion, EVRInitError *peError ) = 0;
+
+ /** Returns true if any driver has an HMD attached. Can be called outside of Init/Cleanup */
+ virtual bool BIsHmdPresent() = 0;
+
+ /** Returns an english error string from inside vrclient.dll which might be newer than the API DLL */
+ virtual const char *GetEnglishStringForHmdError( vr::EVRInitError eError ) = 0;
+
+ /** Returns an error symbol from inside vrclient.dll which might be newer than the API DLL */
+ virtual const char *GetIDForVRInitError( vr::EVRInitError eError ) = 0;
+};
+
+static const char * const IVRClientCore_Version = "IVRClientCore_002";
+
+
+}
diff --git a/src/json/json-forwards.h b/src/json/json-forwards.h
new file mode 100644
index 0000000..910c7de
--- /dev/null
+++ b/src/json/json-forwards.h
@@ -0,0 +1,284 @@
+/// Json-cpp amalgated forward header (http://jsoncpp.sourceforge.net/).
+/// It is intended to be used with #include "json/json-forwards.h"
+/// This header provides forward declaration for all JsonCpp types.
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+/*
+The JsonCpp library's source code, including accompanying documentation,
+tests and demonstration applications, are licensed under the following
+conditions...
+
+The author (Baptiste Lepilleur) explicitly disclaims copyright in all
+jurisdictions which recognize such a disclaimer. In such jurisdictions,
+this software is released into the Public Domain.
+
+In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
+2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
+released under the terms of the MIT License (see below).
+
+In jurisdictions which recognize Public Domain property, the user of this
+software may choose to accept it either as 1) Public Domain, 2) under the
+conditions of the MIT License (see below), or 3) under the terms of dual
+Public Domain/MIT License conditions described here, as they choose.
+
+The MIT License is about as close to Public Domain as a license can get, and is
+described in clear, concise terms at:
+
+ http://en.wikipedia.org/wiki/MIT_License
+
+The full text of the MIT License follows:
+
+========================================================================
+Copyright (c) 2007-2010 Baptiste Lepilleur
+
+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.
+========================================================================
+(END LICENSE TEXT)
+
+The MIT license is compatible with both the GPL and commercial
+software, affording one all of the rights of Public Domain with the
+minor nuisance of being required to keep the above copyright notice
+and license text in the source code. Note also that by accepting the
+Public Domain "license" you can re-license your copy using whatever
+license you like.
+
+*/
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+#ifndef JSON_FORWARD_AMALGATED_H_INCLUDED
+# define JSON_FORWARD_AMALGATED_H_INCLUDED
+/// If defined, indicates that the source file is amalgated
+/// to prevent private header inclusion.
+#define JSON_IS_AMALGAMATION
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/config.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_CONFIG_H_INCLUDED
+#define JSON_CONFIG_H_INCLUDED
+
+/// If defined, indicates that json library is embedded in CppTL library.
+//# define JSON_IN_CPPTL 1
+
+/// If defined, indicates that json may leverage CppTL library
+//# define JSON_USE_CPPTL 1
+/// If defined, indicates that cpptl vector based map should be used instead of
+/// std::map
+/// as Value container.
+//# define JSON_USE_CPPTL_SMALLMAP 1
+
+// If non-zero, the library uses exceptions to report bad input instead of C
+// assertion macros. The default is to use exceptions.
+#ifndef JSON_USE_EXCEPTION
+#define JSON_USE_EXCEPTION 1
+#endif
+
+/// If defined, indicates that the source file is amalgated
+/// to prevent private header inclusion.
+/// Remarks: it is automatically defined in the generated amalgated header.
+// #define JSON_IS_AMALGAMATION
+
+#ifdef JSON_IN_CPPTL
+#include <cpptl/config.h>
+#ifndef JSON_USE_CPPTL
+#define JSON_USE_CPPTL 1
+#endif
+#endif
+
+#ifdef JSON_IN_CPPTL
+#define JSON_API CPPTL_API
+#elif defined(JSON_DLL_BUILD)
+#if defined(_MSC_VER)
+#define JSON_API __declspec(dllexport)
+#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
+#endif // if defined(_MSC_VER)
+#elif defined(JSON_DLL)
+#if defined(_MSC_VER)
+#define JSON_API __declspec(dllimport)
+#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
+#endif // if defined(_MSC_VER)
+#endif // ifdef JSON_IN_CPPTL
+#if !defined(JSON_API)
+#define JSON_API
+#endif
+
+// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
+// integer
+// Storages, and 64 bits integer support is disabled.
+// #define JSON_NO_INT64 1
+
+#if defined(_MSC_VER) // MSVC
+# if _MSC_VER <= 1200 // MSVC 6
+ // Microsoft Visual Studio 6 only support conversion from __int64 to double
+ // (no conversion from unsigned __int64).
+# define JSON_USE_INT64_DOUBLE_CONVERSION 1
+ // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
+ // characters in the debug information)
+ // All projects I've ever seen with VS6 were using this globally (not bothering
+ // with pragma push/pop).
+# pragma warning(disable : 4786)
+# endif // MSVC 6
+
+# if _MSC_VER >= 1500 // MSVC 2008
+ /// Indicates that the following function is deprecated.
+# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
+# endif
+
+#endif // defined(_MSC_VER)
+
+
+#ifndef JSON_HAS_RVALUE_REFERENCES
+
+#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // MSVC >= 2010
+
+#ifdef __clang__
+#if __has_feature(cxx_rvalue_references)
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // has_feature
+
+#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
+#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // GXX_EXPERIMENTAL
+
+#endif // __clang__ || __GNUC__
+
+#endif // not defined JSON_HAS_RVALUE_REFERENCES
+
+#ifndef JSON_HAS_RVALUE_REFERENCES
+#define JSON_HAS_RVALUE_REFERENCES 0
+#endif
+
+#ifdef __clang__
+#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
+# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
+# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
+# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
+# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
+# endif // GNUC version
+#endif // __clang__ || __GNUC__
+
+#if !defined(JSONCPP_DEPRECATED)
+#define JSONCPP_DEPRECATED(message)
+#endif // if !defined(JSONCPP_DEPRECATED)
+
+namespace Json {
+typedef int Int;
+typedef unsigned int UInt;
+#if defined(JSON_NO_INT64)
+typedef int LargestInt;
+typedef unsigned int LargestUInt;
+#undef JSON_HAS_INT64
+#else // if defined(JSON_NO_INT64)
+// For Microsoft Visual use specific types as long long is not supported
+#if defined(_MSC_VER) // Microsoft Visual Studio
+typedef __int64 Int64;
+typedef unsigned __int64 UInt64;
+#else // if defined(_MSC_VER) // Other platforms, use long long
+typedef long long int Int64;
+typedef unsigned long long int UInt64;
+#endif // if defined(_MSC_VER)
+typedef Int64 LargestInt;
+typedef UInt64 LargestUInt;
+#define JSON_HAS_INT64
+#endif // if defined(JSON_NO_INT64)
+} // end namespace Json
+
+#endif // JSON_CONFIG_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/config.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/forwards.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_FORWARDS_H_INCLUDED
+#define JSON_FORWARDS_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "config.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+namespace Json {
+
+// writer.h
+class FastWriter;
+class StyledWriter;
+
+// reader.h
+class Reader;
+
+// features.h
+class Features;
+
+// value.h
+typedef unsigned int ArrayIndex;
+class StaticString;
+class Path;
+class PathArgument;
+class Value;
+class ValueIteratorBase;
+class ValueIterator;
+class ValueConstIterator;
+
+} // namespace Json
+
+#endif // JSON_FORWARDS_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/forwards.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+#endif //ifndef JSON_FORWARD_AMALGATED_H_INCLUDED
diff --git a/src/json/json.h b/src/json/json.h
new file mode 100644
index 0000000..d27f65d
--- /dev/null
+++ b/src/json/json.h
@@ -0,0 +1,2077 @@
+/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).
+/// It is intended to be used with #include "json/json.h"
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+/*
+The JsonCpp library's source code, including accompanying documentation,
+tests and demonstration applications, are licensed under the following
+conditions...
+
+The author (Baptiste Lepilleur) explicitly disclaims copyright in all
+jurisdictions which recognize such a disclaimer. In such jurisdictions,
+this software is released into the Public Domain.
+
+In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
+2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
+released under the terms of the MIT License (see below).
+
+In jurisdictions which recognize Public Domain property, the user of this
+software may choose to accept it either as 1) Public Domain, 2) under the
+conditions of the MIT License (see below), or 3) under the terms of dual
+Public Domain/MIT License conditions described here, as they choose.
+
+The MIT License is about as close to Public Domain as a license can get, and is
+described in clear, concise terms at:
+
+ http://en.wikipedia.org/wiki/MIT_License
+
+The full text of the MIT License follows:
+
+========================================================================
+Copyright (c) 2007-2010 Baptiste Lepilleur
+
+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.
+========================================================================
+(END LICENSE TEXT)
+
+The MIT license is compatible with both the GPL and commercial
+software, affording one all of the rights of Public Domain with the
+minor nuisance of being required to keep the above copyright notice
+and license text in the source code. Note also that by accepting the
+Public Domain "license" you can re-license your copy using whatever
+license you like.
+
+*/
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+#ifndef JSON_AMALGATED_H_INCLUDED
+# define JSON_AMALGATED_H_INCLUDED
+/// If defined, indicates that the source file is amalgated
+/// to prevent private header inclusion.
+#define JSON_IS_AMALGAMATION
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/version.h
+// //////////////////////////////////////////////////////////////////////
+
+// DO NOT EDIT. This file (and "version") is generated by CMake.
+// Run CMake configure step to update it.
+#ifndef JSON_VERSION_H_INCLUDED
+# define JSON_VERSION_H_INCLUDED
+
+# define JSONCPP_VERSION_STRING "1.6.5"
+# define JSONCPP_VERSION_MAJOR 1
+# define JSONCPP_VERSION_MINOR 6
+# define JSONCPP_VERSION_PATCH 5
+# define JSONCPP_VERSION_QUALIFIER
+# define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
+
+#endif // JSON_VERSION_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/version.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/config.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_CONFIG_H_INCLUDED
+#define JSON_CONFIG_H_INCLUDED
+
+/// If defined, indicates that json library is embedded in CppTL library.
+//# define JSON_IN_CPPTL 1
+
+/// If defined, indicates that json may leverage CppTL library
+//# define JSON_USE_CPPTL 1
+/// If defined, indicates that cpptl vector based map should be used instead of
+/// std::map
+/// as Value container.
+//# define JSON_USE_CPPTL_SMALLMAP 1
+
+// If non-zero, the library uses exceptions to report bad input instead of C
+// assertion macros. The default is to use exceptions.
+#ifndef JSON_USE_EXCEPTION
+#define JSON_USE_EXCEPTION 1
+#endif
+
+/// If defined, indicates that the source file is amalgated
+/// to prevent private header inclusion.
+/// Remarks: it is automatically defined in the generated amalgated header.
+// #define JSON_IS_AMALGAMATION
+
+#ifdef JSON_IN_CPPTL
+#include <cpptl/config.h>
+#ifndef JSON_USE_CPPTL
+#define JSON_USE_CPPTL 1
+#endif
+#endif
+
+#ifdef JSON_IN_CPPTL
+#define JSON_API CPPTL_API
+#elif defined(JSON_DLL_BUILD)
+#if defined(_MSC_VER)
+#define JSON_API __declspec(dllexport)
+#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
+#endif // if defined(_MSC_VER)
+#elif defined(JSON_DLL)
+#if defined(_MSC_VER)
+#define JSON_API __declspec(dllimport)
+#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
+#endif // if defined(_MSC_VER)
+#endif // ifdef JSON_IN_CPPTL
+#if !defined(JSON_API)
+#define JSON_API
+#endif
+
+// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
+// integer
+// Storages, and 64 bits integer support is disabled.
+// #define JSON_NO_INT64 1
+
+#if defined(_MSC_VER) // MSVC
+# if _MSC_VER <= 1200 // MSVC 6
+ // Microsoft Visual Studio 6 only support conversion from __int64 to double
+ // (no conversion from unsigned __int64).
+# define JSON_USE_INT64_DOUBLE_CONVERSION 1
+ // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
+ // characters in the debug information)
+ // All projects I've ever seen with VS6 were using this globally (not bothering
+ // with pragma push/pop).
+# pragma warning(disable : 4786)
+# endif // MSVC 6
+
+# if _MSC_VER >= 1500 // MSVC 2008
+ /// Indicates that the following function is deprecated.
+# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
+# endif
+
+#endif // defined(_MSC_VER)
+
+
+#ifndef JSON_HAS_RVALUE_REFERENCES
+
+#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // MSVC >= 2010
+
+#ifdef __clang__
+#if __has_feature(cxx_rvalue_references)
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // has_feature
+
+#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
+#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // GXX_EXPERIMENTAL
+
+#endif // __clang__ || __GNUC__
+
+#endif // not defined JSON_HAS_RVALUE_REFERENCES
+
+#ifndef JSON_HAS_RVALUE_REFERENCES
+#define JSON_HAS_RVALUE_REFERENCES 0
+#endif
+
+#ifdef __clang__
+#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
+# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
+# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
+# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
+# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
+# endif // GNUC version
+#endif // __clang__ || __GNUC__
+
+#if !defined(JSONCPP_DEPRECATED)
+#define JSONCPP_DEPRECATED(message)
+#endif // if !defined(JSONCPP_DEPRECATED)
+
+namespace Json {
+typedef int Int;
+typedef unsigned int UInt;
+#if defined(JSON_NO_INT64)
+typedef int LargestInt;
+typedef unsigned int LargestUInt;
+#undef JSON_HAS_INT64
+#else // if defined(JSON_NO_INT64)
+// For Microsoft Visual use specific types as long long is not supported
+#if defined(_MSC_VER) // Microsoft Visual Studio
+typedef __int64 Int64;
+typedef unsigned __int64 UInt64;
+#else // if defined(_MSC_VER) // Other platforms, use long long
+typedef long long int Int64;
+typedef unsigned long long int UInt64;
+#endif // if defined(_MSC_VER)
+typedef Int64 LargestInt;
+typedef UInt64 LargestUInt;
+#define JSON_HAS_INT64
+#endif // if defined(JSON_NO_INT64)
+} // end namespace Json
+
+#endif // JSON_CONFIG_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/config.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/forwards.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_FORWARDS_H_INCLUDED
+#define JSON_FORWARDS_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "config.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+namespace Json {
+
+// writer.h
+class FastWriter;
+class StyledWriter;
+
+// reader.h
+class Reader;
+
+// features.h
+class Features;
+
+// value.h
+typedef unsigned int ArrayIndex;
+class StaticString;
+class Path;
+class PathArgument;
+class Value;
+class ValueIteratorBase;
+class ValueIterator;
+class ValueConstIterator;
+
+} // namespace Json
+
+#endif // JSON_FORWARDS_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/forwards.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/features.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_FEATURES_H_INCLUDED
+#define CPPTL_JSON_FEATURES_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "forwards.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+namespace Json {
+
+/** \brief Configuration passed to reader and writer.
+ * This configuration object can be used to force the Reader or Writer
+ * to behave in a standard conforming way.
+ */
+class JSON_API Features {
+public:
+ /** \brief A configuration that allows all features and assumes all strings
+ * are UTF-8.
+ * - C & C++ comments are allowed
+ * - Root object can be any JSON value
+ * - Assumes Value strings are encoded in UTF-8
+ */
+ static Features all();
+
+ /** \brief A configuration that is strictly compatible with the JSON
+ * specification.
+ * - Comments are forbidden.
+ * - Root object must be either an array or an object value.
+ * - Assumes Value strings are encoded in UTF-8
+ */
+ static Features strictMode();
+
+ /** \brief Initialize the configuration like JsonConfig::allFeatures;
+ */
+ Features();
+
+ /// \c true if comments are allowed. Default: \c true.
+ bool allowComments_;
+
+ /// \c true if root must be either an array or an object value. Default: \c
+ /// false.
+ bool strictRoot_;
+
+ /// \c true if dropped null placeholders are allowed. Default: \c false.
+ bool allowDroppedNullPlaceholders_;
+
+ /// \c true if numeric object key are allowed. Default: \c false.
+ bool allowNumericKeys_;
+};
+
+} // namespace Json
+
+#endif // CPPTL_JSON_FEATURES_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/features.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/value.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_H_INCLUDED
+#define CPPTL_JSON_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "forwards.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <string>
+#include <vector>
+#include <exception>
+
+#ifndef JSON_USE_CPPTL_SMALLMAP
+#include <map>
+#else
+#include <cpptl/smallmap.h>
+#endif
+#ifdef JSON_USE_CPPTL
+#include <cpptl/forwards.h>
+#endif
+
+// Disable warning C4251: <data member>: <type> needs to have dll-interface to
+// be used by...
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(push)
+#pragma warning(disable : 4251)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+/** \brief JSON (JavaScript Object Notation).
+ */
+namespace Json {
+
+/** Base class for all exceptions we throw.
+ *
+ * We use nothing but these internally. Of course, STL can throw others.
+ */
+class JSON_API Exception : public std::exception {
+public:
+ Exception(std::string const& msg);
+ ~Exception() throw();
+ char const* what() const throw();
+protected:
+ std::string msg_;
+};
+
+/** Exceptions which the user cannot easily avoid.
+ *
+ * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
+ *
+ * \remark derived from Json::Exception
+ */
+class JSON_API RuntimeError : public Exception {
+public:
+ RuntimeError(std::string const& msg);
+};
+
+/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
+ *
+ * These are precondition-violations (user bugs) and internal errors (our bugs).
+ *
+ * \remark derived from Json::Exception
+ */
+class JSON_API LogicError : public Exception {
+public:
+ LogicError(std::string const& msg);
+};
+
+/// used internally
+void throwRuntimeError(std::string const& msg);
+/// used internally
+void throwLogicError(std::string const& msg);
+
+/** \brief Type of the value held by a Value object.
+ */
+enum ValueType {
+ nullValue = 0, ///< 'null' value
+ intValue, ///< signed integer value
+ uintValue, ///< unsigned integer value
+ realValue, ///< double value
+ stringValue, ///< UTF-8 string value
+ booleanValue, ///< bool value
+ arrayValue, ///< array value (ordered list)
+ objectValue ///< object value (collection of name/value pairs).
+};
+
+enum CommentPlacement {
+ commentBefore = 0, ///< a comment placed on the line before a value
+ commentAfterOnSameLine, ///< a comment just after a value on the same line
+ commentAfter, ///< a comment on the line after a value (only make sense for
+ /// root value)
+ numberOfCommentPlacement
+};
+
+//# ifdef JSON_USE_CPPTL
+// typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
+// typedef CppTL::AnyEnumerator<const Value &> EnumValues;
+//# endif
+
+/** \brief Lightweight wrapper to tag static string.
+ *
+ * Value constructor and objectValue member assignement takes advantage of the
+ * StaticString and avoid the cost of string duplication when storing the
+ * string or the member name.
+ *
+ * Example of usage:
+ * \code
+ * Json::Value aValue( StaticString("some text") );
+ * Json::Value object;
+ * static const StaticString code("code");
+ * object[code] = 1234;
+ * \endcode
+ */
+class JSON_API StaticString {
+public:
+ explicit StaticString(const char* czstring) : c_str_(czstring) {}
+
+ operator const char*() const { return c_str_; }
+
+ const char* c_str() const { return c_str_; }
+
+private:
+ const char* c_str_;
+};
+
+/** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
+ *
+ * This class is a discriminated union wrapper that can represents a:
+ * - signed integer [range: Value::minInt - Value::maxInt]
+ * - unsigned integer (range: 0 - Value::maxUInt)
+ * - double
+ * - UTF-8 string
+ * - boolean
+ * - 'null'
+ * - an ordered list of Value
+ * - collection of name/value pairs (javascript object)
+ *
+ * The type of the held value is represented by a #ValueType and
+ * can be obtained using type().
+ *
+ * Values of an #objectValue or #arrayValue can be accessed using operator[]()
+ * methods.
+ * Non-const methods will automatically create the a #nullValue element
+ * if it does not exist.
+ * The sequence of an #arrayValue will be automatically resized and initialized
+ * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
+ *
+ * The get() methods can be used to obtain default value in the case the
+ * required element does not exist.
+ *
+ * It is possible to iterate over the list of a #objectValue values using
+ * the getMemberNames() method.
+ *
+ * \note #Value string-length fit in size_t, but keys must be < 2^30.
+ * (The reason is an implementation detail.) A #CharReader will raise an
+ * exception if a bound is exceeded to avoid security holes in your app,
+ * but the Value API does *not* check bounds. That is the responsibility
+ * of the caller.
+ */
+class JSON_API Value {
+ friend class ValueIteratorBase;
+public:
+ typedef std::vector<std::string> Members;
+ typedef ValueIterator iterator;
+ typedef ValueConstIterator const_iterator;
+ typedef Json::UInt UInt;
+ typedef Json::Int Int;
+#if defined(JSON_HAS_INT64)
+ typedef Json::UInt64 UInt64;
+ typedef Json::Int64 Int64;
+#endif // defined(JSON_HAS_INT64)
+ typedef Json::LargestInt LargestInt;
+ typedef Json::LargestUInt LargestUInt;
+ typedef Json::ArrayIndex ArrayIndex;
+
+ static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value().
+ static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null
+ /// Minimum signed integer value that can be stored in a Json::Value.
+ static const LargestInt minLargestInt;
+ /// Maximum signed integer value that can be stored in a Json::Value.
+ static const LargestInt maxLargestInt;
+ /// Maximum unsigned integer value that can be stored in a Json::Value.
+ static const LargestUInt maxLargestUInt;
+
+ /// Minimum signed int value that can be stored in a Json::Value.
+ static const Int minInt;
+ /// Maximum signed int value that can be stored in a Json::Value.
+ static const Int maxInt;
+ /// Maximum unsigned int value that can be stored in a Json::Value.
+ static const UInt maxUInt;
+
+#if defined(JSON_HAS_INT64)
+ /// Minimum signed 64 bits int value that can be stored in a Json::Value.
+ static const Int64 minInt64;
+ /// Maximum signed 64 bits int value that can be stored in a Json::Value.
+ static const Int64 maxInt64;
+ /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
+ static const UInt64 maxUInt64;
+#endif // defined(JSON_HAS_INT64)
+
+private:
+#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
+ class CZString {
+ public:
+ enum DuplicationPolicy {
+ noDuplication = 0,
+ duplicate,
+ duplicateOnCopy
+ };
+ CZString(ArrayIndex index);
+ CZString(char const* str, unsigned length, DuplicationPolicy allocate);
+ CZString(CZString const& other);
+#if JSON_HAS_RVALUE_REFERENCES
+ CZString(CZString&& other);
+#endif
+ ~CZString();
+ CZString& operator=(CZString other);
+ bool operator<(CZString const& other) const;
+ bool operator==(CZString const& other) const;
+ ArrayIndex index() const;
+ //const char* c_str() const; ///< \deprecated
+ char const* data() const;
+ unsigned length() const;
+ bool isStaticString() const;
+
+ private:
+ void swap(CZString& other);
+
+ struct StringStorage {
+ unsigned policy_: 2;
+ unsigned length_: 30; // 1GB max
+ };
+
+ char const* cstr_; // actually, a prefixed string, unless policy is noDup
+ union {
+ ArrayIndex index_;
+ StringStorage storage_;
+ };
+ };
+
+public:
+#ifndef JSON_USE_CPPTL_SMALLMAP
+ typedef std::map<CZString, Value> ObjectValues;
+#else
+ typedef CppTL::SmallMap<CZString, Value> ObjectValues;
+#endif // ifndef JSON_USE_CPPTL_SMALLMAP
+#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
+
+public:
+ /** \brief Create a default Value of the given type.
+
+ This is a very useful constructor.
+ To create an empty array, pass arrayValue.
+ To create an empty object, pass objectValue.
+ Another Value can then be set to this one by assignment.
+This is useful since clear() and resize() will not alter types.
+
+ Examples:
+\code
+Json::Value null_value; // null
+Json::Value arr_value(Json::arrayValue); // []
+Json::Value obj_value(Json::objectValue); // {}
+\endcode
+ */
+ Value(ValueType type = nullValue);
+ Value(Int value);
+ Value(UInt value);
+#if defined(JSON_HAS_INT64)
+ Value(Int64 value);
+ Value(UInt64 value);
+#endif // if defined(JSON_HAS_INT64)
+ Value(double value);
+ Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
+ Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
+ /** \brief Constructs a value from a static string.
+
+ * Like other value string constructor but do not duplicate the string for
+ * internal storage. The given string must remain alive after the call to this
+ * constructor.
+ * \note This works only for null-terminated strings. (We cannot change the
+ * size of this class, so we have nowhere to store the length,
+ * which might be computed later for various operations.)
+ *
+ * Example of usage:
+ * \code
+ * static StaticString foo("some text");
+ * Json::Value aValue(foo);
+ * \endcode
+ */
+ Value(const StaticString& value);
+ Value(const std::string& value); ///< Copy data() til size(). Embedded zeroes too.
+#ifdef JSON_USE_CPPTL
+ Value(const CppTL::ConstString& value);
+#endif
+ Value(bool value);
+ /// Deep copy.
+ Value(const Value& other);
+#if JSON_HAS_RVALUE_REFERENCES
+ /// Move constructor
+ Value(Value&& other);
+#endif
+ ~Value();
+
+ /// Deep copy, then swap(other).
+ /// \note Over-write existing comments. To preserve comments, use #swapPayload().
+ Value& operator=(Value other);
+ /// Swap everything.
+ void swap(Value& other);
+ /// Swap values but leave comments and source offsets in place.
+ void swapPayload(Value& other);
+
+ ValueType type() const;
+
+ /// Compare payload only, not comments etc.
+ bool operator<(const Value& other) const;
+ bool operator<=(const Value& other) const;
+ bool operator>=(const Value& other) const;
+ bool operator>(const Value& other) const;
+ bool operator==(const Value& other) const;
+ bool operator!=(const Value& other) const;
+ int compare(const Value& other) const;
+
+ const char* asCString() const; ///< Embedded zeroes could cause you trouble!
+ std::string asString() const; ///< Embedded zeroes are possible.
+ /** Get raw char* of string-value.
+ * \return false if !string. (Seg-fault if str or end are NULL.)
+ */
+ bool getString(
+ char const** begin, char const** end) const;
+#ifdef JSON_USE_CPPTL
+ CppTL::ConstString asConstString() const;
+#endif
+ Int asInt() const;
+ UInt asUInt() const;
+#if defined(JSON_HAS_INT64)
+ Int64 asInt64() const;
+ UInt64 asUInt64() const;
+#endif // if defined(JSON_HAS_INT64)
+ LargestInt asLargestInt() const;
+ LargestUInt asLargestUInt() const;
+ float asFloat() const;
+ double asDouble() const;
+ bool asBool() const;
+
+ bool isNull() const;
+ bool isBool() const;
+ bool isInt() const;
+ bool isInt64() const;
+ bool isUInt() const;
+ bool isUInt64() const;
+ bool isIntegral() const;
+ bool isDouble() const;
+ bool isNumeric() const;
+ bool isString() const;
+ bool isArray() const;
+ bool isObject() const;
+
+ bool isConvertibleTo(ValueType other) const;
+
+ /// Number of values in array or object
+ ArrayIndex size() const;
+
+ /// \brief Return true if empty array, empty object, or null;
+ /// otherwise, false.
+ bool empty() const;
+
+ /// Return isNull()
+ bool operator!() const;
+
+ /// Remove all object members and array elements.
+ /// \pre type() is arrayValue, objectValue, or nullValue
+ /// \post type() is unchanged
+ void clear();
+
+ /// Resize the array to size elements.
+ /// New elements are initialized to null.
+ /// May only be called on nullValue or arrayValue.
+ /// \pre type() is arrayValue or nullValue
+ /// \post type() is arrayValue
+ void resize(ArrayIndex size);
+
+ /// Access an array element (zero based index ).
+ /// If the array contains less than index element, then null value are
+ /// inserted
+ /// in the array so that its size is index+1.
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ Value& operator[](ArrayIndex index);
+
+ /// Access an array element (zero based index ).
+ /// If the array contains less than index element, then null value are
+ /// inserted
+ /// in the array so that its size is index+1.
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ Value& operator[](int index);
+
+ /// Access an array element (zero based index )
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ const Value& operator[](ArrayIndex index) const;
+
+ /// Access an array element (zero based index )
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ const Value& operator[](int index) const;
+
+ /// If the array contains at least index+1 elements, returns the element
+ /// value,
+ /// otherwise returns defaultValue.
+ Value get(ArrayIndex index, const Value& defaultValue) const;
+ /// Return true if index < size().
+ bool isValidIndex(ArrayIndex index) const;
+ /// \brief Append value to array at the end.
+ ///
+ /// Equivalent to jsonvalue[jsonvalue.size()] = value;
+ Value& append(const Value& value);
+
+ /// Access an object value by name, create a null member if it does not exist.
+ /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
+ /// Exceeding that will cause an exception.
+ Value& operator[](const char* key);
+ /// Access an object value by name, returns null if there is no member with
+ /// that name.
+ const Value& operator[](const char* key) const;
+ /// Access an object value by name, create a null member if it does not exist.
+ /// \param key may contain embedded nulls.
+ Value& operator[](const std::string& key);
+ /// Access an object value by name, returns null if there is no member with
+ /// that name.
+ /// \param key may contain embedded nulls.
+ const Value& operator[](const std::string& key) const;
+ /** \brief Access an object value by name, create a null member if it does not
+ exist.
+
+ * If the object has no entry for that name, then the member name used to store
+ * the new entry is not duplicated.
+ * Example of use:
+ * \code
+ * Json::Value object;
+ * static const StaticString code("code");
+ * object[code] = 1234;
+ * \endcode
+ */
+ Value& operator[](const StaticString& key);
+#ifdef JSON_USE_CPPTL
+ /// Access an object value by name, create a null member if it does not exist.
+ Value& operator[](const CppTL::ConstString& key);
+ /// Access an object value by name, returns null if there is no member with
+ /// that name.
+ const Value& operator[](const CppTL::ConstString& key) const;
+#endif
+ /// Return the member named key if it exist, defaultValue otherwise.
+ /// \note deep copy
+ Value get(const char* key, const Value& defaultValue) const;
+ /// Return the member named key if it exist, defaultValue otherwise.
+ /// \note deep copy
+ /// \note key may contain embedded nulls.
+ Value get(const char* begin, const char* end, const Value& defaultValue) const;
+ /// Return the member named key if it exist, defaultValue otherwise.
+ /// \note deep copy
+ /// \param key may contain embedded nulls.
+ Value get(const std::string& key, const Value& defaultValue) const;
+#ifdef JSON_USE_CPPTL
+ /// Return the member named key if it exist, defaultValue otherwise.
+ /// \note deep copy
+ Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
+#endif
+ /// Most general and efficient version of isMember()const, get()const,
+ /// and operator[]const
+ /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
+ Value const* find(char const* begin, char const* end) const;
+ /// Most general and efficient version of object-mutators.
+ /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
+ /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
+ Value const* demand(char const* begin, char const* end);
+ /// \brief Remove and return the named member.
+ ///
+ /// Do nothing if it did not exist.
+ /// \return the removed Value, or null.
+ /// \pre type() is objectValue or nullValue
+ /// \post type() is unchanged
+ /// \deprecated
+ Value removeMember(const char* key);
+ /// Same as removeMember(const char*)
+ /// \param key may contain embedded nulls.
+ /// \deprecated
+ Value removeMember(const std::string& key);
+ /// Same as removeMember(const char* begin, const char* end, Value* removed),
+ /// but 'key' is null-terminated.
+ bool removeMember(const char* key, Value* removed);
+ /** \brief Remove the named map member.
+
+ Update 'removed' iff removed.
+ \param key may contain embedded nulls.
+ \return true iff removed (no exceptions)
+ */
+ bool removeMember(std::string const& key, Value* removed);
+ /// Same as removeMember(std::string const& key, Value* removed)
+ bool removeMember(const char* begin, const char* end, Value* removed);
+ /** \brief Remove the indexed array element.
+
+ O(n) expensive operations.
+ Update 'removed' iff removed.
+ \return true iff removed (no exceptions)
+ */
+ bool removeIndex(ArrayIndex i, Value* removed);
+
+ /// Return true if the object has a member named key.
+ /// \note 'key' must be null-terminated.
+ bool isMember(const char* key) const;
+ /// Return true if the object has a member named key.
+ /// \param key may contain embedded nulls.
+ bool isMember(const std::string& key) const;
+ /// Same as isMember(std::string const& key)const
+ bool isMember(const char* begin, const char* end) const;
+#ifdef JSON_USE_CPPTL
+ /// Return true if the object has a member named key.
+ bool isMember(const CppTL::ConstString& key) const;
+#endif
+
+ /// \brief Return a list of the member names.
+ ///
+ /// If null, return an empty list.
+ /// \pre type() is objectValue or nullValue
+ /// \post if type() was nullValue, it remains nullValue
+ Members getMemberNames() const;
+
+ //# ifdef JSON_USE_CPPTL
+ // EnumMemberNames enumMemberNames() const;
+ // EnumValues enumValues() const;
+ //# endif
+
+ /// \deprecated Always pass len.
+ JSONCPP_DEPRECATED("Use setComment(std::string const&) instead.")
+ void setComment(const char* comment, CommentPlacement placement);
+ /// Comments must be //... or /* ... */
+ void setComment(const char* comment, size_t len, CommentPlacement placement);
+ /// Comments must be //... or /* ... */
+ void setComment(const std::string& comment, CommentPlacement placement);
+ bool hasComment(CommentPlacement placement) const;
+ /// Include delimiters and embedded newlines.
+ std::string getComment(CommentPlacement placement) const;
+
+ std::string toStyledString() const;
+
+ const_iterator begin() const;
+ const_iterator end() const;
+
+ iterator begin();
+ iterator end();
+
+ // Accessors for the [start, limit) range of bytes within the JSON text from
+ // which this value was parsed, if any.
+ void setOffsetStart(size_t start);
+ void setOffsetLimit(size_t limit);
+ size_t getOffsetStart() const;
+ size_t getOffsetLimit() const;
+
+private:
+ void initBasic(ValueType type, bool allocated = false);
+
+ Value& resolveReference(const char* key);
+ Value& resolveReference(const char* key, const char* end);
+
+ struct CommentInfo {
+ CommentInfo();
+ ~CommentInfo();
+
+ void setComment(const char* text, size_t len);
+
+ char* comment_;
+ };
+
+ // struct MemberNamesTransform
+ //{
+ // typedef const char *result_type;
+ // const char *operator()( const CZString &name ) const
+ // {
+ // return name.c_str();
+ // }
+ //};
+
+ union ValueHolder {
+ LargestInt int_;
+ LargestUInt uint_;
+ double real_;
+ bool bool_;
+ char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
+ ObjectValues* map_;
+ } value_;
+ ValueType type_ : 8;
+ unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
+ // If not allocated_, string_ must be null-terminated.
+ CommentInfo* comments_;
+ Value *default_value_; // if via .get( "key", default ), this was the default
+
+ // [start, limit) byte offsets in the source JSON text from which this Value
+ // was extracted.
+ size_t start_;
+ size_t limit_;
+};
+
+/** \brief Experimental and untested: represents an element of the "path" to
+ * access a node.
+ */
+class JSON_API PathArgument {
+public:
+ friend class Path;
+
+ PathArgument();
+ PathArgument(ArrayIndex index);
+ PathArgument(const char* key);
+ PathArgument(const std::string& key);
+
+private:
+ enum Kind {
+ kindNone = 0,
+ kindIndex,
+ kindKey
+ };
+ std::string key_;
+ ArrayIndex index_;
+ Kind kind_;
+};
+
+/** \brief Experimental and untested: represents a "path" to access a node.
+ *
+ * Syntax:
+ * - "." => root node
+ * - ".[n]" => elements at index 'n' of root node (an array value)
+ * - ".name" => member named 'name' of root node (an object value)
+ * - ".name1.name2.name3"
+ * - ".[0][1][2].name1[3]"
+ * - ".%" => member name is provided as parameter
+ * - ".[%]" => index is provied as parameter
+ */
+class JSON_API Path {
+public:
+ Path(const std::string& path,
+ const PathArgument& a1 = PathArgument(),
+ const PathArgument& a2 = PathArgument(),
+ const PathArgument& a3 = PathArgument(),
+ const PathArgument& a4 = PathArgument(),
+ const PathArgument& a5 = PathArgument());
+
+ const Value& resolve(const Value& root) const;
+ Value resolve(const Value& root, const Value& defaultValue) const;
+ /// Creates the "path" to access the specified node and returns a reference on
+ /// the node.
+ Value& make(Value& root) const;
+
+private:
+ typedef std::vector<const PathArgument*> InArgs;
+ typedef std::vector<PathArgument> Args;
+
+ void makePath(const std::string& path, const InArgs& in);
+ void addPathInArg(const std::string& path,
+ const InArgs& in,
+ InArgs::const_iterator& itInArg,
+ PathArgument::Kind kind);
+ void invalidPath(const std::string& path, int location);
+
+ Args args_;
+};
+
+/** \brief base class for Value iterators.
+ *
+ */
+class JSON_API ValueIteratorBase {
+public:
+ typedef std::bidirectional_iterator_tag iterator_category;
+ typedef unsigned int size_t;
+ typedef int difference_type;
+ typedef ValueIteratorBase SelfType;
+
+ bool operator==(const SelfType& other) const { return isEqual(other); }
+
+ bool operator!=(const SelfType& other) const { return !isEqual(other); }
+
+ difference_type operator-(const SelfType& other) const {
+ return other.computeDistance(*this);
+ }
+
+ /// Return either the index or the member name of the referenced value as a
+ /// Value.
+ Value key() const;
+
+ /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
+ UInt index() const;
+
+ /// Return the member name of the referenced Value, or "" if it is not an
+ /// objectValue.
+ /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
+ std::string name() const;
+
+ /// Return the member name of the referenced Value. "" if it is not an
+ /// objectValue.
+ /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
+ JSONCPP_DEPRECATED("Use `key = name();` instead.")
+ char const* memberName() const;
+ /// Return the member name of the referenced Value, or NULL if it is not an
+ /// objectValue.
+ /// \note Better version than memberName(). Allows embedded nulls.
+ char const* memberName(char const** end) const;
+
+protected:
+ Value& deref() const;
+
+ void increment();
+
+ void decrement();
+
+ difference_type computeDistance(const SelfType& other) const;
+
+ bool isEqual(const SelfType& other) const;
+
+ void copy(const SelfType& other);
+
+private:
+ Value::ObjectValues::iterator current_;
+ // Indicates that iterator is for a null value.
+ bool isNull_;
+
+public:
+ // For some reason, BORLAND needs these at the end, rather
+ // than earlier. No idea why.
+ ValueIteratorBase();
+ explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
+};
+
+/** \brief const iterator for object and array value.
+ *
+ */
+class JSON_API ValueConstIterator : public ValueIteratorBase {
+ friend class Value;
+
+public:
+ typedef const Value value_type;
+ //typedef unsigned int size_t;
+ //typedef int difference_type;
+ typedef const Value& reference;
+ typedef const Value* pointer;
+ typedef ValueConstIterator SelfType;
+
+ ValueConstIterator();
+ ValueConstIterator(ValueIterator const& other);
+
+private:
+/*! \internal Use by Value to create an iterator.
+ */
+ explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
+public:
+ SelfType& operator=(const ValueIteratorBase& other);
+
+ SelfType operator++(int) {
+ SelfType temp(*this);
+ ++*this;
+ return temp;
+ }
+
+ SelfType operator--(int) {
+ SelfType temp(*this);
+ --*this;
+ return temp;
+ }
+
+ SelfType& operator--() {
+ decrement();
+ return *this;
+ }
+
+ SelfType& operator++() {
+ increment();
+ return *this;
+ }
+
+ reference operator*() const { return deref(); }
+
+ pointer operator->() const { return &deref(); }
+};
+
+/** \brief Iterator for object and array value.
+ */
+class JSON_API ValueIterator : public ValueIteratorBase {
+ friend class Value;
+
+public:
+ typedef Value value_type;
+ typedef unsigned int size_t;
+ typedef int difference_type;
+ typedef Value& reference;
+ typedef Value* pointer;
+ typedef ValueIterator SelfType;
+
+ ValueIterator();
+ explicit ValueIterator(const ValueConstIterator& other);
+ ValueIterator(const ValueIterator& other);
+
+private:
+/*! \internal Use by Value to create an iterator.
+ */
+ explicit ValueIterator(const Value::ObjectValues::iterator& current);
+public:
+ SelfType& operator=(const SelfType& other);
+
+ SelfType operator++(int) {
+ SelfType temp(*this);
+ ++*this;
+ return temp;
+ }
+
+ SelfType operator--(int) {
+ SelfType temp(*this);
+ --*this;
+ return temp;
+ }
+
+ SelfType& operator--() {
+ decrement();
+ return *this;
+ }
+
+ SelfType& operator++() {
+ increment();
+ return *this;
+ }
+
+ reference operator*() const { return deref(); }
+
+ pointer operator->() const { return &deref(); }
+};
+
+} // namespace Json
+
+
+namespace std {
+/// Specialize std::swap() for Json::Value.
+template<>
+inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
+}
+
+
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(pop)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+#endif // CPPTL_JSON_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/value.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/reader.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_READER_H_INCLUDED
+#define CPPTL_JSON_READER_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "features.h"
+#include "value.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <deque>
+#include <iosfwd>
+#include <stack>
+#include <string>
+#include <istream>
+
+// Disable warning C4251: <data member>: <type> needs to have dll-interface to
+// be used by...
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(push)
+#pragma warning(disable : 4251)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+namespace Json {
+
+/** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
+ *Value.
+ *
+ * \deprecated Use CharReader and CharReaderBuilder.
+ */
+class JSON_API Reader {
+public:
+ typedef char Char;
+ typedef const Char* Location;
+
+ /** \brief An error tagged with where in the JSON text it was encountered.
+ *
+ * The offsets give the [start, limit) range of bytes within the text. Note
+ * that this is bytes, not codepoints.
+ *
+ */
+ struct StructuredError {
+ size_t offset_start;
+ size_t offset_limit;
+ std::string message;
+ };
+
+ /** \brief Constructs a Reader allowing all features
+ * for parsing.
+ */
+ Reader();
+
+ /** \brief Constructs a Reader allowing the specified feature set
+ * for parsing.
+ */
+ Reader(const Features& features);
+
+ /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
+ * document.
+ * \param document UTF-8 encoded string containing the document to read.
+ * \param root [out] Contains the root value of the document if it was
+ * successfully parsed.
+ * \param collectComments \c true to collect comment and allow writing them
+ * back during
+ * serialization, \c false to discard comments.
+ * This parameter is ignored if
+ * Features::allowComments_
+ * is \c false.
+ * \return \c true if the document was successfully parsed, \c false if an
+ * error occurred.
+ */
+ bool
+ parse(const std::string& document, Value& root, bool collectComments = true);
+
+ /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
+ document.
+ * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
+ document to read.
+ * \param endDoc Pointer on the end of the UTF-8 encoded string of the
+ document to read.
+ * Must be >= beginDoc.
+ * \param root [out] Contains the root value of the document if it was
+ * successfully parsed.
+ * \param collectComments \c true to collect comment and allow writing them
+ back during
+ * serialization, \c false to discard comments.
+ * This parameter is ignored if
+ Features::allowComments_
+ * is \c false.
+ * \return \c true if the document was successfully parsed, \c false if an
+ error occurred.
+ */
+ bool parse(const char* beginDoc,
+ const char* endDoc,
+ Value& root,
+ bool collectComments = true);
+
+ /// \brief Parse from input stream.
+ /// \see Json::operator>>(std::istream&, Json::Value&).
+ bool parse(std::istream& is, Value& root, bool collectComments = true);
+
+ /** \brief Returns a user friendly string that list errors in the parsed
+ * document.
+ * \return Formatted error message with the list of errors with their location
+ * in
+ * the parsed document. An empty string is returned if no error
+ * occurred
+ * during parsing.
+ * \deprecated Use getFormattedErrorMessages() instead (typo fix).
+ */
+ JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
+ std::string getFormatedErrorMessages() const;
+
+ /** \brief Returns a user friendly string that list errors in the parsed
+ * document.
+ * \return Formatted error message with the list of errors with their location
+ * in
+ * the parsed document. An empty string is returned if no error
+ * occurred
+ * during parsing.
+ */
+ std::string getFormattedErrorMessages() const;
+
+ /** \brief Returns a vector of structured erros encounted while parsing.
+ * \return A (possibly empty) vector of StructuredError objects. Currently
+ * only one error can be returned, but the caller should tolerate
+ * multiple
+ * errors. This can occur if the parser recovers from a non-fatal
+ * parse error and then encounters additional errors.
+ */
+ std::vector<StructuredError> getStructuredErrors() const;
+
+ /** \brief Add a semantic error message.
+ * \param value JSON Value location associated with the error
+ * \param message The error message.
+ * \return \c true if the error was successfully added, \c false if the
+ * Value offset exceeds the document size.
+ */
+ bool pushError(const Value& value, const std::string& message);
+
+ /** \brief Add a semantic error message with extra context.
+ * \param value JSON Value location associated with the error
+ * \param message The error message.
+ * \param extra Additional JSON Value location to contextualize the error
+ * \return \c true if the error was successfully added, \c false if either
+ * Value offset exceeds the document size.
+ */
+ bool pushError(const Value& value, const std::string& message, const Value& extra);
+
+ /** \brief Return whether there are any errors.
+ * \return \c true if there are no errors to report \c false if
+ * errors have occurred.
+ */
+ bool good() const;
+
+private:
+ enum TokenType {
+ tokenEndOfStream = 0,
+ tokenObjectBegin,
+ tokenObjectEnd,
+ tokenArrayBegin,
+ tokenArrayEnd,
+ tokenString,
+ tokenNumber,
+ tokenTrue,
+ tokenFalse,
+ tokenNull,
+ tokenArraySeparator,
+ tokenMemberSeparator,
+ tokenComment,
+ tokenError
+ };
+
+ class Token {
+ public:
+ TokenType type_;
+ Location start_;
+ Location end_;
+ };
+
+ class ErrorInfo {
+ public:
+ Token token_;
+ std::string message_;
+ Location extra_;
+ };
+
+ typedef std::deque<ErrorInfo> Errors;
+
+ bool readToken(Token& token);
+ void skipSpaces();
+ bool match(Location pattern, int patternLength);
+ bool readComment();
+ bool readCStyleComment();
+ bool readCppStyleComment();
+ bool readString();
+ void readNumber();
+ bool readValue();
+ bool readObject(Token& token);
+ bool readArray(Token& token);
+ bool decodeNumber(Token& token);
+ bool decodeNumber(Token& token, Value& decoded);
+ bool decodeString(Token& token);
+ bool decodeString(Token& token, std::string& decoded);
+ bool decodeDouble(Token& token);
+ bool decodeDouble(Token& token, Value& decoded);
+ bool decodeUnicodeCodePoint(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode);
+ bool decodeUnicodeEscapeSequence(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode);
+ bool addError(const std::string& message, Token& token, Location extra = 0);
+ bool recoverFromError(TokenType skipUntilToken);
+ bool addErrorAndRecover(const std::string& message,
+ Token& token,
+ TokenType skipUntilToken);
+ void skipUntilSpace();
+ Value& currentValue();
+ Char getNextChar();
+ void
+ getLocationLineAndColumn(Location location, int& line, int& column) const;
+ std::string getLocationLineAndColumn(Location location) const;
+ std::string getLocationSnippet(Location location) const;
+ void addComment(Location begin, Location end, CommentPlacement placement);
+ void skipCommentTokens(Token& token);
+
+ typedef std::stack<Value*> Nodes;
+ Nodes nodes_;
+ Errors errors_;
+ std::string document_;
+ Location begin_;
+ Location end_;
+ Location current_;
+ Location lastValueEnd_;
+ Value* lastValue_;
+ std::string commentsBefore_;
+ Features features_;
+ bool collectComments_;
+}; // Reader
+
+/** Interface for reading JSON from a char array.
+ */
+class JSON_API CharReader {
+public:
+ virtual ~CharReader() {}
+ /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
+ document.
+ * The document must be a UTF-8 encoded string containing the document to read.
+ *
+ * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
+ document to read.
+ * \param endDoc Pointer on the end of the UTF-8 encoded string of the
+ document to read.
+ * Must be >= beginDoc.
+ * \param root [out] Contains the root value of the document if it was
+ * successfully parsed.
+ * \param errs [out] Formatted error messages (if not NULL)
+ * a user friendly string that lists errors in the parsed
+ * document.
+ * \return \c true if the document was successfully parsed, \c false if an
+ error occurred.
+ */
+ virtual bool parse(
+ char const* beginDoc, char const* endDoc,
+ Value* root, std::string* errs) = 0;
+
+ class JSON_API Factory {
+ public:
+ virtual ~Factory() {}
+ /** \brief Allocate a CharReader via operator new().
+ * \throw std::exception if something goes wrong (e.g. invalid settings)
+ */
+ virtual CharReader* newCharReader() const = 0;
+ }; // Factory
+}; // CharReader
+
+/** \brief Build a CharReader implementation.
+
+Usage:
+\code
+ using namespace Json;
+ CharReaderBuilder builder;
+ builder["collectComments"] = false;
+ Value value;
+ std::string errs;
+ bool ok = parseFromStream(builder, std::cin, &value, &errs);
+\endcode
+*/
+class JSON_API CharReaderBuilder : public CharReader::Factory {
+public:
+ // Note: We use a Json::Value so that we can add data-members to this class
+ // without a major version bump.
+ /** Configuration of this builder.
+ These are case-sensitive.
+ Available settings (case-sensitive):
+ - `"collectComments": false or true`
+ - true to collect comment and allow writing them
+ back during serialization, false to discard comments.
+ This parameter is ignored if allowComments is false.
+ - `"allowComments": false or true`
+ - true if comments are allowed.
+ - `"strictRoot": false or true`
+ - true if root must be either an array or an object value
+ - `"allowDroppedNullPlaceholders": false or true`
+ - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
+ - `"allowNumericKeys": false or true`
+ - true if numeric object keys are allowed.
+ - `"allowSingleQuotes": false or true`
+ - true if '' are allowed for strings (both keys and values)
+ - `"stackLimit": integer`
+ - Exceeding stackLimit (recursive depth of `readValue()`) will
+ cause an exception.
+ - This is a security issue (seg-faults caused by deeply nested JSON),
+ so the default is low.
+ - `"failIfExtra": false or true`
+ - If true, `parse()` returns false when extra non-whitespace trails
+ the JSON value in the input string.
+ - `"rejectDupKeys": false or true`
+ - If true, `parse()` returns false when a key is duplicated within an object.
+ - `"allowSpecialFloats": false or true`
+ - If true, special float values (NaNs and infinities) are allowed
+ and their values are lossfree restorable.
+
+ You can examine 'settings_` yourself
+ to see the defaults. You can also write and read them just like any
+ JSON Value.
+ \sa setDefaults()
+ */
+ Json::Value settings_;
+
+ CharReaderBuilder();
+ ~CharReaderBuilder();
+
+ CharReader* newCharReader() const;
+
+ /** \return true if 'settings' are legal and consistent;
+ * otherwise, indicate bad settings via 'invalid'.
+ */
+ bool validate(Json::Value* invalid) const;
+
+ /** A simple way to update a specific setting.
+ */
+ Value& operator[](std::string key);
+
+ /** Called by ctor, but you can use this to reset settings_.
+ * \pre 'settings' != NULL (but Json::null is fine)
+ * \remark Defaults:
+ * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
+ */
+ static void setDefaults(Json::Value* settings);
+ /** Same as old Features::strictMode().
+ * \pre 'settings' != NULL (but Json::null is fine)
+ * \remark Defaults:
+ * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
+ */
+ static void strictMode(Json::Value* settings);
+};
+
+/** Consume entire stream and use its begin/end.
+ * Someday we might have a real StreamReader, but for now this
+ * is convenient.
+ */
+bool JSON_API parseFromStream(
+ CharReader::Factory const&,
+ std::istream&,
+ Value* root, std::string* errs);
+
+/** \brief Read from 'sin' into 'root'.
+
+ Always keep comments from the input JSON.
+
+ This can be used to read a file into a particular sub-object.
+ For example:
+ \code
+ Json::Value root;
+ cin >> root["dir"]["file"];
+ cout << root;
+ \endcode
+ Result:
+ \verbatim
+ {
+ "dir": {
+ "file": {
+ // The input stream JSON would be nested here.
+ }
+ }
+ }
+ \endverbatim
+ \throw std::exception on parse error.
+ \see Json::operator<<()
+*/
+JSON_API std::istream& operator>>(std::istream&, Value&);
+
+} // namespace Json
+
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(pop)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+#endif // CPPTL_JSON_READER_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/reader.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/writer.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_WRITER_H_INCLUDED
+#define JSON_WRITER_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "value.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <vector>
+#include <string>
+#include <ostream>
+
+// Disable warning C4251: <data member>: <type> needs to have dll-interface to
+// be used by...
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(push)
+#pragma warning(disable : 4251)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+namespace Json {
+
+class Value;
+
+/**
+
+Usage:
+\code
+ using namespace Json;
+ void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
+ std::unique_ptr<StreamWriter> const writer(
+ factory.newStreamWriter());
+ writer->write(value, &std::cout);
+ std::cout << std::endl; // add lf and flush
+ }
+\endcode
+*/
+class JSON_API StreamWriter {
+protected:
+ std::ostream* sout_; // not owned; will not delete
+public:
+ StreamWriter();
+ virtual ~StreamWriter();
+ /** Write Value into document as configured in sub-class.
+ Do not take ownership of sout, but maintain a reference during function.
+ \pre sout != NULL
+ \return zero on success (For now, we always return zero, so check the stream instead.)
+ \throw std::exception possibly, depending on configuration
+ */
+ virtual int write(Value const& root, std::ostream* sout) = 0;
+
+ /** \brief A simple abstract factory.
+ */
+ class JSON_API Factory {
+ public:
+ virtual ~Factory();
+ /** \brief Allocate a CharReader via operator new().
+ * \throw std::exception if something goes wrong (e.g. invalid settings)
+ */
+ virtual StreamWriter* newStreamWriter() const = 0;
+ }; // Factory
+}; // StreamWriter
+
+/** \brief Write into stringstream, then return string, for convenience.
+ * A StreamWriter will be created from the factory, used, and then deleted.
+ */
+std::string JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
+
+
+/** \brief Build a StreamWriter implementation.
+
+Usage:
+\code
+ using namespace Json;
+ Value value = ...;
+ StreamWriterBuilder builder;
+ builder["commentStyle"] = "None";
+ builder["indentation"] = " "; // or whatever you like
+ std::unique_ptr<Json::StreamWriter> writer(
+ builder.newStreamWriter());
+ writer->write(value, &std::cout);
+ std::cout << std::endl; // add lf and flush
+\endcode
+*/
+class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
+public:
+ // Note: We use a Json::Value so that we can add data-members to this class
+ // without a major version bump.
+ /** Configuration of this builder.
+ Available settings (case-sensitive):
+ - "commentStyle": "None" or "All"
+ - "indentation": "<anything>"
+ - "enableYAMLCompatibility": false or true
+ - slightly change the whitespace around colons
+ - "dropNullPlaceholders": false or true
+ - Drop the "null" string from the writer's output for nullValues.
+ Strictly speaking, this is not valid JSON. But when the output is being
+ fed to a browser's Javascript, it makes for smaller output and the
+ browser can handle the output just fine.
+ - "useSpecialFloats": false or true
+ - If true, outputs non-finite floating point values in the following way:
+ NaN values as "NaN", positive infinity as "Infinity", and negative infinity
+ as "-Infinity".
+
+ You can examine 'settings_` yourself
+ to see the defaults. You can also write and read them just like any
+ JSON Value.
+ \sa setDefaults()
+ */
+ Json::Value settings_;
+
+ StreamWriterBuilder();
+ ~StreamWriterBuilder();
+
+ /**
+ * \throw std::exception if something goes wrong (e.g. invalid settings)
+ */
+ StreamWriter* newStreamWriter() const;
+
+ /** \return true if 'settings' are legal and consistent;
+ * otherwise, indicate bad settings via 'invalid'.
+ */
+ bool validate(Json::Value* invalid) const;
+ /** A simple way to update a specific setting.
+ */
+ Value& operator[](std::string key);
+
+ /** Called by ctor, but you can use this to reset settings_.
+ * \pre 'settings' != NULL (but Json::null is fine)
+ * \remark Defaults:
+ * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
+ */
+ static void setDefaults(Json::Value* settings);
+};
+
+/** \brief Abstract class for writers.
+ * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
+ */
+class JSON_API Writer {
+public:
+ virtual ~Writer();
+
+ virtual std::string write(const Value& root) = 0;
+};
+
+/** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
+ *without formatting (not human friendly).
+ *
+ * The JSON document is written in a single line. It is not intended for 'human'
+ *consumption,
+ * but may be usefull to support feature such as RPC where bandwith is limited.
+ * \sa Reader, Value
+ * \deprecated Use StreamWriterBuilder.
+ */
+class JSON_API FastWriter : public Writer {
+
+public:
+ FastWriter();
+ ~FastWriter() {}
+
+ void enableYAMLCompatibility();
+
+ /** \brief Drop the "null" string from the writer's output for nullValues.
+ * Strictly speaking, this is not valid JSON. But when the output is being
+ * fed to a browser's Javascript, it makes for smaller output and the
+ * browser can handle the output just fine.
+ */
+ void dropNullPlaceholders();
+
+ void omitEndingLineFeed();
+
+public: // overridden from Writer
+ std::string write(const Value& root);
+
+private:
+ void writeValue(const Value& value);
+
+ std::string document_;
+ bool yamlCompatiblityEnabled_;
+ bool dropNullPlaceholders_;
+ bool omitEndingLineFeed_;
+};
+
+/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
+ *human friendly way.
+ *
+ * The rules for line break and indent are as follow:
+ * - Object value:
+ * - if empty then print {} without indent and line break
+ * - if not empty the print '{', line break & indent, print one value per
+ *line
+ * and then unindent and line break and print '}'.
+ * - Array value:
+ * - if empty then print [] without indent and line break
+ * - if the array contains no object value, empty array or some other value
+ *types,
+ * and all the values fit on one lines, then print the array on a single
+ *line.
+ * - otherwise, it the values do not fit on one line, or the array contains
+ * object or non empty array, then print one value per line.
+ *
+ * If the Value have comments then they are outputed according to their
+ *#CommentPlacement.
+ *
+ * \sa Reader, Value, Value::setComment()
+ * \deprecated Use StreamWriterBuilder.
+ */
+class JSON_API StyledWriter : public Writer {
+public:
+ StyledWriter();
+ ~StyledWriter() {}
+
+public: // overridden from Writer
+ /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
+ * \param root Value to serialize.
+ * \return String containing the JSON document that represents the root value.
+ */
+ std::string write(const Value& root);
+
+private:
+ void writeValue(const Value& value);
+ void writeArrayValue(const Value& value);
+ bool isMultineArray(const Value& value);
+ void pushValue(const std::string& value);
+ void writeIndent();
+ void writeWithIndent(const std::string& value);
+ void indent();
+ void unindent();
+ void writeCommentBeforeValue(const Value& root);
+ void writeCommentAfterValueOnSameLine(const Value& root);
+ bool hasCommentForValue(const Value& value);
+ static std::string normalizeEOL(const std::string& text);
+
+ typedef std::vector<std::string> ChildValues;
+
+ ChildValues childValues_;
+ std::string document_;
+ std::string indentString_;
+ int rightMargin_;
+ int indentSize_;
+ bool addChildValues_;
+};
+
+/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
+ human friendly way,
+ to a stream rather than to a string.
+ *
+ * The rules for line break and indent are as follow:
+ * - Object value:
+ * - if empty then print {} without indent and line break
+ * - if not empty the print '{', line break & indent, print one value per
+ line
+ * and then unindent and line break and print '}'.
+ * - Array value:
+ * - if empty then print [] without indent and line break
+ * - if the array contains no object value, empty array or some other value
+ types,
+ * and all the values fit on one lines, then print the array on a single
+ line.
+ * - otherwise, it the values do not fit on one line, or the array contains
+ * object or non empty array, then print one value per line.
+ *
+ * If the Value have comments then they are outputed according to their
+ #CommentPlacement.
+ *
+ * \param indentation Each level will be indented by this amount extra.
+ * \sa Reader, Value, Value::setComment()
+ * \deprecated Use StreamWriterBuilder.
+ */
+class JSON_API StyledStreamWriter {
+public:
+ StyledStreamWriter(std::string indentation = "\t");
+ ~StyledStreamWriter() {}
+
+public:
+ /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
+ * \param out Stream to write to. (Can be ostringstream, e.g.)
+ * \param root Value to serialize.
+ * \note There is no point in deriving from Writer, since write() should not
+ * return a value.
+ */
+ void write(std::ostream& out, const Value& root);
+
+private:
+ void writeValue(const Value& value);
+ void writeArrayValue(const Value& value);
+ bool isMultineArray(const Value& value);
+ void pushValue(const std::string& value);
+ void writeIndent();
+ void writeWithIndent(const std::string& value);
+ void indent();
+ void unindent();
+ void writeCommentBeforeValue(const Value& root);
+ void writeCommentAfterValueOnSameLine(const Value& root);
+ bool hasCommentForValue(const Value& value);
+ static std::string normalizeEOL(const std::string& text);
+
+ typedef std::vector<std::string> ChildValues;
+
+ ChildValues childValues_;
+ std::ostream* document_;
+ std::string indentString_;
+ int rightMargin_;
+ std::string indentation_;
+ bool addChildValues_ : 1;
+ bool indented_ : 1;
+};
+
+#if defined(JSON_HAS_INT64)
+std::string JSON_API valueToString(Int value);
+std::string JSON_API valueToString(UInt value);
+#endif // if defined(JSON_HAS_INT64)
+std::string JSON_API valueToString(LargestInt value);
+std::string JSON_API valueToString(LargestUInt value);
+std::string JSON_API valueToString(double value);
+std::string JSON_API valueToString(bool value);
+std::string JSON_API valueToQuotedString(const char* value);
+
+/// \brief Output using the StyledStreamWriter.
+/// \see Json::operator>>()
+JSON_API std::ostream& operator<<(std::ostream&, const Value& root);
+
+} // namespace Json
+
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(pop)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+#endif // JSON_WRITER_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/writer.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/assertions.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
+#define CPPTL_JSON_ASSERTIONS_H_INCLUDED
+
+#include <stdlib.h>
+#include <sstream>
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "config.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+/** It should not be possible for a maliciously designed file to
+ * cause an abort() or seg-fault, so these macros are used only
+ * for pre-condition violations and internal logic errors.
+ */
+#if JSON_USE_EXCEPTION
+
+// @todo <= add detail about condition in exception
+# define JSON_ASSERT(condition) \
+ {if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
+
+# define JSON_FAIL_MESSAGE(message) \
+ { \
+ std::ostringstream oss; oss << message; \
+ Json::throwLogicError(oss.str()); \
+ abort(); \
+ }
+
+#else // JSON_USE_EXCEPTION
+
+# define JSON_ASSERT(condition) assert(condition)
+
+// The call to assert() will show the failure message in debug builds. In
+// release builds we abort, for a core-dump or debugger.
+# define JSON_FAIL_MESSAGE(message) \
+ { \
+ std::ostringstream oss; oss << message; \
+ assert(false && oss.str().c_str()); \
+ abort(); \
+ }
+
+
+#endif
+
+#define JSON_ASSERT_MESSAGE(condition, message) \
+ if (!(condition)) { \
+ JSON_FAIL_MESSAGE(message); \
+ }
+
+#endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/assertions.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+#endif //ifndef JSON_AMALGATED_H_INCLUDED
diff --git a/src/jsoncpp.cpp b/src/jsoncpp.cpp
new file mode 100644
index 0000000..e67d353
--- /dev/null
+++ b/src/jsoncpp.cpp
@@ -0,0 +1,5266 @@
+/// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/).
+/// It is intended to be used with #include "json/json.h"
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+/*
+The JsonCpp library's source code, including accompanying documentation,
+tests and demonstration applications, are licensed under the following
+conditions...
+
+The author (Baptiste Lepilleur) explicitly disclaims copyright in all
+jurisdictions which recognize such a disclaimer. In such jurisdictions,
+this software is released into the Public Domain.
+
+In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
+2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
+released under the terms of the MIT License (see below).
+
+In jurisdictions which recognize Public Domain property, the user of this
+software may choose to accept it either as 1) Public Domain, 2) under the
+conditions of the MIT License (see below), or 3) under the terms of dual
+Public Domain/MIT License conditions described here, as they choose.
+
+The MIT License is about as close to Public Domain as a license can get, and is
+described in clear, concise terms at:
+
+ http://en.wikipedia.org/wiki/MIT_License
+
+The full text of the MIT License follows:
+
+========================================================================
+Copyright (c) 2007-2010 Baptiste Lepilleur
+
+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.
+========================================================================
+(END LICENSE TEXT)
+
+The MIT license is compatible with both the GPL and commercial
+software, affording one all of the rights of Public Domain with the
+minor nuisance of being required to keep the above copyright notice
+and license text in the source code. Note also that by accepting the
+Public Domain "license" you can re-license your copy using whatever
+license you like.
+
+*/
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+#include "json/json.h"
+
+#ifndef JSON_IS_AMALGAMATION
+#error "Compile with -I PATH_TO_JSON_DIRECTORY"
+#endif
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_tool.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
+#define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
+
+/* This header provides common string manipulation support, such as UTF-8,
+ * portable conversion from/to string...
+ *
+ * It is an internal header that must not be exposed.
+ */
+
+namespace Json {
+
+/// Converts a unicode code-point to UTF-8.
+static inline std::string codePointToUTF8(unsigned int cp) {
+ std::string result;
+
+ // based on description from http://en.wikipedia.org/wiki/UTF-8
+
+ if (cp <= 0x7f) {
+ result.resize(1);
+ result[0] = static_cast<char>(cp);
+ } else if (cp <= 0x7FF) {
+ result.resize(2);
+ result[1] = static_cast<char>(0x80 | (0x3f & cp));
+ result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
+ } else if (cp <= 0xFFFF) {
+ result.resize(3);
+ result[2] = static_cast<char>(0x80 | (0x3f & cp));
+ result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
+ result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12)));
+ } else if (cp <= 0x10FFFF) {
+ result.resize(4);
+ result[3] = static_cast<char>(0x80 | (0x3f & cp));
+ result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
+ result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
+ result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
+ }
+
+ return result;
+}
+
+/// Returns true if ch is a control character (in range [1,31]).
+static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; }
+
+enum {
+ /// Constant that specify the size of the buffer that must be passed to
+ /// uintToString.
+ uintToStringBufferSize = 3 * sizeof(LargestUInt) + 1
+};
+
+// Defines a char buffer for use with uintToString().
+typedef char UIntToStringBuffer[uintToStringBufferSize];
+
+/** Converts an unsigned integer to string.
+ * @param value Unsigned interger to convert to string
+ * @param current Input/Output string buffer.
+ * Must have at least uintToStringBufferSize chars free.
+ */
+static inline void uintToString(LargestUInt value, char*& current) {
+ *--current = 0;
+ do {
+ *--current = static_cast<signed char>(value % 10U + static_cast<unsigned>('0'));
+ value /= 10;
+ } while (value != 0);
+}
+
+/** Change ',' to '.' everywhere in buffer.
+ *
+ * We had a sophisticated way, but it did not work in WinCE.
+ * @see https://github.com/open-source-parsers/jsoncpp/pull/9
+ */
+static inline void fixNumericLocale(char* begin, char* end) {
+ while (begin < end) {
+ if (*begin == ',') {
+ *begin = '.';
+ }
+ ++begin;
+ }
+}
+
+} // namespace Json {
+
+#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: src/lib_json/json_tool.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_reader.cpp
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2011 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include <json/assertions.h>
+#include <json/reader.h>
+#include <json/value.h>
+#include "json_tool.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <utility>
+#include <cstdio>
+#include <cassert>
+#include <cstring>
+#include <istream>
+#include <sstream>
+#include <memory>
+#include <set>
+#include <limits>
+
+#if defined(_MSC_VER)
+#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
+#define snprintf sprintf_s
+#elif _MSC_VER >= 1900 // VC++ 14.0 and above
+#define snprintf std::snprintf
+#else
+#define snprintf _snprintf
+#endif
+#elif defined(__ANDROID__) || defined(__QNXNTO__)
+#define snprintf snprintf
+#elif __cplusplus >= 201103L
+#define snprintf std::snprintf
+#endif
+
+#if defined(__QNXNTO__)
+#define sscanf std::sscanf
+#endif
+
+#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
+// Disable warning about strdup being deprecated.
+#pragma warning(disable : 4996)
+#endif
+
+static int const stackLimit_g = 1000;
+static int stackDepth_g = 0; // see readValue()
+
+namespace Json {
+
+#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
+typedef std::unique_ptr<CharReader> CharReaderPtr;
+#else
+typedef std::auto_ptr<CharReader> CharReaderPtr;
+#endif
+
+// Implementation of class Features
+// ////////////////////////////////
+
+Features::Features()
+ : allowComments_(true), strictRoot_(false),
+ allowDroppedNullPlaceholders_(false), allowNumericKeys_(false) {}
+
+Features Features::all() { return Features(); }
+
+Features Features::strictMode() {
+ Features features;
+ features.allowComments_ = false;
+ features.strictRoot_ = true;
+ features.allowDroppedNullPlaceholders_ = false;
+ features.allowNumericKeys_ = false;
+ return features;
+}
+
+// Implementation of class Reader
+// ////////////////////////////////
+
+static bool containsNewLine(Reader::Location begin, Reader::Location end) {
+ for (; begin < end; ++begin)
+ if (*begin == '\n' || *begin == '\r')
+ return true;
+ return false;
+}
+
+// Class Reader
+// //////////////////////////////////////////////////////////////////
+
+Reader::Reader()
+ : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
+ lastValue_(), commentsBefore_(), features_(Features::all()),
+ collectComments_() {}
+
+Reader::Reader(const Features& features)
+ : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
+ lastValue_(), commentsBefore_(), features_(features), collectComments_() {
+}
+
+bool
+Reader::parse(const std::string& document, Value& root, bool collectComments) {
+ document_ = document;
+ const char* begin = document_.c_str();
+ const char* end = begin + document_.length();
+ return parse(begin, end, root, collectComments);
+}
+
+bool Reader::parse(std::istream& sin, Value& root, bool collectComments) {
+ // std::istream_iterator<char> begin(sin);
+ // std::istream_iterator<char> end;
+ // Those would allow streamed input from a file, if parse() were a
+ // template function.
+
+ // Since std::string is reference-counted, this at least does not
+ // create an extra copy.
+ std::string doc;
+ std::getline(sin, doc, (char)EOF);
+ return parse(doc, root, collectComments);
+}
+
+bool Reader::parse(const char* beginDoc,
+ const char* endDoc,
+ Value& root,
+ bool collectComments) {
+ if (!features_.allowComments_) {
+ collectComments = false;
+ }
+
+ begin_ = beginDoc;
+ end_ = endDoc;
+ collectComments_ = collectComments;
+ current_ = begin_;
+ lastValueEnd_ = 0;
+ lastValue_ = 0;
+ commentsBefore_ = "";
+ errors_.clear();
+ while (!nodes_.empty())
+ nodes_.pop();
+ nodes_.push(&root);
+
+ stackDepth_g = 0; // Yes, this is bad coding, but options are limited.
+ bool successful = readValue();
+ Token token;
+ skipCommentTokens(token);
+ if (collectComments_ && !commentsBefore_.empty())
+ root.setComment(commentsBefore_, commentAfter);
+ if (features_.strictRoot_) {
+ if (!root.isArray() && !root.isObject()) {
+ // Set error location to start of doc, ideally should be first token found
+ // in doc
+ token.type_ = tokenError;
+ token.start_ = beginDoc;
+ token.end_ = endDoc;
+ addError(
+ "A valid JSON document must be either an array or an object value.",
+ token);
+ return false;
+ }
+ }
+ return successful;
+}
+
+bool Reader::readValue() {
+ // This is a non-reentrant way to support a stackLimit. Terrible!
+ // But this deprecated class has a security problem: Bad input can
+ // cause a seg-fault. This seems like a fair, binary-compatible way
+ // to prevent the problem.
+ if (stackDepth_g >= stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue().");
+ ++stackDepth_g;
+
+ Token token;
+ skipCommentTokens(token);
+ bool successful = true;
+
+ if (collectComments_ && !commentsBefore_.empty()) {
+ currentValue().setComment(commentsBefore_, commentBefore);
+ commentsBefore_ = "";
+ }
+
+ switch (token.type_) {
+ case tokenObjectBegin:
+ successful = readObject(token);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ case tokenArrayBegin:
+ successful = readArray(token);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ case tokenNumber:
+ successful = decodeNumber(token);
+ break;
+ case tokenString:
+ successful = decodeString(token);
+ break;
+ case tokenTrue:
+ {
+ Value v(true);
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenFalse:
+ {
+ Value v(false);
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenNull:
+ {
+ Value v;
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenArraySeparator:
+ case tokenObjectEnd:
+ case tokenArrayEnd:
+ if (features_.allowDroppedNullPlaceholders_) {
+ // "Un-read" the current token and mark the current value as a null
+ // token.
+ current_--;
+ Value v;
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(current_ - begin_ - 1);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ } // Else, fall through...
+ default:
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return addError("Syntax error: value, object or array expected.", token);
+ }
+
+ if (collectComments_) {
+ lastValueEnd_ = current_;
+ lastValue_ = &currentValue();
+ }
+
+ --stackDepth_g;
+ return successful;
+}
+
+void Reader::skipCommentTokens(Token& token) {
+ if (features_.allowComments_) {
+ do {
+ readToken(token);
+ } while (token.type_ == tokenComment);
+ } else {
+ readToken(token);
+ }
+}
+
+bool Reader::readToken(Token& token) {
+ skipSpaces();
+ token.start_ = current_;
+ Char c = getNextChar();
+ bool ok = true;
+ switch (c) {
+ case '{':
+ token.type_ = tokenObjectBegin;
+ break;
+ case '}':
+ token.type_ = tokenObjectEnd;
+ break;
+ case '[':
+ token.type_ = tokenArrayBegin;
+ break;
+ case ']':
+ token.type_ = tokenArrayEnd;
+ break;
+ case '"':
+ token.type_ = tokenString;
+ ok = readString();
+ break;
+ case '/':
+ token.type_ = tokenComment;
+ ok = readComment();
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '-':
+ token.type_ = tokenNumber;
+ readNumber();
+ break;
+ case 't':
+ token.type_ = tokenTrue;
+ ok = match("rue", 3);
+ break;
+ case 'f':
+ token.type_ = tokenFalse;
+ ok = match("alse", 4);
+ break;
+ case 'n':
+ token.type_ = tokenNull;
+ ok = match("ull", 3);
+ break;
+ case ',':
+ token.type_ = tokenArraySeparator;
+ break;
+ case ':':
+ token.type_ = tokenMemberSeparator;
+ break;
+ case 0:
+ token.type_ = tokenEndOfStream;
+ break;
+ default:
+ ok = false;
+ break;
+ }
+ if (!ok)
+ token.type_ = tokenError;
+ token.end_ = current_;
+ return true;
+}
+
+void Reader::skipSpaces() {
+ while (current_ != end_) {
+ Char c = *current_;
+ if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
+ ++current_;
+ else
+ break;
+ }
+}
+
+bool Reader::match(Location pattern, int patternLength) {
+ if (end_ - current_ < patternLength)
+ return false;
+ int index = patternLength;
+ while (index--)
+ if (current_[index] != pattern[index])
+ return false;
+ current_ += patternLength;
+ return true;
+}
+
+bool Reader::readComment() {
+ Location commentBegin = current_ - 1;
+ Char c = getNextChar();
+ bool successful = false;
+ if (c == '*')
+ successful = readCStyleComment();
+ else if (c == '/')
+ successful = readCppStyleComment();
+ if (!successful)
+ return false;
+
+ if (collectComments_) {
+ CommentPlacement placement = commentBefore;
+ if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
+ if (c != '*' || !containsNewLine(commentBegin, current_))
+ placement = commentAfterOnSameLine;
+ }
+
+ addComment(commentBegin, current_, placement);
+ }
+ return true;
+}
+
+static std::string normalizeEOL(Reader::Location begin, Reader::Location end) {
+ std::string normalized;
+ normalized.reserve(end - begin);
+ Reader::Location current = begin;
+ while (current != end) {
+ char c = *current++;
+ if (c == '\r') {
+ if (current != end && *current == '\n')
+ // convert dos EOL
+ ++current;
+ // convert Mac EOL
+ normalized += '\n';
+ } else {
+ normalized += c;
+ }
+ }
+ return normalized;
+}
+
+void
+Reader::addComment(Location begin, Location end, CommentPlacement placement) {
+ assert(collectComments_);
+ const std::string& normalized = normalizeEOL(begin, end);
+ if (placement == commentAfterOnSameLine) {
+ assert(lastValue_ != 0);
+ lastValue_->setComment(normalized, placement);
+ } else {
+ commentsBefore_ += normalized;
+ }
+}
+
+bool Reader::readCStyleComment() {
+ while (current_ != end_) {
+ Char c = getNextChar();
+ if (c == '*' && *current_ == '/')
+ break;
+ }
+ return getNextChar() == '/';
+}
+
+bool Reader::readCppStyleComment() {
+ while (current_ != end_) {
+ Char c = getNextChar();
+ if (c == '\n')
+ break;
+ if (c == '\r') {
+ // Consume DOS EOL. It will be normalized in addComment.
+ if (current_ != end_ && *current_ == '\n')
+ getNextChar();
+ // Break on Moc OS 9 EOL.
+ break;
+ }
+ }
+ return true;
+}
+
+void Reader::readNumber() {
+ const char *p = current_;
+ char c = '0'; // stopgap for already consumed character
+ // integral part
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ // fractional part
+ if (c == '.') {
+ c = (current_ = p) < end_ ? *p++ : 0;
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ }
+ // exponential part
+ if (c == 'e' || c == 'E') {
+ c = (current_ = p) < end_ ? *p++ : 0;
+ if (c == '+' || c == '-')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ }
+}
+
+bool Reader::readString() {
+ Char c = 0;
+ while (current_ != end_) {
+ c = getNextChar();
+ if (c == '\\')
+ getNextChar();
+ else if (c == '"')
+ break;
+ }
+ return c == '"';
+}
+
+bool Reader::readObject(Token& tokenStart) {
+ Token tokenName;
+ std::string name;
+ Value init(objectValue);
+ currentValue().swapPayload(init);
+ currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ while (readToken(tokenName)) {
+ bool initialTokenOk = true;
+ while (tokenName.type_ == tokenComment && initialTokenOk)
+ initialTokenOk = readToken(tokenName);
+ if (!initialTokenOk)
+ break;
+ if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
+ return true;
+ name = "";
+ if (tokenName.type_ == tokenString) {
+ if (!decodeString(tokenName, name))
+ return recoverFromError(tokenObjectEnd);
+ } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
+ Value numberName;
+ if (!decodeNumber(tokenName, numberName))
+ return recoverFromError(tokenObjectEnd);
+ name = numberName.asString();
+ } else {
+ break;
+ }
+
+ Token colon;
+ if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
+ return addErrorAndRecover(
+ "Missing ':' after object member name", colon, tokenObjectEnd);
+ }
+ Value& value = currentValue()[name];
+ nodes_.push(&value);
+ bool ok = readValue();
+ nodes_.pop();
+ if (!ok) // error already set
+ return recoverFromError(tokenObjectEnd);
+
+ Token comma;
+ if (!readToken(comma) ||
+ (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
+ comma.type_ != tokenComment)) {
+ return addErrorAndRecover(
+ "Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
+ }
+ bool finalizeTokenOk = true;
+ while (comma.type_ == tokenComment && finalizeTokenOk)
+ finalizeTokenOk = readToken(comma);
+ if (comma.type_ == tokenObjectEnd)
+ return true;
+ }
+ return addErrorAndRecover(
+ "Missing '}' or object member name", tokenName, tokenObjectEnd);
+}
+
+bool Reader::readArray(Token& tokenStart) {
+ Value init(arrayValue);
+ currentValue().swapPayload(init);
+ currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ skipSpaces();
+ if (*current_ == ']') // empty array
+ {
+ Token endArray;
+ readToken(endArray);
+ return true;
+ }
+ int index = 0;
+ for (;;) {
+ Value& value = currentValue()[index++];
+ nodes_.push(&value);
+ bool ok = readValue();
+ nodes_.pop();
+ if (!ok) // error already set
+ return recoverFromError(tokenArrayEnd);
+
+ Token token;
+ // Accept Comment after last item in the array.
+ ok = readToken(token);
+ while (token.type_ == tokenComment && ok) {
+ ok = readToken(token);
+ }
+ bool badTokenType =
+ (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
+ if (!ok || badTokenType) {
+ return addErrorAndRecover(
+ "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
+ }
+ if (token.type_ == tokenArrayEnd)
+ break;
+ }
+ return true;
+}
+
+bool Reader::decodeNumber(Token& token) {
+ Value decoded;
+ if (!decodeNumber(token, decoded))
+ return false;
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool Reader::decodeNumber(Token& token, Value& decoded) {
+ // Attempts to parse the number as an integer. If the number is
+ // larger than the maximum supported value of an integer then
+ // we decode the number as a double.
+ Location current = token.start_;
+ bool isNegative = *current == '-';
+ if (isNegative)
+ ++current;
+ // TODO: Help the compiler do the div and mod at compile time or get rid of them.
+ Value::LargestUInt maxIntegerValue =
+ isNegative ? Value::LargestUInt(Value::maxLargestInt) + 1
+ : Value::maxLargestUInt;
+ Value::LargestUInt threshold = maxIntegerValue / 10;
+ Value::LargestUInt value = 0;
+ while (current < token.end_) {
+ Char c = *current++;
+ if (c < '0' || c > '9')
+ return decodeDouble(token, decoded);
+ Value::UInt digit(c - '0');
+ if (value >= threshold) {
+ // We've hit or exceeded the max value divided by 10 (rounded down). If
+ // a) we've only just touched the limit, b) this is the last digit, and
+ // c) it's small enough to fit in that rounding delta, we're okay.
+ // Otherwise treat this number as a double to avoid overflow.
+ if (value > threshold || current != token.end_ ||
+ digit > maxIntegerValue % 10) {
+ return decodeDouble(token, decoded);
+ }
+ }
+ value = value * 10 + digit;
+ }
+ if (isNegative && value == maxIntegerValue)
+ decoded = Value::minLargestInt;
+ else if (isNegative)
+ decoded = -Value::LargestInt(value);
+ else if (value <= Value::LargestUInt(Value::maxInt))
+ decoded = Value::LargestInt(value);
+ else
+ decoded = value;
+ return true;
+}
+
+bool Reader::decodeDouble(Token& token) {
+ Value decoded;
+ if (!decodeDouble(token, decoded))
+ return false;
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool Reader::decodeDouble(Token& token, Value& decoded) {
+ double value = 0;
+ std::string buffer(token.start_, token.end_);
+ std::istringstream is(buffer);
+ if (!(is >> value))
+ return addError("'" + std::string(token.start_, token.end_) +
+ "' is not a number.",
+ token);
+ decoded = value;
+ return true;
+}
+
+bool Reader::decodeString(Token& token) {
+ std::string decoded_string;
+ if (!decodeString(token, decoded_string))
+ return false;
+ Value decoded(decoded_string);
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool Reader::decodeString(Token& token, std::string& decoded) {
+ decoded.reserve(token.end_ - token.start_ - 2);
+ Location current = token.start_ + 1; // skip '"'
+ Location end = token.end_ - 1; // do not include '"'
+ while (current != end) {
+ Char c = *current++;
+ if (c == '"')
+ break;
+ else if (c == '\\') {
+ if (current == end)
+ return addError("Empty escape sequence in string", token, current);
+ Char escape = *current++;
+ switch (escape) {
+ case '"':
+ decoded += '"';
+ break;
+ case '/':
+ decoded += '/';
+ break;
+ case '\\':
+ decoded += '\\';
+ break;
+ case 'b':
+ decoded += '\b';
+ break;
+ case 'f':
+ decoded += '\f';
+ break;
+ case 'n':
+ decoded += '\n';
+ break;
+ case 'r':
+ decoded += '\r';
+ break;
+ case 't':
+ decoded += '\t';
+ break;
+ case 'u': {
+ unsigned int unicode;
+ if (!decodeUnicodeCodePoint(token, current, end, unicode))
+ return false;
+ decoded += codePointToUTF8(unicode);
+ } break;
+ default:
+ return addError("Bad escape sequence in string", token, current);
+ }
+ } else {
+ decoded += c;
+ }
+ }
+ return true;
+}
+
+bool Reader::decodeUnicodeCodePoint(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode) {
+
+ if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
+ return false;
+ if (unicode >= 0xD800 && unicode <= 0xDBFF) {
+ // surrogate pairs
+ if (end - current < 6)
+ return addError(
+ "additional six characters expected to parse unicode surrogate pair.",
+ token,
+ current);
+ unsigned int surrogatePair;
+ if (*(current++) == '\\' && *(current++) == 'u') {
+ if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
+ unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
+ } else
+ return false;
+ } else
+ return addError("expecting another \\u token to begin the second half of "
+ "a unicode surrogate pair",
+ token,
+ current);
+ }
+ return true;
+}
+
+bool Reader::decodeUnicodeEscapeSequence(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode) {
+ if (end - current < 4)
+ return addError(
+ "Bad unicode escape sequence in string: four digits expected.",
+ token,
+ current);
+ unicode = 0;
+ for (int index = 0; index < 4; ++index) {
+ Char c = *current++;
+ unicode *= 16;
+ if (c >= '0' && c <= '9')
+ unicode += c - '0';
+ else if (c >= 'a' && c <= 'f')
+ unicode += c - 'a' + 10;
+ else if (c >= 'A' && c <= 'F')
+ unicode += c - 'A' + 10;
+ else
+ return addError(
+ "Bad unicode escape sequence in string: hexadecimal digit expected.",
+ token,
+ current);
+ }
+ return true;
+}
+
+bool
+Reader::addError(const std::string& message, Token& token, Location extra) {
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = extra;
+ errors_.push_back(info);
+ return false;
+}
+
+bool Reader::recoverFromError(TokenType skipUntilToken) {
+ int errorCount = int(errors_.size());
+ Token skip;
+ for (;;) {
+ if (!readToken(skip))
+ errors_.resize(errorCount); // discard errors caused by recovery
+ if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
+ break;
+ }
+ errors_.resize(errorCount);
+ return false;
+}
+
+bool Reader::addErrorAndRecover(const std::string& message,
+ Token& token,
+ TokenType skipUntilToken) {
+ addError(message, token);
+ return recoverFromError(skipUntilToken);
+}
+
+Value& Reader::currentValue() { return *(nodes_.top()); }
+
+Reader::Char Reader::getNextChar() {
+ if (current_ == end_)
+ return 0;
+ return *current_++;
+}
+
+void Reader::getLocationLineAndColumn(Location location,
+ int& line,
+ int& column) const {
+ Location current = begin_;
+ Location lastLineStart = current;
+ line = 0;
+ while (current < location && current != end_) {
+ Char c = *current++;
+ if (c == '\r') {
+ if (*current == '\n')
+ ++current;
+ lastLineStart = current;
+ ++line;
+ } else if (c == '\n') {
+ lastLineStart = current;
+ ++line;
+ }
+ }
+ // column & line start at 1
+ column = int(location - lastLineStart) + 1;
+ ++line;
+}
+
+std::string Reader::getLocationLineAndColumn(Location location) const {
+ int line, column;
+ getLocationLineAndColumn(location, line, column);
+ char buffer[18 + 16 + 16 + 1];
+ snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
+ return buffer;
+}
+
+std::string Reader::getLocationSnippet(Location location) const {
+ std::string snippet = "";
+ std::istringstream docStream(document_);
+ int lin, col;
+ getLocationLineAndColumn(location, lin, col);
+ std::string line;
+ for (int i=1; i<lin+2 && std::getline(docStream, line); i++)
+ {
+ if (lin-i < 2)
+ {
+ snippet += " " + std::to_string(i) + ": " + line + "\n";
+ }
+ }
+ return snippet;
+}
+
+// Deprecated. Preserved for backward compatibility
+std::string Reader::getFormatedErrorMessages() const {
+ return getFormattedErrorMessages();
+}
+
+std::string Reader::getFormattedErrorMessages() const {
+ std::string formattedMessage;
+ for (Errors::const_iterator itError = errors_.begin();
+ itError != errors_.end();
+ ++itError) {
+ const ErrorInfo& error = *itError;
+ formattedMessage +=
+ "* " + getLocationLineAndColumn(error.token_.start_) + "\n";
+ formattedMessage += getLocationSnippet(error.token_.start_) + "\n";
+ formattedMessage += " " + error.message_ + "\n";
+ if (error.extra_)
+ formattedMessage +=
+ "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
+ }
+ return formattedMessage;
+}
+
+std::vector<Reader::StructuredError> Reader::getStructuredErrors() const {
+ std::vector<Reader::StructuredError> allErrors;
+ for (Errors::const_iterator itError = errors_.begin();
+ itError != errors_.end();
+ ++itError) {
+ const ErrorInfo& error = *itError;
+ Reader::StructuredError structured;
+ structured.offset_start = error.token_.start_ - begin_;
+ structured.offset_limit = error.token_.end_ - begin_;
+ structured.message = error.message_;
+ allErrors.push_back(structured);
+ }
+ return allErrors;
+}
+
+bool Reader::pushError(const Value& value, const std::string& message) {
+ size_t length = end_ - begin_;
+ if(value.getOffsetStart() > length
+ || value.getOffsetLimit() > length)
+ return false;
+ Token token;
+ token.type_ = tokenError;
+ token.start_ = begin_ + value.getOffsetStart();
+ token.end_ = end_ + value.getOffsetLimit();
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = 0;
+ errors_.push_back(info);
+ return true;
+}
+
+bool Reader::pushError(const Value& value, const std::string& message, const Value& extra) {
+ size_t length = end_ - begin_;
+ if(value.getOffsetStart() > length
+ || value.getOffsetLimit() > length
+ || extra.getOffsetLimit() > length)
+ return false;
+ Token token;
+ token.type_ = tokenError;
+ token.start_ = begin_ + value.getOffsetStart();
+ token.end_ = begin_ + value.getOffsetLimit();
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = begin_ + extra.getOffsetStart();
+ errors_.push_back(info);
+ return true;
+}
+
+bool Reader::good() const {
+ return !errors_.size();
+}
+
+// exact copy of Features
+class OurFeatures {
+public:
+ static OurFeatures all();
+ bool allowComments_;
+ bool strictRoot_;
+ bool allowDroppedNullPlaceholders_;
+ bool allowNumericKeys_;
+ bool allowSingleQuotes_;
+ bool failIfExtra_;
+ bool rejectDupKeys_;
+ bool allowSpecialFloats_;
+ int stackLimit_;
+}; // OurFeatures
+
+// exact copy of Implementation of class Features
+// ////////////////////////////////
+
+OurFeatures OurFeatures::all() { return OurFeatures(); }
+
+// Implementation of class Reader
+// ////////////////////////////////
+
+// exact copy of Reader, renamed to OurReader
+class OurReader {
+public:
+ typedef char Char;
+ typedef const Char* Location;
+ struct StructuredError {
+ size_t offset_start;
+ size_t offset_limit;
+ std::string message;
+ };
+
+ OurReader(OurFeatures const& features);
+ bool parse(const char* beginDoc,
+ const char* endDoc,
+ Value& root,
+ bool collectComments = true);
+ std::string getFormattedErrorMessages() const;
+ std::vector<StructuredError> getStructuredErrors() const;
+ bool pushError(const Value& value, const std::string& message);
+ bool pushError(const Value& value, const std::string& message, const Value& extra);
+ bool good() const;
+
+private:
+ OurReader(OurReader const&); // no impl
+ void operator=(OurReader const&); // no impl
+
+ enum TokenType {
+ tokenEndOfStream = 0,
+ tokenObjectBegin,
+ tokenObjectEnd,
+ tokenArrayBegin,
+ tokenArrayEnd,
+ tokenString,
+ tokenNumber,
+ tokenTrue,
+ tokenFalse,
+ tokenNull,
+ tokenNaN,
+ tokenPosInf,
+ tokenNegInf,
+ tokenArraySeparator,
+ tokenMemberSeparator,
+ tokenComment,
+ tokenError
+ };
+
+ class Token {
+ public:
+ TokenType type_;
+ Location start_;
+ Location end_;
+ };
+
+ class ErrorInfo {
+ public:
+ Token token_;
+ std::string message_;
+ Location extra_;
+ };
+
+ typedef std::deque<ErrorInfo> Errors;
+
+ bool readToken(Token& token);
+ void skipSpaces();
+ bool match(Location pattern, int patternLength);
+ bool readComment();
+ bool readCStyleComment();
+ bool readCppStyleComment();
+ bool readString();
+ bool readStringSingleQuote();
+ bool readNumber(bool checkInf);
+ bool readValue();
+ bool readObject(Token& token);
+ bool readArray(Token& token);
+ bool decodeNumber(Token& token);
+ bool decodeNumber(Token& token, Value& decoded);
+ bool decodeString(Token& token);
+ bool decodeString(Token& token, std::string& decoded);
+ bool decodeDouble(Token& token);
+ bool decodeDouble(Token& token, Value& decoded);
+ bool decodeUnicodeCodePoint(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode);
+ bool decodeUnicodeEscapeSequence(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode);
+ bool addError(const std::string& message, Token& token, Location extra = 0);
+ bool recoverFromError(TokenType skipUntilToken);
+ bool addErrorAndRecover(const std::string& message,
+ Token& token,
+ TokenType skipUntilToken);
+ void skipUntilSpace();
+ Value& currentValue();
+ Char getNextChar();
+ void
+ getLocationLineAndColumn(Location location, int& line, int& column) const;
+ std::string getLocationLineAndColumn(Location location) const;
+ void addComment(Location begin, Location end, CommentPlacement placement);
+ void skipCommentTokens(Token& token);
+
+ typedef std::stack<Value*> Nodes;
+ Nodes nodes_;
+ Errors errors_;
+ std::string document_;
+ Location begin_;
+ Location end_;
+ Location current_;
+ Location lastValueEnd_;
+ Value* lastValue_;
+ std::string commentsBefore_;
+ int stackDepth_;
+
+ OurFeatures const features_;
+ bool collectComments_;
+}; // OurReader
+
+// complete copy of Read impl, for OurReader
+
+OurReader::OurReader(OurFeatures const& features)
+ : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
+ lastValue_(), commentsBefore_(),
+ stackDepth_(0),
+ features_(features), collectComments_() {
+}
+
+bool OurReader::parse(const char* beginDoc,
+ const char* endDoc,
+ Value& root,
+ bool collectComments) {
+ if (!features_.allowComments_) {
+ collectComments = false;
+ }
+
+ begin_ = beginDoc;
+ end_ = endDoc;
+ collectComments_ = collectComments;
+ current_ = begin_;
+ lastValueEnd_ = 0;
+ lastValue_ = 0;
+ commentsBefore_ = "";
+ errors_.clear();
+ while (!nodes_.empty())
+ nodes_.pop();
+ nodes_.push(&root);
+
+ stackDepth_ = 0;
+ bool successful = readValue();
+ Token token;
+ skipCommentTokens(token);
+ if (features_.failIfExtra_) {
+ if (token.type_ != tokenError && token.type_ != tokenEndOfStream) {
+ addError("Extra non-whitespace after JSON value.", token);
+ return false;
+ }
+ }
+ if (collectComments_ && !commentsBefore_.empty())
+ root.setComment(commentsBefore_, commentAfter);
+ if (features_.strictRoot_) {
+ if (!root.isArray() && !root.isObject()) {
+ // Set error location to start of doc, ideally should be first token found
+ // in doc
+ token.type_ = tokenError;
+ token.start_ = beginDoc;
+ token.end_ = endDoc;
+ addError(
+ "A valid JSON document must be either an array or an object value.",
+ token);
+ return false;
+ }
+ }
+ return successful;
+}
+
+bool OurReader::readValue() {
+ if (stackDepth_ >= features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue().");
+ ++stackDepth_;
+ Token token;
+ skipCommentTokens(token);
+ bool successful = true;
+
+ if (collectComments_ && !commentsBefore_.empty()) {
+ currentValue().setComment(commentsBefore_, commentBefore);
+ commentsBefore_ = "";
+ }
+
+ switch (token.type_) {
+ case tokenObjectBegin:
+ successful = readObject(token);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ case tokenArrayBegin:
+ successful = readArray(token);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ case tokenNumber:
+ successful = decodeNumber(token);
+ break;
+ case tokenString:
+ successful = decodeString(token);
+ break;
+ case tokenTrue:
+ {
+ Value v(true);
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenFalse:
+ {
+ Value v(false);
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenNull:
+ {
+ Value v;
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenNaN:
+ {
+ Value v(std::numeric_limits<double>::quiet_NaN());
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenPosInf:
+ {
+ Value v(std::numeric_limits<double>::infinity());
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenNegInf:
+ {
+ Value v(-std::numeric_limits<double>::infinity());
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenArraySeparator:
+ case tokenObjectEnd:
+ case tokenArrayEnd:
+ if (features_.allowDroppedNullPlaceholders_) {
+ // "Un-read" the current token and mark the current value as a null
+ // token.
+ current_--;
+ Value v;
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(current_ - begin_ - 1);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ } // else, fall through ...
+ default:
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return addError("Syntax error: value, object or array expected.", token);
+ }
+
+ if (collectComments_) {
+ lastValueEnd_ = current_;
+ lastValue_ = &currentValue();
+ }
+
+ --stackDepth_;
+ return successful;
+}
+
+void OurReader::skipCommentTokens(Token& token) {
+ if (features_.allowComments_) {
+ do {
+ readToken(token);
+ } while (token.type_ == tokenComment);
+ } else {
+ readToken(token);
+ }
+}
+
+bool OurReader::readToken(Token& token) {
+ skipSpaces();
+ token.start_ = current_;
+ Char c = getNextChar();
+ bool ok = true;
+ switch (c) {
+ case '{':
+ token.type_ = tokenObjectBegin;
+ break;
+ case '}':
+ token.type_ = tokenObjectEnd;
+ break;
+ case '[':
+ token.type_ = tokenArrayBegin;
+ break;
+ case ']':
+ token.type_ = tokenArrayEnd;
+ break;
+ case '"':
+ token.type_ = tokenString;
+ ok = readString();
+ break;
+ case '\'':
+ if (features_.allowSingleQuotes_) {
+ token.type_ = tokenString;
+ ok = readStringSingleQuote();
+ break;
+ } // else continue
+ case '/':
+ token.type_ = tokenComment;
+ ok = readComment();
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ token.type_ = tokenNumber;
+ readNumber(false);
+ break;
+ case '-':
+ if (readNumber(true)) {
+ token.type_ = tokenNumber;
+ } else {
+ token.type_ = tokenNegInf;
+ ok = features_.allowSpecialFloats_ && match("nfinity", 7);
+ }
+ break;
+ case 't':
+ token.type_ = tokenTrue;
+ ok = match("rue", 3);
+ break;
+ case 'f':
+ token.type_ = tokenFalse;
+ ok = match("alse", 4);
+ break;
+ case 'n':
+ token.type_ = tokenNull;
+ ok = match("ull", 3);
+ break;
+ case 'N':
+ if (features_.allowSpecialFloats_) {
+ token.type_ = tokenNaN;
+ ok = match("aN", 2);
+ } else {
+ ok = false;
+ }
+ break;
+ case 'I':
+ if (features_.allowSpecialFloats_) {
+ token.type_ = tokenPosInf;
+ ok = match("nfinity", 7);
+ } else {
+ ok = false;
+ }
+ break;
+ case ',':
+ token.type_ = tokenArraySeparator;
+ break;
+ case ':':
+ token.type_ = tokenMemberSeparator;
+ break;
+ case 0:
+ token.type_ = tokenEndOfStream;
+ break;
+ default:
+ ok = false;
+ break;
+ }
+ if (!ok)
+ token.type_ = tokenError;
+ token.end_ = current_;
+ return true;
+}
+
+void OurReader::skipSpaces() {
+ while (current_ != end_) {
+ Char c = *current_;
+ if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
+ ++current_;
+ else
+ break;
+ }
+}
+
+bool OurReader::match(Location pattern, int patternLength) {
+ if (end_ - current_ < patternLength)
+ return false;
+ int index = patternLength;
+ while (index--)
+ if (current_[index] != pattern[index])
+ return false;
+ current_ += patternLength;
+ return true;
+}
+
+bool OurReader::readComment() {
+ Location commentBegin = current_ - 1;
+ Char c = getNextChar();
+ bool successful = false;
+ if (c == '*')
+ successful = readCStyleComment();
+ else if (c == '/')
+ successful = readCppStyleComment();
+ if (!successful)
+ return false;
+
+ if (collectComments_) {
+ CommentPlacement placement = commentBefore;
+ if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
+ if (c != '*' || !containsNewLine(commentBegin, current_))
+ placement = commentAfterOnSameLine;
+ }
+
+ addComment(commentBegin, current_, placement);
+ }
+ return true;
+}
+
+void
+OurReader::addComment(Location begin, Location end, CommentPlacement placement) {
+ assert(collectComments_);
+ const std::string& normalized = normalizeEOL(begin, end);
+ if (placement == commentAfterOnSameLine) {
+ assert(lastValue_ != 0);
+ lastValue_->setComment(normalized, placement);
+ } else {
+ commentsBefore_ += normalized;
+ }
+}
+
+bool OurReader::readCStyleComment() {
+ while (current_ != end_) {
+ Char c = getNextChar();
+ if (c == '*' && *current_ == '/')
+ break;
+ }
+ return getNextChar() == '/';
+}
+
+bool OurReader::readCppStyleComment() {
+ while (current_ != end_) {
+ Char c = getNextChar();
+ if (c == '\n')
+ break;
+ if (c == '\r') {
+ // Consume DOS EOL. It will be normalized in addComment.
+ if (current_ != end_ && *current_ == '\n')
+ getNextChar();
+ // Break on Moc OS 9 EOL.
+ break;
+ }
+ }
+ return true;
+}
+
+bool OurReader::readNumber(bool checkInf) {
+ const char *p = current_;
+ if (checkInf && p != end_ && *p == 'I') {
+ current_ = ++p;
+ return false;
+ }
+ char c = '0'; // stopgap for already consumed character
+ // integral part
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ // fractional part
+ if (c == '.') {
+ c = (current_ = p) < end_ ? *p++ : 0;
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ }
+ // exponential part
+ if (c == 'e' || c == 'E') {
+ c = (current_ = p) < end_ ? *p++ : 0;
+ if (c == '+' || c == '-')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ }
+ return true;
+}
+bool OurReader::readString() {
+ Char c = 0;
+ while (current_ != end_) {
+ c = getNextChar();
+ if (c == '\\')
+ getNextChar();
+ else if (c == '"')
+ break;
+ }
+ return c == '"';
+}
+
+
+bool OurReader::readStringSingleQuote() {
+ Char c = 0;
+ while (current_ != end_) {
+ c = getNextChar();
+ if (c == '\\')
+ getNextChar();
+ else if (c == '\'')
+ break;
+ }
+ return c == '\'';
+}
+
+bool OurReader::readObject(Token& tokenStart) {
+ Token tokenName;
+ std::string name;
+ Value init(objectValue);
+ currentValue().swapPayload(init);
+ currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ while (readToken(tokenName)) {
+ bool initialTokenOk = true;
+ while (tokenName.type_ == tokenComment && initialTokenOk)
+ initialTokenOk = readToken(tokenName);
+ if (!initialTokenOk)
+ break;
+ if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
+ return true;
+ name = "";
+ if (tokenName.type_ == tokenString) {
+ if (!decodeString(tokenName, name))
+ return recoverFromError(tokenObjectEnd);
+ } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
+ Value numberName;
+ if (!decodeNumber(tokenName, numberName))
+ return recoverFromError(tokenObjectEnd);
+ name = numberName.asString();
+ } else {
+ break;
+ }
+
+ Token colon;
+ if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
+ return addErrorAndRecover(
+ "Missing ':' after object member name", colon, tokenObjectEnd);
+ }
+ if (name.length() >= (1U<<30)) throwRuntimeError("keylength >= 2^30");
+ if (features_.rejectDupKeys_ && currentValue().isMember(name)) {
+ std::string msg = "Duplicate key: '" + name + "'";
+ return addErrorAndRecover(
+ msg, tokenName, tokenObjectEnd);
+ }
+ Value& value = currentValue()[name];
+ nodes_.push(&value);
+ bool ok = readValue();
+ nodes_.pop();
+ if (!ok) // error already set
+ return recoverFromError(tokenObjectEnd);
+
+ Token comma;
+ if (!readToken(comma) ||
+ (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
+ comma.type_ != tokenComment)) {
+ return addErrorAndRecover(
+ "Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
+ }
+ bool finalizeTokenOk = true;
+ while (comma.type_ == tokenComment && finalizeTokenOk)
+ finalizeTokenOk = readToken(comma);
+ if (comma.type_ == tokenObjectEnd)
+ return true;
+ }
+ return addErrorAndRecover(
+ "Missing '}' or object member name", tokenName, tokenObjectEnd);
+}
+
+bool OurReader::readArray(Token& tokenStart) {
+ Value init(arrayValue);
+ currentValue().swapPayload(init);
+ currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ skipSpaces();
+ if (*current_ == ']') // empty array
+ {
+ Token endArray;
+ readToken(endArray);
+ return true;
+ }
+ int index = 0;
+ for (;;) {
+ Value& value = currentValue()[index++];
+ nodes_.push(&value);
+ bool ok = readValue();
+ nodes_.pop();
+ if (!ok) // error already set
+ return recoverFromError(tokenArrayEnd);
+
+ Token token;
+ // Accept Comment after last item in the array.
+ ok = readToken(token);
+ while (token.type_ == tokenComment && ok) {
+ ok = readToken(token);
+ }
+ bool badTokenType =
+ (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
+ if (!ok || badTokenType) {
+ return addErrorAndRecover(
+ "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
+ }
+ if (token.type_ == tokenArrayEnd)
+ break;
+ }
+ return true;
+}
+
+bool OurReader::decodeNumber(Token& token) {
+ Value decoded;
+ if (!decodeNumber(token, decoded))
+ return false;
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool OurReader::decodeNumber(Token& token, Value& decoded) {
+ // Attempts to parse the number as an integer. If the number is
+ // larger than the maximum supported value of an integer then
+ // we decode the number as a double.
+ Location current = token.start_;
+ bool isNegative = *current == '-';
+ if (isNegative)
+ ++current;
+ // TODO: Help the compiler do the div and mod at compile time or get rid of them.
+ Value::LargestUInt maxIntegerValue =
+ isNegative ? Value::LargestUInt(-Value::minLargestInt)
+ : Value::maxLargestUInt;
+ Value::LargestUInt threshold = maxIntegerValue / 10;
+ Value::LargestUInt value = 0;
+ while (current < token.end_) {
+ Char c = *current++;
+ if (c < '0' || c > '9')
+ return decodeDouble(token, decoded);
+ Value::UInt digit(c - '0');
+ if (value >= threshold) {
+ // We've hit or exceeded the max value divided by 10 (rounded down). If
+ // a) we've only just touched the limit, b) this is the last digit, and
+ // c) it's small enough to fit in that rounding delta, we're okay.
+ // Otherwise treat this number as a double to avoid overflow.
+ if (value > threshold || current != token.end_ ||
+ digit > maxIntegerValue % 10) {
+ return decodeDouble(token, decoded);
+ }
+ }
+ value = value * 10 + digit;
+ }
+ if (isNegative)
+ decoded = -Value::LargestInt(value);
+ else if (value <= Value::LargestUInt(Value::maxInt))
+ decoded = Value::LargestInt(value);
+ else
+ decoded = value;
+ return true;
+}
+
+bool OurReader::decodeDouble(Token& token) {
+ Value decoded;
+ if (!decodeDouble(token, decoded))
+ return false;
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool OurReader::decodeDouble(Token& token, Value& decoded) {
+ double value = 0;
+ const int bufferSize = 32;
+ int count;
+ int length = int(token.end_ - token.start_);
+
+ // Sanity check to avoid buffer overflow exploits.
+ if (length < 0) {
+ return addError("Unable to parse token length", token);
+ }
+
+ // Avoid using a string constant for the format control string given to
+ // sscanf, as this can cause hard to debug crashes on OS X. See here for more
+ // info:
+ //
+ // http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html
+ char format[] = "%lf";
+
+ if (length <= bufferSize) {
+ Char buffer[bufferSize + 1];
+ memcpy(buffer, token.start_, length);
+ buffer[length] = 0;
+ count = sscanf(buffer, format, &value);
+ } else {
+ std::string buffer(token.start_, token.end_);
+ count = sscanf(buffer.c_str(), format, &value);
+ }
+
+ if (count != 1)
+ return addError("'" + std::string(token.start_, token.end_) +
+ "' is not a number.",
+ token);
+ decoded = value;
+ return true;
+}
+
+bool OurReader::decodeString(Token& token) {
+ std::string decoded_string;
+ if (!decodeString(token, decoded_string))
+ return false;
+ Value decoded(decoded_string);
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool OurReader::decodeString(Token& token, std::string& decoded) {
+ decoded.reserve(token.end_ - token.start_ - 2);
+ Location current = token.start_ + 1; // skip '"'
+ Location end = token.end_ - 1; // do not include '"'
+ while (current != end) {
+ Char c = *current++;
+ if (c == '"')
+ break;
+ else if (c == '\\') {
+ if (current == end)
+ return addError("Empty escape sequence in string", token, current);
+ Char escape = *current++;
+ switch (escape) {
+ case '"':
+ decoded += '"';
+ break;
+ case '/':
+ decoded += '/';
+ break;
+ case '\\':
+ decoded += '\\';
+ break;
+ case 'b':
+ decoded += '\b';
+ break;
+ case 'f':
+ decoded += '\f';
+ break;
+ case 'n':
+ decoded += '\n';
+ break;
+ case 'r':
+ decoded += '\r';
+ break;
+ case 't':
+ decoded += '\t';
+ break;
+ case 'u': {
+ unsigned int unicode;
+ if (!decodeUnicodeCodePoint(token, current, end, unicode))
+ return false;
+ decoded += codePointToUTF8(unicode);
+ } break;
+ default:
+ return addError("Bad escape sequence in string", token, current);
+ }
+ } else {
+ decoded += c;
+ }
+ }
+ return true;
+}
+
+bool OurReader::decodeUnicodeCodePoint(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode) {
+
+ if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
+ return false;
+ if (unicode >= 0xD800 && unicode <= 0xDBFF) {
+ // surrogate pairs
+ if (end - current < 6)
+ return addError(
+ "additional six characters expected to parse unicode surrogate pair.",
+ token,
+ current);
+ unsigned int surrogatePair;
+ if (*(current++) == '\\' && *(current++) == 'u') {
+ if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
+ unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
+ } else
+ return false;
+ } else
+ return addError("expecting another \\u token to begin the second half of "
+ "a unicode surrogate pair",
+ token,
+ current);
+ }
+ return true;
+}
+
+bool OurReader::decodeUnicodeEscapeSequence(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode) {
+ if (end - current < 4)
+ return addError(
+ "Bad unicode escape sequence in string: four digits expected.",
+ token,
+ current);
+ unicode = 0;
+ for (int index = 0; index < 4; ++index) {
+ Char c = *current++;
+ unicode *= 16;
+ if (c >= '0' && c <= '9')
+ unicode += c - '0';
+ else if (c >= 'a' && c <= 'f')
+ unicode += c - 'a' + 10;
+ else if (c >= 'A' && c <= 'F')
+ unicode += c - 'A' + 10;
+ else
+ return addError(
+ "Bad unicode escape sequence in string: hexadecimal digit expected.",
+ token,
+ current);
+ }
+ return true;
+}
+
+bool
+OurReader::addError(const std::string& message, Token& token, Location extra) {
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = extra;
+ errors_.push_back(info);
+ return false;
+}
+
+bool OurReader::recoverFromError(TokenType skipUntilToken) {
+ int errorCount = int(errors_.size());
+ Token skip;
+ for (;;) {
+ if (!readToken(skip))
+ errors_.resize(errorCount); // discard errors caused by recovery
+ if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
+ break;
+ }
+ errors_.resize(errorCount);
+ return false;
+}
+
+bool OurReader::addErrorAndRecover(const std::string& message,
+ Token& token,
+ TokenType skipUntilToken) {
+ addError(message, token);
+ return recoverFromError(skipUntilToken);
+}
+
+Value& OurReader::currentValue() { return *(nodes_.top()); }
+
+OurReader::Char OurReader::getNextChar() {
+ if (current_ == end_)
+ return 0;
+ return *current_++;
+}
+
+void OurReader::getLocationLineAndColumn(Location location,
+ int& line,
+ int& column) const {
+ Location current = begin_;
+ Location lastLineStart = current;
+ line = 0;
+ while (current < location && current != end_) {
+ Char c = *current++;
+ if (c == '\r') {
+ if (*current == '\n')
+ ++current;
+ lastLineStart = current;
+ ++line;
+ } else if (c == '\n') {
+ lastLineStart = current;
+ ++line;
+ }
+ }
+ // column & line start at 1
+ column = int(location - lastLineStart) + 1;
+ ++line;
+}
+
+std::string OurReader::getLocationLineAndColumn(Location location) const {
+ int line, column;
+ getLocationLineAndColumn(location, line, column);
+ char buffer[18 + 16 + 16 + 1];
+ snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
+ return buffer;
+}
+
+std::string OurReader::getFormattedErrorMessages() const {
+ std::string formattedMessage;
+ for (Errors::const_iterator itError = errors_.begin();
+ itError != errors_.end();
+ ++itError) {
+ const ErrorInfo& error = *itError;
+ formattedMessage +=
+ "* " + getLocationLineAndColumn(error.token_.start_) + "\n";
+ formattedMessage += " " + error.message_ + "\n";
+ if (error.extra_)
+ formattedMessage +=
+ "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
+ }
+ return formattedMessage;
+}
+
+std::vector<OurReader::StructuredError> OurReader::getStructuredErrors() const {
+ std::vector<OurReader::StructuredError> allErrors;
+ for (Errors::const_iterator itError = errors_.begin();
+ itError != errors_.end();
+ ++itError) {
+ const ErrorInfo& error = *itError;
+ OurReader::StructuredError structured;
+ structured.offset_start = error.token_.start_ - begin_;
+ structured.offset_limit = error.token_.end_ - begin_;
+ structured.message = error.message_;
+ allErrors.push_back(structured);
+ }
+ return allErrors;
+}
+
+bool OurReader::pushError(const Value& value, const std::string& message) {
+ size_t length = end_ - begin_;
+ if(value.getOffsetStart() > length
+ || value.getOffsetLimit() > length)
+ return false;
+ Token token;
+ token.type_ = tokenError;
+ token.start_ = begin_ + value.getOffsetStart();
+ token.end_ = end_ + value.getOffsetLimit();
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = 0;
+ errors_.push_back(info);
+ return true;
+}
+
+bool OurReader::pushError(const Value& value, const std::string& message, const Value& extra) {
+ size_t length = end_ - begin_;
+ if(value.getOffsetStart() > length
+ || value.getOffsetLimit() > length
+ || extra.getOffsetLimit() > length)
+ return false;
+ Token token;
+ token.type_ = tokenError;
+ token.start_ = begin_ + value.getOffsetStart();
+ token.end_ = begin_ + value.getOffsetLimit();
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = begin_ + extra.getOffsetStart();
+ errors_.push_back(info);
+ return true;
+}
+
+bool OurReader::good() const {
+ return !errors_.size();
+}
+
+
+class OurCharReader : public CharReader {
+ bool const collectComments_;
+ OurReader reader_;
+public:
+ OurCharReader(
+ bool collectComments,
+ OurFeatures const& features)
+ : collectComments_(collectComments)
+ , reader_(features)
+ {}
+ bool parse(
+ char const* beginDoc, char const* endDoc,
+ Value* root, std::string* errs) {
+ bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
+ if (errs) {
+ *errs = reader_.getFormattedErrorMessages();
+ }
+ return ok;
+ }
+};
+
+CharReaderBuilder::CharReaderBuilder()
+{
+ setDefaults(&settings_);
+}
+CharReaderBuilder::~CharReaderBuilder()
+{}
+CharReader* CharReaderBuilder::newCharReader() const
+{
+ bool collectComments = settings_["collectComments"].asBool();
+ OurFeatures features = OurFeatures::all();
+ features.allowComments_ = settings_["allowComments"].asBool();
+ features.strictRoot_ = settings_["strictRoot"].asBool();
+ features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool();
+ features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool();
+ features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool();
+ features.stackLimit_ = settings_["stackLimit"].asInt();
+ features.failIfExtra_ = settings_["failIfExtra"].asBool();
+ features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool();
+ features.allowSpecialFloats_ = settings_["allowSpecialFloats"].asBool();
+ return new OurCharReader(collectComments, features);
+}
+static void getValidReaderKeys(std::set<std::string>* valid_keys)
+{
+ valid_keys->clear();
+ valid_keys->insert("collectComments");
+ valid_keys->insert("allowComments");
+ valid_keys->insert("strictRoot");
+ valid_keys->insert("allowDroppedNullPlaceholders");
+ valid_keys->insert("allowNumericKeys");
+ valid_keys->insert("allowSingleQuotes");
+ valid_keys->insert("stackLimit");
+ valid_keys->insert("failIfExtra");
+ valid_keys->insert("rejectDupKeys");
+ valid_keys->insert("allowSpecialFloats");
+}
+bool CharReaderBuilder::validate(Json::Value* invalid) const
+{
+ Json::Value my_invalid;
+ if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
+ Json::Value& inv = *invalid;
+ std::set<std::string> valid_keys;
+ getValidReaderKeys(&valid_keys);
+ Value::Members keys = settings_.getMemberNames();
+ size_t n = keys.size();
+ for (size_t i = 0; i < n; ++i) {
+ std::string const& key = keys[i];
+ if (valid_keys.find(key) == valid_keys.end()) {
+ inv[key] = settings_[key];
+ }
+ }
+ return 0u == inv.size();
+}
+Value& CharReaderBuilder::operator[](std::string key)
+{
+ return settings_[key];
+}
+// static
+void CharReaderBuilder::strictMode(Json::Value* settings)
+{
+//! [CharReaderBuilderStrictMode]
+ (*settings)["allowComments"] = false;
+ (*settings)["strictRoot"] = true;
+ (*settings)["allowDroppedNullPlaceholders"] = false;
+ (*settings)["allowNumericKeys"] = false;
+ (*settings)["allowSingleQuotes"] = false;
+ (*settings)["stackLimit"] = 1000;
+ (*settings)["failIfExtra"] = true;
+ (*settings)["rejectDupKeys"] = true;
+ (*settings)["allowSpecialFloats"] = false;
+//! [CharReaderBuilderStrictMode]
+}
+// static
+void CharReaderBuilder::setDefaults(Json::Value* settings)
+{
+//! [CharReaderBuilderDefaults]
+ (*settings)["collectComments"] = true;
+ (*settings)["allowComments"] = true;
+ (*settings)["strictRoot"] = false;
+ (*settings)["allowDroppedNullPlaceholders"] = false;
+ (*settings)["allowNumericKeys"] = false;
+ (*settings)["allowSingleQuotes"] = false;
+ (*settings)["stackLimit"] = 1000;
+ (*settings)["failIfExtra"] = false;
+ (*settings)["rejectDupKeys"] = false;
+ (*settings)["allowSpecialFloats"] = false;
+//! [CharReaderBuilderDefaults]
+}
+
+//////////////////////////////////
+// global functions
+
+bool parseFromStream(
+ CharReader::Factory const& fact, std::istream& sin,
+ Value* root, std::string* errs)
+{
+ std::ostringstream ssin;
+ ssin << sin.rdbuf();
+ std::string doc = ssin.str();
+ char const* begin = doc.data();
+ char const* end = begin + doc.size();
+ // Note that we do not actually need a null-terminator.
+ CharReaderPtr const reader(fact.newCharReader());
+ return reader->parse(begin, end, root, errs);
+}
+
+std::istream& operator>>(std::istream& sin, Value& root) {
+ CharReaderBuilder b;
+ std::string errs;
+ bool ok = parseFromStream(b, sin, &root, &errs);
+ if (!ok) {
+ fprintf(stderr,
+ "Error from reader: %s",
+ errs.c_str());
+
+ throwRuntimeError(errs);
+ }
+ return sin;
+}
+
+} // namespace Json
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: src/lib_json/json_reader.cpp
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_valueiterator.inl
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+// included by json_value.cpp
+
+namespace Json {
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class ValueIteratorBase
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+ValueIteratorBase::ValueIteratorBase()
+ : current_(), isNull_(true) {
+}
+
+ValueIteratorBase::ValueIteratorBase(
+ const Value::ObjectValues::iterator& current)
+ : current_(current), isNull_(false) {}
+
+Value& ValueIteratorBase::deref() const {
+ return current_->second;
+}
+
+void ValueIteratorBase::increment() {
+ ++current_;
+}
+
+void ValueIteratorBase::decrement() {
+ --current_;
+}
+
+ValueIteratorBase::difference_type
+ValueIteratorBase::computeDistance(const SelfType& other) const {
+#ifdef JSON_USE_CPPTL_SMALLMAP
+ return other.current_ - current_;
+#else
+ // Iterator for null value are initialized using the default
+ // constructor, which initialize current_ to the default
+ // std::map::iterator. As begin() and end() are two instance
+ // of the default std::map::iterator, they can not be compared.
+ // To allow this, we handle this comparison specifically.
+ if (isNull_ && other.isNull_) {
+ return 0;
+ }
+
+ // Usage of std::distance is not portable (does not compile with Sun Studio 12
+ // RogueWave STL,
+ // which is the one used by default).
+ // Using a portable hand-made version for non random iterator instead:
+ // return difference_type( std::distance( current_, other.current_ ) );
+ difference_type myDistance = 0;
+ for (Value::ObjectValues::iterator it = current_; it != other.current_;
+ ++it) {
+ ++myDistance;
+ }
+ return myDistance;
+#endif
+}
+
+bool ValueIteratorBase::isEqual(const SelfType& other) const {
+ if (isNull_) {
+ return other.isNull_;
+ }
+ return current_ == other.current_;
+}
+
+void ValueIteratorBase::copy(const SelfType& other) {
+ current_ = other.current_;
+ isNull_ = other.isNull_;
+}
+
+Value ValueIteratorBase::key() const {
+ const Value::CZString czstring = (*current_).first;
+ if (czstring.data()) {
+ if (czstring.isStaticString())
+ return Value(StaticString(czstring.data()));
+ return Value(czstring.data(), czstring.data() + czstring.length());
+ }
+ return Value(czstring.index());
+}
+
+UInt ValueIteratorBase::index() const {
+ const Value::CZString czstring = (*current_).first;
+ if (!czstring.data())
+ return czstring.index();
+ return Value::UInt(-1);
+}
+
+std::string ValueIteratorBase::name() const {
+ char const* keey;
+ char const* end;
+ keey = memberName(&end);
+ if (!keey) return std::string();
+ return std::string(keey, end);
+}
+
+char const* ValueIteratorBase::memberName() const {
+ const char* cname = (*current_).first.data();
+ return cname ? cname : "";
+}
+
+char const* ValueIteratorBase::memberName(char const** end) const {
+ const char* cname = (*current_).first.data();
+ if (!cname) {
+ *end = NULL;
+ return NULL;
+ }
+ *end = cname + (*current_).first.length();
+ return cname;
+}
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class ValueConstIterator
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+ValueConstIterator::ValueConstIterator() {}
+
+ValueConstIterator::ValueConstIterator(
+ const Value::ObjectValues::iterator& current)
+ : ValueIteratorBase(current) {}
+
+ValueConstIterator::ValueConstIterator(ValueIterator const& other)
+ : ValueIteratorBase(other) {}
+
+ValueConstIterator& ValueConstIterator::
+operator=(const ValueIteratorBase& other) {
+ copy(other);
+ return *this;
+}
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class ValueIterator
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+ValueIterator::ValueIterator() {}
+
+ValueIterator::ValueIterator(const Value::ObjectValues::iterator& current)
+ : ValueIteratorBase(current) {}
+
+ValueIterator::ValueIterator(const ValueConstIterator& other)
+ : ValueIteratorBase(other) {
+ throwRuntimeError("ConstIterator to Iterator should never be allowed.");
+}
+
+ValueIterator::ValueIterator(const ValueIterator& other)
+ : ValueIteratorBase(other) {}
+
+ValueIterator& ValueIterator::operator=(const SelfType& other) {
+ copy(other);
+ return *this;
+}
+
+} // namespace Json
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: src/lib_json/json_valueiterator.inl
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_value.cpp
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2011 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include <json/assertions.h>
+#include <json/value.h>
+#include <json/writer.h>
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <math.h>
+#include <sstream>
+#include <utility>
+#include <cstring>
+#include <cassert>
+#ifdef JSON_USE_CPPTL
+#include <cpptl/conststring.h>
+#endif
+#include <cstddef> // size_t
+#include <algorithm> // min()
+
+#define JSON_ASSERT_UNREACHABLE assert(false)
+
+/*
+-- Valve 1/7/16
+4702 unreachable code
+*/
+#pragma warning (push)
+#pragma warning (disable: 4702)
+
+namespace Json {
+
+// This is a walkaround to avoid the static initialization of Value::null.
+// kNull must be word-aligned to avoid crashing on ARM. We use an alignment of
+// 8 (instead of 4) as a bit of future-proofing.
+#if defined(__ARMEL__)
+#define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
+#else
+#define ALIGNAS(byte_alignment)
+#endif
+static const unsigned char ALIGNAS(8) kNull[sizeof(Value)] = { 0 };
+const unsigned char& kNullRef = kNull[0];
+const Value& Value::null = reinterpret_cast<const Value&>(kNullRef);
+const Value& Value::nullRef = null;
+
+const Int Value::minInt = Int(~(UInt(-1) / 2));
+const Int Value::maxInt = Int(UInt(-1) / 2);
+const UInt Value::maxUInt = UInt(-1);
+#if defined(JSON_HAS_INT64)
+const Int64 Value::minInt64 = Int64(~(UInt64(-1) / 2));
+const Int64 Value::maxInt64 = Int64(UInt64(-1) / 2);
+const UInt64 Value::maxUInt64 = UInt64(-1);
+// The constant is hard-coded because some compiler have trouble
+// converting Value::maxUInt64 to a double correctly (AIX/xlC).
+// Assumes that UInt64 is a 64 bits integer.
+static const double maxUInt64AsDouble = 18446744073709551615.0;
+#endif // defined(JSON_HAS_INT64)
+const LargestInt Value::minLargestInt = LargestInt(~(LargestUInt(-1) / 2));
+const LargestInt Value::maxLargestInt = LargestInt(LargestUInt(-1) / 2);
+const LargestUInt Value::maxLargestUInt = LargestUInt(-1);
+
+#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+template <typename T, typename U>
+static inline bool InRange(double d, T min, U max) {
+ return d >= min && d <= max;
+}
+#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+static inline double integerToDouble(Json::UInt64 value) {
+ return static_cast<double>(Int64(value / 2)) * 2.0 + Int64(value & 1);
+}
+
+template <typename T> static inline double integerToDouble(T value) {
+ return static_cast<double>(value);
+}
+
+template <typename T, typename U>
+static inline bool InRange(double d, T min, U max) {
+ return d >= integerToDouble(min) && d <= integerToDouble(max);
+}
+#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+
+/** Duplicates the specified string value.
+ * @param value Pointer to the string to duplicate. Must be zero-terminated if
+ * length is "unknown".
+ * @param length Length of the value. if equals to unknown, then it will be
+ * computed using strlen(value).
+ * @return Pointer on the duplicate instance of string.
+ */
+static inline char* duplicateStringValue(const char* value,
+ size_t length) {
+ // Avoid an integer overflow in the call to malloc below by limiting length
+ // to a sane value.
+ if (length >= (size_t)Value::maxInt)
+ length = Value::maxInt - 1;
+
+ char* newString = static_cast<char*>(malloc(length + 1));
+ if (newString == NULL) {
+ throwRuntimeError(
+ "in Json::Value::duplicateStringValue(): "
+ "Failed to allocate string value buffer");
+ }
+ memcpy(newString, value, length);
+ newString[length] = 0;
+ return newString;
+}
+
+/* Record the length as a prefix.
+ */
+static inline char* duplicateAndPrefixStringValue(
+ const char* value,
+ unsigned int length)
+{
+ // Avoid an integer overflow in the call to malloc below by limiting length
+ // to a sane value.
+ JSON_ASSERT_MESSAGE(length <= (unsigned)Value::maxInt - sizeof(unsigned) - 1U,
+ "in Json::Value::duplicateAndPrefixStringValue(): "
+ "length too big for prefixing");
+ unsigned actualLength = length + static_cast<unsigned>(sizeof(unsigned)) + 1U;
+ char* newString = static_cast<char*>(malloc(actualLength));
+ if (newString == 0) {
+ throwRuntimeError(
+ "in Json::Value::duplicateAndPrefixStringValue(): "
+ "Failed to allocate string value buffer");
+ }
+ *reinterpret_cast<unsigned*>(newString) = length;
+ memcpy(newString + sizeof(unsigned), value, length);
+ newString[actualLength - 1U] = 0; // to avoid buffer over-run accidents by users later
+ return newString;
+}
+inline static void decodePrefixedString(
+ bool isPrefixed, char const* prefixed,
+ unsigned* length, char const** value)
+{
+ if (!isPrefixed) {
+ *length = static_cast<unsigned>(strlen(prefixed));
+ *value = prefixed;
+ } else {
+ *length = *reinterpret_cast<unsigned const*>(prefixed);
+ *value = prefixed + sizeof(unsigned);
+ }
+}
+/** Free the string duplicated by duplicateStringValue()/duplicateAndPrefixStringValue().
+ */
+static inline void releaseStringValue(char* value) { free(value); }
+
+} // namespace Json
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// ValueInternals...
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+#if !defined(JSON_IS_AMALGAMATION)
+
+#include "json_valueiterator.inl"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+namespace Json {
+
+Exception::Exception(std::string const& msg)
+ : msg_(msg)
+{}
+Exception::~Exception() throw()
+{}
+char const* Exception::what() const throw()
+{
+ return msg_.c_str();
+}
+RuntimeError::RuntimeError(std::string const& msg)
+ : Exception(msg)
+{}
+LogicError::LogicError(std::string const& msg)
+ : Exception(msg)
+{}
+void throwRuntimeError(std::string const& msg)
+{
+ throw RuntimeError(msg);
+}
+void throwLogicError(std::string const& msg)
+{
+ throw LogicError(msg);
+}
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class Value::CommentInfo
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+Value::CommentInfo::CommentInfo() : comment_(0) {}
+
+Value::CommentInfo::~CommentInfo() {
+ if (comment_)
+ releaseStringValue(comment_);
+}
+
+void Value::CommentInfo::setComment(const char* text, size_t len) {
+ if (comment_) {
+ releaseStringValue(comment_);
+ comment_ = 0;
+ }
+ JSON_ASSERT(text != 0);
+ JSON_ASSERT_MESSAGE(
+ text[0] == '\0' || text[0] == '/',
+ "in Json::Value::setComment(): Comments must start with /");
+ // It seems that /**/ style comments are acceptable as well.
+ comment_ = duplicateStringValue(text, len);
+}
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class Value::CZString
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+// Notes: policy_ indicates if the string was allocated when
+// a string is stored.
+
+Value::CZString::CZString(ArrayIndex aindex) : cstr_(0), index_(aindex) {}
+
+Value::CZString::CZString(char const* str, unsigned ulength, DuplicationPolicy allocate)
+ : cstr_(str) {
+ // allocate != duplicate
+ storage_.policy_ = allocate & 0x3;
+ storage_.length_ = ulength & 0x3FFFFFFF;
+}
+
+Value::CZString::CZString(const CZString& other)
+ : cstr_(other.storage_.policy_ != noDuplication && other.cstr_ != 0
+ ? duplicateStringValue(other.cstr_, other.storage_.length_)
+ : other.cstr_) {
+ storage_.policy_ = (other.cstr_
+ ? (static_cast<DuplicationPolicy>(other.storage_.policy_) == noDuplication
+ ? noDuplication : duplicate)
+ : static_cast<DuplicationPolicy>(other.storage_.policy_));
+ storage_.length_ = other.storage_.length_;
+}
+
+#if JSON_HAS_RVALUE_REFERENCES
+Value::CZString::CZString(CZString&& other)
+ : cstr_(other.cstr_), index_(other.index_) {
+ other.cstr_ = nullptr;
+}
+#endif
+
+Value::CZString::~CZString() {
+ if (cstr_ && storage_.policy_ == duplicate)
+ releaseStringValue(const_cast<char*>(cstr_));
+}
+
+void Value::CZString::swap(CZString& other) {
+ std::swap(cstr_, other.cstr_);
+ std::swap(index_, other.index_);
+}
+
+Value::CZString& Value::CZString::operator=(CZString other) {
+ swap(other);
+ return *this;
+}
+
+bool Value::CZString::operator<(const CZString& other) const {
+ if (!cstr_) return index_ < other.index_;
+ //return strcmp(cstr_, other.cstr_) < 0;
+ // Assume both are strings.
+ unsigned this_len = this->storage_.length_;
+ unsigned other_len = other.storage_.length_;
+ unsigned min_len = std::min(this_len, other_len);
+ int comp = memcmp(this->cstr_, other.cstr_, min_len);
+ if (comp < 0) return true;
+ if (comp > 0) return false;
+ return (this_len < other_len);
+}
+
+bool Value::CZString::operator==(const CZString& other) const {
+ if (!cstr_) return index_ == other.index_;
+ //return strcmp(cstr_, other.cstr_) == 0;
+ // Assume both are strings.
+ unsigned this_len = this->storage_.length_;
+ unsigned other_len = other.storage_.length_;
+ if (this_len != other_len) return false;
+ int comp = memcmp(this->cstr_, other.cstr_, this_len);
+ return comp == 0;
+}
+
+ArrayIndex Value::CZString::index() const { return index_; }
+
+//const char* Value::CZString::c_str() const { return cstr_; }
+const char* Value::CZString::data() const { return cstr_; }
+unsigned Value::CZString::length() const { return storage_.length_; }
+bool Value::CZString::isStaticString() const { return storage_.policy_ == noDuplication; }
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class Value::Value
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+/*! \internal Default constructor initialization must be equivalent to:
+ * memset( this, 0, sizeof(Value) )
+ * This optimization is used in ValueInternalMap fast allocator.
+ */
+Value::Value(ValueType vtype) {
+ initBasic(vtype);
+ switch (vtype) {
+ case nullValue:
+ break;
+ case intValue:
+ case uintValue:
+ value_.int_ = 0;
+ break;
+ case realValue:
+ value_.real_ = 0.0;
+ break;
+ case stringValue:
+ value_.string_ = 0;
+ break;
+ case arrayValue:
+ case objectValue:
+ value_.map_ = new ObjectValues();
+ break;
+ case booleanValue:
+ value_.bool_ = false;
+ break;
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+}
+
+Value::Value(Int value) {
+ initBasic(intValue);
+ value_.int_ = value;
+}
+
+Value::Value(UInt value) {
+ initBasic(uintValue);
+ value_.uint_ = value;
+}
+#if defined(JSON_HAS_INT64)
+Value::Value(Int64 value) {
+ initBasic(intValue);
+ value_.int_ = value;
+}
+Value::Value(UInt64 value) {
+ initBasic(uintValue);
+ value_.uint_ = value;
+}
+#endif // defined(JSON_HAS_INT64)
+
+Value::Value(double value) {
+ initBasic(realValue);
+ value_.real_ = value;
+}
+
+Value::Value(const char* value) {
+ initBasic(stringValue, true);
+ value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(strlen(value)));
+}
+
+Value::Value(const char* beginValue, const char* endValue) {
+ initBasic(stringValue, true);
+ value_.string_ =
+ duplicateAndPrefixStringValue(beginValue, static_cast<unsigned>(endValue - beginValue));
+}
+
+Value::Value(const std::string& value) {
+ initBasic(stringValue, true);
+ value_.string_ =
+ duplicateAndPrefixStringValue(value.data(), static_cast<unsigned>(value.length()));
+}
+
+Value::Value(const StaticString& value) {
+ initBasic(stringValue);
+ value_.string_ = const_cast<char*>(value.c_str());
+}
+
+#ifdef JSON_USE_CPPTL
+Value::Value(const CppTL::ConstString& value) {
+ initBasic(stringValue, true);
+ value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(value.length()));
+}
+#endif
+
+Value::Value(bool value) {
+ initBasic(booleanValue);
+ value_.bool_ = value;
+}
+
+Value::Value(Value const& other)
+ : type_(other.type_), allocated_(false)
+ ,
+ comments_(nullptr), default_value_(nullptr), start_(other.start_), limit_(other.limit_)
+{
+ switch (type_) {
+ case nullValue:
+ case intValue:
+ case uintValue:
+ case realValue:
+ case booleanValue:
+ value_ = other.value_;
+ break;
+ case stringValue:
+ if (other.value_.string_ && other.allocated_) {
+ unsigned len;
+ char const* str;
+ decodePrefixedString(other.allocated_, other.value_.string_,
+ &len, &str);
+ value_.string_ = duplicateAndPrefixStringValue(str, len);
+ allocated_ = true;
+ } else {
+ value_.string_ = other.value_.string_;
+ allocated_ = false;
+ }
+ break;
+ case arrayValue:
+ case objectValue:
+ value_.map_ = new ObjectValues(*other.value_.map_);
+ break;
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+ if (other.comments_) {
+ comments_ = new CommentInfo[numberOfCommentPlacement];
+ for (int comment = 0; comment < numberOfCommentPlacement; ++comment) {
+ const CommentInfo& otherComment = other.comments_[comment];
+ if (otherComment.comment_)
+ comments_[comment].setComment(
+ otherComment.comment_, strlen(otherComment.comment_));
+ }
+ }
+
+ if ( other.default_value_ )
+ {
+ default_value_ = new Value( *other.default_value_ );
+ }
+
+}
+
+#if JSON_HAS_RVALUE_REFERENCES
+// Move constructor
+Value::Value(Value&& other) {
+ initBasic(nullValue);
+ swap(other);
+}
+#endif
+
+Value::~Value() {
+ switch (type_) {
+ case nullValue:
+ case intValue:
+ case uintValue:
+ case realValue:
+ case booleanValue:
+ break;
+ case stringValue:
+ if (allocated_)
+ releaseStringValue(value_.string_);
+ break;
+ case arrayValue:
+ case objectValue:
+ delete value_.map_;
+ break;
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+
+ if (comments_)
+ delete[] comments_;
+
+ if ( default_value_)
+ delete default_value_;
+}
+
+Value& Value::operator=(Value other) {
+ swap(other);
+ return *this;
+}
+
+void Value::swapPayload(Value& other) {
+ ValueType temp = type_;
+ type_ = other.type_;
+ other.type_ = temp;
+ std::swap(value_, other.value_);
+ int temp2 = allocated_;
+ allocated_ = other.allocated_;
+ other.allocated_ = temp2 & 0x1;
+}
+
+void Value::swap(Value& other) {
+ swapPayload(other);
+ std::swap(comments_, other.comments_);
+ std::swap(default_value_, other.default_value_);
+ std::swap(start_, other.start_);
+ std::swap(limit_, other.limit_);
+}
+
+ValueType Value::type() const { return type_; }
+
+int Value::compare(const Value& other) const {
+ if (*this < other)
+ return -1;
+ if (*this > other)
+ return 1;
+ return 0;
+}
+
+bool Value::operator<(const Value& other) const {
+ int typeDelta = type_ - other.type_;
+ if (typeDelta)
+ return typeDelta < 0 ? true : false;
+ switch (type_) {
+ case nullValue:
+ return false;
+ case intValue:
+ return value_.int_ < other.value_.int_;
+ case uintValue:
+ return value_.uint_ < other.value_.uint_;
+ case realValue:
+ return value_.real_ < other.value_.real_;
+ case booleanValue:
+ return value_.bool_ < other.value_.bool_;
+ case stringValue:
+ {
+ if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
+ if (other.value_.string_) return true;
+ else return false;
+ }
+ unsigned this_len;
+ unsigned other_len;
+ char const* this_str;
+ char const* other_str;
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
+ decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
+ unsigned min_len = std::min(this_len, other_len);
+ int comp = memcmp(this_str, other_str, min_len);
+ if (comp < 0) return true;
+ if (comp > 0) return false;
+ return (this_len < other_len);
+ }
+ case arrayValue:
+ case objectValue: {
+ int delta = int(value_.map_->size() - other.value_.map_->size());
+ if (delta)
+ return delta < 0;
+ return (*value_.map_) < (*other.value_.map_);
+ }
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+ return false; // unreachable
+}
+
+bool Value::operator<=(const Value& other) const { return !(other < *this); }
+
+bool Value::operator>=(const Value& other) const { return !(*this < other); }
+
+bool Value::operator>(const Value& other) const { return other < *this; }
+
+bool Value::operator==(const Value& other) const {
+ // if ( type_ != other.type_ )
+ // GCC 2.95.3 says:
+ // attempt to take address of bit-field structure member `Json::Value::type_'
+ // Beats me, but a temp solves the problem.
+ int temp = other.type_;
+ if (type_ != temp)
+ return false;
+ switch (type_) {
+ case nullValue:
+ return true;
+ case intValue:
+ return value_.int_ == other.value_.int_;
+ case uintValue:
+ return value_.uint_ == other.value_.uint_;
+ case realValue:
+ return value_.real_ == other.value_.real_;
+ case booleanValue:
+ return value_.bool_ == other.value_.bool_;
+ case stringValue:
+ {
+ if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
+ return (value_.string_ == other.value_.string_);
+ }
+ unsigned this_len;
+ unsigned other_len;
+ char const* this_str;
+ char const* other_str;
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
+ decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
+ if (this_len != other_len) return false;
+ int comp = memcmp(this_str, other_str, this_len);
+ return comp == 0;
+ }
+ case arrayValue:
+ case objectValue:
+ return value_.map_->size() == other.value_.map_->size() &&
+ (*value_.map_) == (*other.value_.map_);
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+ return false; // unreachable
+}
+
+bool Value::operator!=(const Value& other) const { return !(*this == other); }
+
+const char* Value::asCString() const {
+ JSON_ASSERT_MESSAGE(type_ == stringValue,
+ "in Json::Value::asCString(): requires stringValue");
+ if (value_.string_ == 0) return 0;
+ unsigned this_len;
+ char const* this_str;
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
+ return this_str;
+}
+
+bool Value::getString(char const** str, char const** cend) const {
+ if (type_ != stringValue) return false;
+ if (value_.string_ == 0) return false;
+ unsigned length;
+ decodePrefixedString(this->allocated_, this->value_.string_, &length, str);
+ *cend = *str + length;
+ return true;
+}
+
+std::string Value::asString() const {
+ switch (type_) {
+ case nullValue:
+ return "";
+ case stringValue:
+ {
+ if (value_.string_ == 0) return "";
+ unsigned this_len;
+ char const* this_str;
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
+ return std::string(this_str, this_len);
+ }
+ case booleanValue:
+ return value_.bool_ ? "true" : "false";
+ case intValue:
+ return valueToString(value_.int_);
+ case uintValue:
+ return valueToString(value_.uint_);
+ case realValue:
+ return valueToString(value_.real_);
+ default:
+ if ( default_value_ )
+ return default_value_->asString();
+ else
+ return "";
+ }
+}
+
+#ifdef JSON_USE_CPPTL
+CppTL::ConstString Value::asConstString() const {
+ unsigned len;
+ char const* str;
+ decodePrefixedString(allocated_, value_.string_,
+ &len, &str);
+ return CppTL::ConstString(str, len);
+}
+#endif
+
+Value::Int Value::asInt() const {
+ switch (type_) {
+ case intValue:
+ JSON_ASSERT_MESSAGE(isInt(), "LargestInt out of Int range");
+ return Int(value_.int_);
+ case uintValue:
+ JSON_ASSERT_MESSAGE(isInt(), "LargestUInt out of Int range");
+ return Int(value_.uint_);
+ case realValue:
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt, maxInt),
+ "double out of Int range");
+ return Int(value_.real_);
+ case nullValue:
+ return 0;
+ case booleanValue:
+ return value_.bool_ ? 1 : 0;
+ default:
+ if ( default_value_ )
+ return default_value_->asInt();
+ else
+ return 0;
+ }
+}
+
+Value::UInt Value::asUInt() const {
+ switch (type_) {
+ case intValue:
+ JSON_ASSERT_MESSAGE(isUInt(), "LargestInt out of UInt range");
+ return UInt(value_.int_);
+ case uintValue:
+ JSON_ASSERT_MESSAGE(isUInt(), "LargestUInt out of UInt range");
+ return UInt(value_.uint_);
+ case realValue:
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt),
+ "double out of UInt range");
+ return UInt(value_.real_);
+ case nullValue:
+ return 0;
+ case booleanValue:
+ return value_.bool_ ? 1 : 0;
+ default:
+ if ( default_value_ )
+ return default_value_->asUInt();
+ else
+ return 0u;
+ }
+}
+
+#if defined(JSON_HAS_INT64)
+
+Value::Int64 Value::asInt64() const {
+ switch (type_) {
+ case intValue:
+ return Int64(value_.int_);
+ case uintValue:
+ JSON_ASSERT_MESSAGE(isInt64(), "LargestUInt out of Int64 range");
+ return Int64(value_.uint_);
+ case realValue:
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt64, maxInt64),
+ "double out of Int64 range");
+ return Int64(value_.real_);
+ case nullValue:
+ return 0;
+ case booleanValue:
+ return value_.bool_ ? 1 : 0;
+ default:
+ if ( default_value_ )
+ return default_value_->asInt64();
+ else
+ return 0l;
+ }
+}
+
+Value::UInt64 Value::asUInt64() const {
+ switch (type_) {
+ case intValue:
+ JSON_ASSERT_MESSAGE(isUInt64(), "LargestInt out of UInt64 range");
+ return UInt64(value_.int_);
+ case uintValue:
+ return UInt64(value_.uint_);
+ case realValue:
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt64),
+ "double out of UInt64 range");
+ return UInt64(value_.real_);
+ case nullValue:
+ return 0;
+ case booleanValue:
+ return value_.bool_ ? 1 : 0;
+ default:
+ if ( default_value_ )
+ return default_value_->asUInt64();
+ else
+ return 0ul;
+ }
+}
+#endif // if defined(JSON_HAS_INT64)
+
+LargestInt Value::asLargestInt() const {
+#if defined(JSON_NO_INT64)
+ return asInt();
+#else
+ return asInt64();
+#endif
+}
+
+LargestUInt Value::asLargestUInt() const {
+#if defined(JSON_NO_INT64)
+ return asUInt();
+#else
+ return asUInt64();
+#endif
+}
+
+double Value::asDouble() const {
+ switch (type_) {
+ case intValue:
+ return static_cast<double>(value_.int_);
+ case uintValue:
+#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ return static_cast<double>(value_.uint_);
+#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ return integerToDouble(value_.uint_);
+#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ case realValue:
+ return value_.real_;
+ case nullValue:
+ return 0.0;
+ case booleanValue:
+ return value_.bool_ ? 1.0 : 0.0;
+ default:
+ if ( default_value_ )
+ return default_value_->asDouble();
+ else
+ return 0.0;
+ }
+}
+
+float Value::asFloat() const {
+ switch (type_) {
+ case intValue:
+ return static_cast<float>(value_.int_);
+ case uintValue:
+#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ return static_cast<float>(value_.uint_);
+#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ return integerToDouble(value_.uint_);
+#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ case realValue:
+ return static_cast<float>(value_.real_);
+ case nullValue:
+ return 0.0;
+ case booleanValue:
+ return value_.bool_ ? 1.0f : 0.0f;
+ default:
+ if ( default_value_ )
+ return default_value_->asFloat();
+ else
+ return 0.0f;
+ }
+}
+
+bool Value::asBool() const {
+ switch (type_) {
+ case booleanValue:
+ return value_.bool_;
+ case nullValue:
+ return false;
+ case intValue:
+ return value_.int_ ? true : false;
+ case uintValue:
+ return value_.uint_ ? true : false;
+ case realValue:
+ // This is kind of strange. Not recommended.
+ return (value_.real_ != 0.0) ? true : false;
+ default:
+ if ( default_value_ )
+ return default_value_->asBool();
+ else
+ return false;
+ }
+}
+
+bool Value::isConvertibleTo(ValueType other) const {
+ switch (other) {
+ case nullValue:
+ return (isNumeric() && asDouble() == 0.0) ||
+ (type_ == booleanValue && value_.bool_ == false) ||
+ (type_ == stringValue && asString() == "") ||
+ (type_ == arrayValue && value_.map_->size() == 0) ||
+ (type_ == objectValue && value_.map_->size() == 0) ||
+ type_ == nullValue;
+ case intValue:
+ return isInt() ||
+ (type_ == realValue && InRange(value_.real_, minInt, maxInt)) ||
+ type_ == booleanValue || type_ == nullValue;
+ case uintValue:
+ return isUInt() ||
+ (type_ == realValue && InRange(value_.real_, 0, maxUInt)) ||
+ type_ == booleanValue || type_ == nullValue;
+ case realValue:
+ return isNumeric() || type_ == booleanValue || type_ == nullValue;
+ case booleanValue:
+ return isNumeric() || type_ == booleanValue || type_ == nullValue;
+ case stringValue:
+ return isNumeric() || type_ == booleanValue || type_ == stringValue ||
+ type_ == nullValue;
+ case arrayValue:
+ return type_ == arrayValue || type_ == nullValue;
+ case objectValue:
+ return type_ == objectValue || type_ == nullValue;
+ }
+ JSON_ASSERT_UNREACHABLE;
+ return false;
+}
+
+/// Number of values in array or object
+ArrayIndex Value::size() const {
+ switch (type_) {
+ case nullValue:
+ case intValue:
+ case uintValue:
+ case realValue:
+ case booleanValue:
+ case stringValue:
+ return 0;
+ case arrayValue: // size of the array is highest index + 1
+ if (!value_.map_->empty()) {
+ ObjectValues::const_iterator itLast = value_.map_->end();
+ --itLast;
+ return (*itLast).first.index() + 1;
+ }
+ return 0;
+ case objectValue:
+ return ArrayIndex(value_.map_->size());
+ }
+ JSON_ASSERT_UNREACHABLE;
+ return 0; // unreachable;
+}
+
+bool Value::empty() const {
+ if (isNull() || isArray() || isObject())
+ return size() == 0u;
+ else
+ return false;
+}
+
+bool Value::operator!() const { return isNull(); }
+
+void Value::clear() {
+ JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue ||
+ type_ == objectValue,
+ "in Json::Value::clear(): requires complex value");
+ start_ = 0;
+ limit_ = 0;
+ delete default_value_;
+ default_value_ = nullptr;
+ switch (type_) {
+ case arrayValue:
+ case objectValue:
+ value_.map_->clear();
+ break;
+ default:
+ break;
+ }
+}
+
+void Value::resize(ArrayIndex newSize) {
+ JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue,
+ "in Json::Value::resize(): requires arrayValue");
+ if (type_ == nullValue)
+ *this = Value(arrayValue);
+ ArrayIndex oldSize = size();
+ if (newSize == 0)
+ clear();
+ else if (newSize > oldSize)
+ (*this)[newSize - 1];
+ else {
+ for (ArrayIndex index = newSize; index < oldSize; ++index) {
+ value_.map_->erase(index);
+ }
+ assert(size() == newSize);
+ }
+}
+
+Value& Value::operator[](ArrayIndex index) {
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == arrayValue,
+ "in Json::Value::operator[](ArrayIndex): requires arrayValue");
+ if (type_ == nullValue)
+ *this = Value(arrayValue);
+ CZString key(index);
+ ObjectValues::iterator it = value_.map_->lower_bound(key);
+ if (it != value_.map_->end() && (*it).first == key)
+ return (*it).second;
+
+ ObjectValues::value_type defaultValue(key, nullRef);
+ it = value_.map_->insert(it, defaultValue);
+ return (*it).second;
+}
+
+Value& Value::operator[](int index) {
+ JSON_ASSERT_MESSAGE(
+ index >= 0,
+ "in Json::Value::operator[](int index): index cannot be negative");
+ return (*this)[ArrayIndex(index)];
+}
+
+const Value& Value::operator[](ArrayIndex index) const {
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == arrayValue,
+ "in Json::Value::operator[](ArrayIndex)const: requires arrayValue");
+ if (type_ == nullValue)
+ return nullRef;
+ CZString key(index);
+ ObjectValues::const_iterator it = value_.map_->find(key);
+ if (it == value_.map_->end())
+ return nullRef;
+ return (*it).second;
+}
+
+const Value& Value::operator[](int index) const {
+ JSON_ASSERT_MESSAGE(
+ index >= 0,
+ "in Json::Value::operator[](int index) const: index cannot be negative");
+ return (*this)[ArrayIndex(index)];
+}
+
+void Value::initBasic(ValueType vtype, bool allocated) {
+ type_ = vtype;
+ allocated_ = allocated;
+ comments_ = 0;
+ start_ = 0;
+ limit_ = 0;
+ default_value_ = nullptr;
+}
+
+// Access an object value by name, create a null member if it does not exist.
+// @pre Type of '*this' is object or null.
+// @param key is null-terminated.
+Value& Value::resolveReference(const char* key) {
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == objectValue,
+ "in Json::Value::resolveReference(): requires objectValue");
+ if (type_ == nullValue)
+ *this = Value(objectValue);
+ CZString actualKey(
+ key, static_cast<unsigned>(strlen(key)), CZString::noDuplication); // NOTE!
+ ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
+ if (it != value_.map_->end() && (*it).first == actualKey)
+ return (*it).second;
+
+ ObjectValues::value_type defaultValue(actualKey, nullRef);
+ it = value_.map_->insert(it, defaultValue);
+ Value& value = (*it).second;
+ return value;
+}
+
+// @param key is not null-terminated.
+Value& Value::resolveReference(char const* key, char const* cend)
+{
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == objectValue,
+ "in Json::Value::resolveReference(key, end): requires objectValue");
+ if (type_ == nullValue)
+ *this = Value(objectValue);
+ CZString actualKey(
+ key, static_cast<unsigned>(cend-key), CZString::duplicateOnCopy);
+ ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
+ if (it != value_.map_->end() && (*it).first == actualKey)
+ return (*it).second;
+
+ ObjectValues::value_type defaultValue(actualKey, nullRef);
+ it = value_.map_->insert(it, defaultValue);
+ Value& value = (*it).second;
+ return value;
+}
+
+Value Value::get(ArrayIndex index, const Value& defaultValue) const {
+ const Value* value = &((*this)[index]);
+ if ( value == &nullRef )
+ {
+ return defaultValue;
+ }
+ else
+ {
+ Value result = *value;
+ result.default_value_ = new Value( defaultValue );
+ return result;
+ }
+}
+
+bool Value::isValidIndex(ArrayIndex index) const { return index < size(); }
+
+Value const* Value::find(char const* key, char const* cend) const
+{
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == objectValue,
+ "in Json::Value::find(key, end, found): requires objectValue or nullValue");
+ if (type_ == nullValue) return NULL;
+ CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
+ ObjectValues::const_iterator it = value_.map_->find(actualKey);
+ if (it == value_.map_->end()) return NULL;
+ return &(*it).second;
+}
+const Value& Value::operator[](const char* key) const
+{
+ Value const* found = find(key, key + strlen(key));
+ if (!found) return nullRef;
+ return *found;
+}
+Value const& Value::operator[](std::string const& key) const
+{
+ Value const* found = find(key.data(), key.data() + key.length());
+ if (!found) return nullRef;
+ return *found;
+}
+
+Value& Value::operator[](const char* key) {
+ return resolveReference(key, key + strlen(key));
+}
+
+Value& Value::operator[](const std::string& key) {
+ return resolveReference(key.data(), key.data() + key.length());
+}
+
+Value& Value::operator[](const StaticString& key) {
+ return resolveReference(key.c_str());
+}
+
+#ifdef JSON_USE_CPPTL
+Value& Value::operator[](const CppTL::ConstString& key) {
+ return resolveReference(key.c_str(), key.end_c_str());
+}
+Value const& Value::operator[](CppTL::ConstString const& key) const
+{
+ Value const* found = find(key.c_str(), key.end_c_str());
+ if (!found) return nullRef;
+ return *found;
+}
+#endif
+
+Value& Value::append(const Value& value) { return (*this)[size()] = value; }
+
+Value Value::get(char const* key, char const* cend, Value const& defaultValue) const
+{
+ Value const* found = find(key, cend);
+ if ( !found )
+ {
+ return defaultValue;
+ }
+ else
+ {
+ Value result = *found;
+ result.default_value_ = new Value( defaultValue );
+ return result;
+ }
+}
+Value Value::get(char const* key, Value const& defaultValue) const
+{
+ return get(key, key + strlen(key), defaultValue);
+}
+Value Value::get(std::string const& key, Value const& defaultValue) const
+{
+ return get(key.data(), key.data() + key.length(), defaultValue);
+}
+
+
+bool Value::removeMember(const char* key, const char* cend, Value* removed)
+{
+ if (type_ != objectValue) {
+ return false;
+ }
+ CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
+ ObjectValues::iterator it = value_.map_->find(actualKey);
+ if (it == value_.map_->end())
+ return false;
+ *removed = it->second;
+ value_.map_->erase(it);
+ return true;
+}
+bool Value::removeMember(const char* key, Value* removed)
+{
+ return removeMember(key, key + strlen(key), removed);
+}
+bool Value::removeMember(std::string const& key, Value* removed)
+{
+ return removeMember(key.data(), key.data() + key.length(), removed);
+}
+Value Value::removeMember(const char* key)
+{
+ JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == objectValue,
+ "in Json::Value::removeMember(): requires objectValue");
+ if (type_ == nullValue)
+ return nullRef;
+
+ Value removed; // null
+ removeMember(key, key + strlen(key), &removed);
+ return removed; // still null if removeMember() did nothing
+}
+Value Value::removeMember(const std::string& key)
+{
+ return removeMember(key.c_str());
+}
+
+bool Value::removeIndex(ArrayIndex index, Value* removed) {
+ if (type_ != arrayValue) {
+ return false;
+ }
+ CZString key(index);
+ ObjectValues::iterator it = value_.map_->find(key);
+ if (it == value_.map_->end()) {
+ return false;
+ }
+ *removed = it->second;
+ ArrayIndex oldSize = size();
+ // shift left all items left, into the place of the "removed"
+ for (ArrayIndex i = index; i < (oldSize - 1); ++i){
+ CZString keey(i);
+ (*value_.map_)[keey] = (*this)[i + 1];
+ }
+ // erase the last one ("leftover")
+ CZString keyLast(oldSize - 1);
+ ObjectValues::iterator itLast = value_.map_->find(keyLast);
+ value_.map_->erase(itLast);
+ return true;
+}
+
+#ifdef JSON_USE_CPPTL
+Value Value::get(const CppTL::ConstString& key,
+ const Value& defaultValue) const {
+ return get(key.c_str(), key.end_c_str(), defaultValue);
+}
+#endif
+
+bool Value::isMember(char const* key, char const* cend) const
+{
+ Value const* value = find(key, cend);
+ return NULL != value;
+}
+bool Value::isMember(char const* key) const
+{
+ return isMember(key, key + strlen(key));
+}
+bool Value::isMember(std::string const& key) const
+{
+ return isMember(key.data(), key.data() + key.length());
+}
+
+#ifdef JSON_USE_CPPTL
+bool Value::isMember(const CppTL::ConstString& key) const {
+ return isMember(key.c_str(), key.end_c_str());
+}
+#endif
+
+Value::Members Value::getMemberNames() const {
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == objectValue,
+ "in Json::Value::getMemberNames(), value must be objectValue");
+ if (type_ == nullValue)
+ return Value::Members();
+ Members members;
+ members.reserve(value_.map_->size());
+ ObjectValues::const_iterator it = value_.map_->begin();
+ ObjectValues::const_iterator itEnd = value_.map_->end();
+ for (; it != itEnd; ++it) {
+ members.push_back(std::string((*it).first.data(),
+ (*it).first.length()));
+ }
+ return members;
+}
+//
+//# ifdef JSON_USE_CPPTL
+// EnumMemberNames
+// Value::enumMemberNames() const
+//{
+// if ( type_ == objectValue )
+// {
+// return CppTL::Enum::any( CppTL::Enum::transform(
+// CppTL::Enum::keys( *(value_.map_), CppTL::Type<const CZString &>() ),
+// MemberNamesTransform() ) );
+// }
+// return EnumMemberNames();
+//}
+//
+//
+// EnumValues
+// Value::enumValues() const
+//{
+// if ( type_ == objectValue || type_ == arrayValue )
+// return CppTL::Enum::anyValues( *(value_.map_),
+// CppTL::Type<const Value &>() );
+// return EnumValues();
+//}
+//
+//# endif
+
+static bool IsIntegral(double d) {
+ double integral_part;
+ return modf(d, &integral_part) == 0.0;
+}
+
+bool Value::isNull() const { return type_ == nullValue; }
+
+bool Value::isBool() const { return type_ == booleanValue; }
+
+bool Value::isInt() const {
+ switch (type_) {
+ case intValue:
+ return value_.int_ >= minInt && value_.int_ <= maxInt;
+ case uintValue:
+ return value_.uint_ <= UInt(maxInt);
+ case realValue:
+ return value_.real_ >= minInt && value_.real_ <= maxInt &&
+ IsIntegral(value_.real_);
+ default:
+ break;
+ }
+ return false;
+}
+
+bool Value::isUInt() const {
+ switch (type_) {
+ case intValue:
+ return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt);
+ case uintValue:
+ return value_.uint_ <= maxUInt;
+ case realValue:
+ return value_.real_ >= 0 && value_.real_ <= maxUInt &&
+ IsIntegral(value_.real_);
+ default:
+ break;
+ }
+ return false;
+}
+
+bool Value::isInt64() const {
+#if defined(JSON_HAS_INT64)
+ switch (type_) {
+ case intValue:
+ return true;
+ case uintValue:
+ return value_.uint_ <= UInt64(maxInt64);
+ case realValue:
+ // Note that maxInt64 (= 2^63 - 1) is not exactly representable as a
+ // double, so double(maxInt64) will be rounded up to 2^63. Therefore we
+ // require the value to be strictly less than the limit.
+ return value_.real_ >= double(minInt64) &&
+ value_.real_ < double(maxInt64) && IsIntegral(value_.real_);
+ default:
+ break;
+ }
+#endif // JSON_HAS_INT64
+ return false;
+}
+
+bool Value::isUInt64() const {
+#if defined(JSON_HAS_INT64)
+ switch (type_) {
+ case intValue:
+ return value_.int_ >= 0;
+ case uintValue:
+ return true;
+ case realValue:
+ // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a
+ // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we
+ // require the value to be strictly less than the limit.
+ return value_.real_ >= 0 && value_.real_ < maxUInt64AsDouble &&
+ IsIntegral(value_.real_);
+ default:
+ break;
+ }
+#endif // JSON_HAS_INT64
+ return false;
+}
+
+bool Value::isIntegral() const {
+#if defined(JSON_HAS_INT64)
+ return isInt64() || isUInt64();
+#else
+ return isInt() || isUInt();
+#endif
+}
+
+bool Value::isDouble() const { return type_ == realValue || isIntegral(); }
+
+bool Value::isNumeric() const { return isIntegral() || isDouble(); }
+
+bool Value::isString() const { return type_ == stringValue; }
+
+bool Value::isArray() const { return type_ == arrayValue; }
+
+bool Value::isObject() const { return type_ == objectValue; }
+
+void Value::setComment(const char* comment, size_t len, CommentPlacement placement) {
+ if (!comments_)
+ comments_ = new CommentInfo[numberOfCommentPlacement];
+ if ((len > 0) && (comment[len-1] == '\n')) {
+ // Always discard trailing newline, to aid indentation.
+ len -= 1;
+ }
+ comments_[placement].setComment(comment, len);
+}
+
+void Value::setComment(const char* comment, CommentPlacement placement) {
+ setComment(comment, strlen(comment), placement);
+}
+
+void Value::setComment(const std::string& comment, CommentPlacement placement) {
+ setComment(comment.c_str(), comment.length(), placement);
+}
+
+bool Value::hasComment(CommentPlacement placement) const {
+ return comments_ != 0 && comments_[placement].comment_ != 0;
+}
+
+std::string Value::getComment(CommentPlacement placement) const {
+ if (hasComment(placement))
+ return comments_[placement].comment_;
+ return "";
+}
+
+void Value::setOffsetStart(size_t start) { start_ = start; }
+
+void Value::setOffsetLimit(size_t limit) { limit_ = limit; }
+
+size_t Value::getOffsetStart() const { return start_; }
+
+size_t Value::getOffsetLimit() const { return limit_; }
+
+std::string Value::toStyledString() const {
+ StyledWriter writer;
+ return writer.write(*this);
+}
+
+Value::const_iterator Value::begin() const {
+ switch (type_) {
+ case arrayValue:
+ case objectValue:
+ if (value_.map_)
+ return const_iterator(value_.map_->begin());
+ break;
+ default:
+ break;
+ }
+ return const_iterator();
+}
+
+Value::const_iterator Value::end() const {
+ switch (type_) {
+ case arrayValue:
+ case objectValue:
+ if (value_.map_)
+ return const_iterator(value_.map_->end());
+ break;
+ default:
+ break;
+ }
+ return const_iterator();
+}
+
+Value::iterator Value::begin() {
+ switch (type_) {
+ case arrayValue:
+ case objectValue:
+ if (value_.map_)
+ return iterator(value_.map_->begin());
+ break;
+ default:
+ break;
+ }
+ return iterator();
+}
+
+Value::iterator Value::end() {
+ switch (type_) {
+ case arrayValue:
+ case objectValue:
+ if (value_.map_)
+ return iterator(value_.map_->end());
+ break;
+ default:
+ break;
+ }
+ return iterator();
+}
+
+// class PathArgument
+// //////////////////////////////////////////////////////////////////
+
+PathArgument::PathArgument() : key_(), index_(), kind_(kindNone) {}
+
+PathArgument::PathArgument(ArrayIndex index)
+ : key_(), index_(index), kind_(kindIndex) {}
+
+PathArgument::PathArgument(const char* key)
+ : key_(key), index_(), kind_(kindKey) {}
+
+PathArgument::PathArgument(const std::string& key)
+ : key_(key.c_str()), index_(), kind_(kindKey) {}
+
+// class Path
+// //////////////////////////////////////////////////////////////////
+
+Path::Path(const std::string& path,
+ const PathArgument& a1,
+ const PathArgument& a2,
+ const PathArgument& a3,
+ const PathArgument& a4,
+ const PathArgument& a5) {
+ InArgs in;
+ in.push_back(&a1);
+ in.push_back(&a2);
+ in.push_back(&a3);
+ in.push_back(&a4);
+ in.push_back(&a5);
+ makePath(path, in);
+}
+
+void Path::makePath(const std::string& path, const InArgs& in) {
+ const char* current = path.c_str();
+ const char* end = current + path.length();
+ InArgs::const_iterator itInArg = in.begin();
+ while (current != end) {
+ if (*current == '[') {
+ ++current;
+ if (*current == '%')
+ addPathInArg(path, in, itInArg, PathArgument::kindIndex);
+ else {
+ ArrayIndex index = 0;
+ for (; current != end && *current >= '0' && *current <= '9'; ++current)
+ index = index * 10 + ArrayIndex(*current - '0');
+ args_.push_back(index);
+ }
+ if (current == end || *current++ != ']')
+ invalidPath(path, int(current - path.c_str()));
+ } else if (*current == '%') {
+ addPathInArg(path, in, itInArg, PathArgument::kindKey);
+ ++current;
+ } else if (*current == '.') {
+ ++current;
+ } else {
+ const char* beginName = current;
+ while (current != end && !strchr("[.", *current))
+ ++current;
+ args_.push_back(std::string(beginName, current));
+ }
+ }
+}
+
+void Path::addPathInArg(const std::string& /*path*/,
+ const InArgs& in,
+ InArgs::const_iterator& itInArg,
+ PathArgument::Kind kind) {
+ if (itInArg == in.end()) {
+ // Error: missing argument %d
+ } else if ((*itInArg)->kind_ != kind) {
+ // Error: bad argument type
+ } else {
+ args_.push_back(**itInArg);
+ }
+}
+
+void Path::invalidPath(const std::string& /*path*/, int /*location*/) {
+ // Error: invalid path.
+}
+
+const Value& Path::resolve(const Value& root) const {
+ const Value* node = &root;
+ for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
+ const PathArgument& arg = *it;
+ if (arg.kind_ == PathArgument::kindIndex) {
+ if (!node->isArray() || !node->isValidIndex(arg.index_)) {
+ // Error: unable to resolve path (array value expected at position...
+ }
+ node = &((*node)[arg.index_]);
+ } else if (arg.kind_ == PathArgument::kindKey) {
+ if (!node->isObject()) {
+ // Error: unable to resolve path (object value expected at position...)
+ }
+ node = &((*node)[arg.key_]);
+ if (node == &Value::nullRef) {
+ // Error: unable to resolve path (object has no member named '' at
+ // position...)
+ }
+ }
+ }
+ return *node;
+}
+
+Value Path::resolve(const Value& root, const Value& defaultValue) const {
+ const Value* node = &root;
+ for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
+ const PathArgument& arg = *it;
+ if (arg.kind_ == PathArgument::kindIndex) {
+ if (!node->isArray() || !node->isValidIndex(arg.index_))
+ return defaultValue;
+ node = &((*node)[arg.index_]);
+ } else if (arg.kind_ == PathArgument::kindKey) {
+ if (!node->isObject())
+ return defaultValue;
+ node = &((*node)[arg.key_]);
+ if (node == &Value::nullRef)
+ return defaultValue;
+ }
+ }
+ return *node;
+}
+
+Value& Path::make(Value& root) const {
+ Value* node = &root;
+ for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
+ const PathArgument& arg = *it;
+ if (arg.kind_ == PathArgument::kindIndex) {
+ if (!node->isArray()) {
+ // Error: node is not an array at position ...
+ }
+ node = &((*node)[arg.index_]);
+ } else if (arg.kind_ == PathArgument::kindKey) {
+ if (!node->isObject()) {
+ // Error: node is not an object at position...
+ }
+ node = &((*node)[arg.key_]);
+ }
+ }
+ return *node;
+}
+
+} // namespace Json
+
+#pragma warning (pop)
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: src/lib_json/json_value.cpp
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_writer.cpp
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2011 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include <json/writer.h>
+#include "json_tool.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <iomanip>
+#include <memory>
+#include <sstream>
+#include <utility>
+#include <set>
+#include <cassert>
+#include <cstring>
+#include <cstdio>
+
+#if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0
+#include <float.h>
+#define isfinite _finite
+#elif defined(__sun) && defined(__SVR4) //Solaris
+#if !defined(isfinite)
+#include <ieeefp.h>
+#define isfinite finite
+#endif
+#elif defined(_AIX)
+#if !defined(isfinite)
+#include <math.h>
+#define isfinite finite
+#endif
+#elif defined(__hpux)
+#if !defined(isfinite)
+#if defined(__ia64) && !defined(finite)
+#define isfinite(x) ((sizeof(x) == sizeof(float) ? \
+ _Isfinitef(x) : _IsFinite(x)))
+#else
+#include <math.h>
+#define isfinite finite
+#endif
+#endif
+#else
+#include <cmath>
+#if !(defined(__QNXNTO__)) // QNX already defines isfinite
+#define isfinite std::isfinite
+#endif
+#endif
+
+#if defined(_MSC_VER)
+#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
+#define snprintf sprintf_s
+#elif _MSC_VER >= 1900 // VC++ 14.0 and above
+#define snprintf std::snprintf
+#else
+#define snprintf _snprintf
+#endif
+#elif defined(__ANDROID__) || defined(__QNXNTO__)
+#define snprintf snprintf
+#elif __cplusplus >= 201103L
+#define snprintf std::snprintf
+#endif
+
+#if defined(__BORLANDC__)
+#include <float.h>
+#define isfinite _finite
+#define snprintf _snprintf
+#endif
+
+#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
+// Disable warning about strdup being deprecated.
+#pragma warning(disable : 4996)
+#endif
+
+namespace Json {
+
+#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
+typedef std::unique_ptr<StreamWriter> StreamWriterPtr;
+#else
+typedef std::auto_ptr<StreamWriter> StreamWriterPtr;
+#endif
+
+static bool containsControlCharacter(const char* str) {
+ while (*str) {
+ if (isControlCharacter(*(str++)))
+ return true;
+ }
+ return false;
+}
+
+static bool containsControlCharacter0(const char* str, unsigned len) {
+ char const* end = str + len;
+ while (end != str) {
+ if (isControlCharacter(*str) || 0==*str)
+ return true;
+ ++str;
+ }
+ return false;
+}
+
+std::string valueToString(LargestInt value) {
+ UIntToStringBuffer buffer;
+ char* current = buffer + sizeof(buffer);
+ if (value == Value::minLargestInt) {
+ uintToString(LargestUInt(Value::maxLargestInt) + 1, current);
+ *--current = '-';
+ } else if (value < 0) {
+ uintToString(LargestUInt(-value), current);
+ *--current = '-';
+ } else {
+ uintToString(LargestUInt(value), current);
+ }
+ assert(current >= buffer);
+ return current;
+}
+
+std::string valueToString(LargestUInt value) {
+ UIntToStringBuffer buffer;
+ char* current = buffer + sizeof(buffer);
+ uintToString(value, current);
+ assert(current >= buffer);
+ return current;
+}
+
+#if defined(JSON_HAS_INT64)
+
+std::string valueToString(Int value) {
+ return valueToString(LargestInt(value));
+}
+
+std::string valueToString(UInt value) {
+ return valueToString(LargestUInt(value));
+}
+
+#endif // # if defined(JSON_HAS_INT64)
+
+std::string valueToString(double value, bool useSpecialFloats, unsigned int precision) {
+ // Allocate a buffer that is more than large enough to store the 16 digits of
+ // precision requested below.
+ char buffer[32];
+ int len = -1;
+
+ char formatString[6];
+ sprintf(formatString, "%%.%dg", precision);
+
+ // Print into the buffer. We need not request the alternative representation
+ // that always has a decimal point because JSON doesn't distingish the
+ // concepts of reals and integers.
+ if (isfinite(value)) {
+ len = snprintf(buffer, sizeof(buffer), formatString, value);
+ } else {
+ // IEEE standard states that NaN values will not compare to themselves
+ if (value != value) {
+ len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "NaN" : "null");
+ } else if (value < 0) {
+ len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "-Infinity" : "-1e+9999");
+ } else {
+ len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "Infinity" : "1e+9999");
+ }
+ // For those, we do not need to call fixNumLoc, but it is fast.
+ }
+ assert(len >= 0);
+ fixNumericLocale(buffer, buffer + len);
+ return buffer;
+}
+
+std::string valueToString(double value) { return valueToString(value, false, 17); }
+
+std::string valueToString(bool value) { return value ? "true" : "false"; }
+
+std::string valueToQuotedString(const char* value) {
+ if (value == NULL)
+ return "";
+ // Not sure how to handle unicode...
+ if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL &&
+ !containsControlCharacter(value))
+ return std::string("\"") + value + "\"";
+ // We have to walk value and escape any special characters.
+ // Appending to std::string is not efficient, but this should be rare.
+ // (Note: forward slashes are *not* rare, but I am not escaping them.)
+ std::string::size_type maxsize =
+ strlen(value) * 2 + 3; // allescaped+quotes+NULL
+ std::string result;
+ result.reserve(maxsize); // to avoid lots of mallocs
+ result += "\"";
+ for (const char* c = value; *c != 0; ++c) {
+ switch (*c) {
+ case '\"':
+ result += "\\\"";
+ break;
+ case '\\':
+ result += "\\\\";
+ break;
+ case '\b':
+ result += "\\b";
+ break;
+ case '\f':
+ result += "\\f";
+ break;
+ case '\n':
+ result += "\\n";
+ break;
+ case '\r':
+ result += "\\r";
+ break;
+ case '\t':
+ result += "\\t";
+ break;
+ // case '/':
+ // Even though \/ is considered a legal escape in JSON, a bare
+ // slash is also legal, so I see no reason to escape it.
+ // (I hope I am not misunderstanding something.
+ // blep notes: actually escaping \/ may be useful in javascript to avoid </
+ // sequence.
+ // Should add a flag to allow this compatibility mode and prevent this
+ // sequence from occurring.
+ default:
+ if (isControlCharacter(*c)) {
+ std::ostringstream oss;
+ oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
+ << std::setw(4) << static_cast<int>(*c);
+ result += oss.str();
+ } else {
+ result += *c;
+ }
+ break;
+ }
+ }
+ result += "\"";
+ return result;
+}
+
+// https://github.com/upcaste/upcaste/blob/master/src/upcore/src/cstring/strnpbrk.cpp
+static char const* strnpbrk(char const* s, char const* accept, size_t n) {
+ assert((s || !n) && accept);
+
+ char const* const end = s + n;
+ for (char const* cur = s; cur < end; ++cur) {
+ int const c = *cur;
+ for (char const* a = accept; *a; ++a) {
+ if (*a == c) {
+ return cur;
+ }
+ }
+ }
+ return NULL;
+}
+static std::string valueToQuotedStringN(const char* value, unsigned length) {
+ if (value == NULL)
+ return "";
+ // Not sure how to handle unicode...
+ if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL &&
+ !containsControlCharacter0(value, length))
+ return std::string("\"") + value + "\"";
+ // We have to walk value and escape any special characters.
+ // Appending to std::string is not efficient, but this should be rare.
+ // (Note: forward slashes are *not* rare, but I am not escaping them.)
+ std::string::size_type maxsize =
+ length * 2 + 3; // allescaped+quotes+NULL
+ std::string result;
+ result.reserve(maxsize); // to avoid lots of mallocs
+ result += "\"";
+ char const* end = value + length;
+ for (const char* c = value; c != end; ++c) {
+ switch (*c) {
+ case '\"':
+ result += "\\\"";
+ break;
+ case '\\':
+ result += "\\\\";
+ break;
+ case '\b':
+ result += "\\b";
+ break;
+ case '\f':
+ result += "\\f";
+ break;
+ case '\n':
+ result += "\\n";
+ break;
+ case '\r':
+ result += "\\r";
+ break;
+ case '\t':
+ result += "\\t";
+ break;
+ // case '/':
+ // Even though \/ is considered a legal escape in JSON, a bare
+ // slash is also legal, so I see no reason to escape it.
+ // (I hope I am not misunderstanding something.)
+ // blep notes: actually escaping \/ may be useful in javascript to avoid </
+ // sequence.
+ // Should add a flag to allow this compatibility mode and prevent this
+ // sequence from occurring.
+ default:
+ if ((isControlCharacter(*c)) || (*c == 0)) {
+ std::ostringstream oss;
+ oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
+ << std::setw(4) << static_cast<int>(*c);
+ result += oss.str();
+ } else {
+ result += *c;
+ }
+ break;
+ }
+ }
+ result += "\"";
+ return result;
+}
+
+// Class Writer
+// //////////////////////////////////////////////////////////////////
+Writer::~Writer() {}
+
+// Class FastWriter
+// //////////////////////////////////////////////////////////////////
+
+FastWriter::FastWriter()
+ : yamlCompatiblityEnabled_(false), dropNullPlaceholders_(false),
+ omitEndingLineFeed_(false) {}
+
+void FastWriter::enableYAMLCompatibility() { yamlCompatiblityEnabled_ = true; }
+
+void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; }
+
+void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; }
+
+std::string FastWriter::write(const Value& root) {
+ document_ = "";
+ writeValue(root);
+ if (!omitEndingLineFeed_)
+ document_ += "\n";
+ return document_;
+}
+
+void FastWriter::writeValue(const Value& value) {
+ switch (value.type()) {
+ case nullValue:
+ if (!dropNullPlaceholders_)
+ document_ += "null";
+ break;
+ case intValue:
+ document_ += valueToString(value.asLargestInt());
+ break;
+ case uintValue:
+ document_ += valueToString(value.asLargestUInt());
+ break;
+ case realValue:
+ document_ += valueToString(value.asDouble());
+ break;
+ case stringValue:
+ {
+ // Is NULL possible for value.string_?
+ char const* str;
+ char const* end;
+ bool ok = value.getString(&str, &end);
+ if (ok) document_ += valueToQuotedStringN(str, static_cast<unsigned>(end-str));
+ break;
+ }
+ case booleanValue:
+ document_ += valueToString(value.asBool());
+ break;
+ case arrayValue: {
+ document_ += '[';
+ int size = value.size();
+ for (int index = 0; index < size; ++index) {
+ if (index > 0)
+ document_ += ',';
+ writeValue(value[index]);
+ }
+ document_ += ']';
+ } break;
+ case objectValue: {
+ Value::Members members(value.getMemberNames());
+ document_ += '{';
+ for (Value::Members::iterator it = members.begin(); it != members.end();
+ ++it) {
+ const std::string& name = *it;
+ if (it != members.begin())
+ document_ += ',';
+ document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
+ document_ += yamlCompatiblityEnabled_ ? ": " : ":";
+ writeValue(value[name]);
+ }
+ document_ += '}';
+ } break;
+ }
+}
+
+// Class StyledWriter
+// //////////////////////////////////////////////////////////////////
+
+StyledWriter::StyledWriter()
+ : rightMargin_(74), indentSize_(3), addChildValues_() {}
+
+std::string StyledWriter::write(const Value& root) {
+ document_ = "";
+ addChildValues_ = false;
+ indentString_ = "";
+ writeCommentBeforeValue(root);
+ writeValue(root);
+ writeCommentAfterValueOnSameLine(root);
+ document_ += "\n";
+ return document_;
+}
+
+void StyledWriter::writeValue(const Value& value) {
+ switch (value.type()) {
+ case nullValue:
+ pushValue("null");
+ break;
+ case intValue:
+ pushValue(valueToString(value.asLargestInt()));
+ break;
+ case uintValue:
+ pushValue(valueToString(value.asLargestUInt()));
+ break;
+ case realValue:
+ pushValue(valueToString(value.asDouble()));
+ break;
+ case stringValue:
+ {
+ // Is NULL possible for value.string_?
+ char const* str;
+ char const* end;
+ bool ok = value.getString(&str, &end);
+ if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
+ else pushValue("");
+ break;
+ }
+ case booleanValue:
+ pushValue(valueToString(value.asBool()));
+ break;
+ case arrayValue:
+ writeArrayValue(value);
+ break;
+ case objectValue: {
+ Value::Members members(value.getMemberNames());
+ if (members.empty())
+ pushValue("{}");
+ else {
+ writeWithIndent("{");
+ indent();
+ Value::Members::iterator it = members.begin();
+ for (;;) {
+ const std::string& name = *it;
+ const Value& childValue = value[name];
+ writeCommentBeforeValue(childValue);
+ writeWithIndent(valueToQuotedString(name.c_str()));
+ document_ += " : ";
+ writeValue(childValue);
+ if (++it == members.end()) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ document_ += ',';
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("}");
+ }
+ } break;
+ }
+}
+
+void StyledWriter::writeArrayValue(const Value& value) {
+ unsigned size = value.size();
+ if (size == 0)
+ pushValue("[]");
+ else {
+ bool isArrayMultiLine = isMultineArray(value);
+ if (isArrayMultiLine) {
+ writeWithIndent("[");
+ indent();
+ bool hasChildValue = !childValues_.empty();
+ unsigned index = 0;
+ for (;;) {
+ const Value& childValue = value[index];
+ writeCommentBeforeValue(childValue);
+ if (hasChildValue)
+ writeWithIndent(childValues_[index]);
+ else {
+ writeIndent();
+ writeValue(childValue);
+ }
+ if (++index == size) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ document_ += ',';
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("]");
+ } else // output on a single line
+ {
+ assert(childValues_.size() == size);
+ document_ += "[ ";
+ for (unsigned index = 0; index < size; ++index) {
+ if (index > 0)
+ document_ += ", ";
+ document_ += childValues_[index];
+ }
+ document_ += " ]";
+ }
+ }
+}
+
+bool StyledWriter::isMultineArray(const Value& value) {
+ int size = value.size();
+ bool isMultiLine = size * 3 >= rightMargin_;
+ childValues_.clear();
+ for (int index = 0; index < size && !isMultiLine; ++index) {
+ const Value& childValue = value[index];
+ isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
+ childValue.size() > 0);
+ }
+ if (!isMultiLine) // check if line length > max line length
+ {
+ childValues_.reserve(size);
+ addChildValues_ = true;
+ int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
+ for (int index = 0; index < size; ++index) {
+ if (hasCommentForValue(value[index])) {
+ isMultiLine = true;
+ }
+ writeValue(value[index]);
+ lineLength += int(childValues_[index].length());
+ }
+ addChildValues_ = false;
+ isMultiLine = isMultiLine || lineLength >= rightMargin_;
+ }
+ return isMultiLine;
+}
+
+void StyledWriter::pushValue(const std::string& value) {
+ if (addChildValues_)
+ childValues_.push_back(value);
+ else
+ document_ += value;
+}
+
+void StyledWriter::writeIndent() {
+ if (!document_.empty()) {
+ char last = document_[document_.length() - 1];
+ if (last == ' ') // already indented
+ return;
+ if (last != '\n') // Comments may add new-line
+ document_ += '\n';
+ }
+ document_ += indentString_;
+}
+
+void StyledWriter::writeWithIndent(const std::string& value) {
+ writeIndent();
+ document_ += value;
+}
+
+void StyledWriter::indent() { indentString_ += std::string(indentSize_, ' '); }
+
+void StyledWriter::unindent() {
+ assert(int(indentString_.size()) >= indentSize_);
+ indentString_.resize(indentString_.size() - indentSize_);
+}
+
+void StyledWriter::writeCommentBeforeValue(const Value& root) {
+ if (!root.hasComment(commentBefore))
+ return;
+
+ document_ += "\n";
+ writeIndent();
+ const std::string& comment = root.getComment(commentBefore);
+ std::string::const_iterator iter = comment.begin();
+ while (iter != comment.end()) {
+ document_ += *iter;
+ if (*iter == '\n' &&
+ (iter != comment.end() && *(iter + 1) == '/'))
+ writeIndent();
+ ++iter;
+ }
+
+ // Comments are stripped of trailing newlines, so add one here
+ document_ += "\n";
+}
+
+void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) {
+ if (root.hasComment(commentAfterOnSameLine))
+ document_ += " " + root.getComment(commentAfterOnSameLine);
+
+ if (root.hasComment(commentAfter)) {
+ document_ += "\n";
+ document_ += root.getComment(commentAfter);
+ document_ += "\n";
+ }
+}
+
+bool StyledWriter::hasCommentForValue(const Value& value) {
+ return value.hasComment(commentBefore) ||
+ value.hasComment(commentAfterOnSameLine) ||
+ value.hasComment(commentAfter);
+}
+
+// Class StyledStreamWriter
+// //////////////////////////////////////////////////////////////////
+
+StyledStreamWriter::StyledStreamWriter(std::string indentation)
+ : document_(NULL), rightMargin_(74), indentation_(indentation),
+ addChildValues_() {}
+
+void StyledStreamWriter::write(std::ostream& out, const Value& root) {
+ document_ = &out;
+ addChildValues_ = false;
+ indentString_ = "";
+ indented_ = true;
+ writeCommentBeforeValue(root);
+ if (!indented_) writeIndent();
+ indented_ = true;
+ writeValue(root);
+ writeCommentAfterValueOnSameLine(root);
+ *document_ << "\n";
+ document_ = NULL; // Forget the stream, for safety.
+}
+
+void StyledStreamWriter::writeValue(const Value& value) {
+ switch (value.type()) {
+ case nullValue:
+ pushValue("null");
+ break;
+ case intValue:
+ pushValue(valueToString(value.asLargestInt()));
+ break;
+ case uintValue:
+ pushValue(valueToString(value.asLargestUInt()));
+ break;
+ case realValue:
+ pushValue(valueToString(value.asDouble()));
+ break;
+ case stringValue:
+ {
+ // Is NULL possible for value.string_?
+ char const* str;
+ char const* end;
+ bool ok = value.getString(&str, &end);
+ if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
+ else pushValue("");
+ break;
+ }
+ case booleanValue:
+ pushValue(valueToString(value.asBool()));
+ break;
+ case arrayValue:
+ writeArrayValue(value);
+ break;
+ case objectValue: {
+ Value::Members members(value.getMemberNames());
+ if (members.empty())
+ pushValue("{}");
+ else {
+ writeWithIndent("{");
+ indent();
+ Value::Members::iterator it = members.begin();
+ for (;;) {
+ const std::string& name = *it;
+ const Value& childValue = value[name];
+ writeCommentBeforeValue(childValue);
+ writeWithIndent(valueToQuotedString(name.c_str()));
+ *document_ << " : ";
+ writeValue(childValue);
+ if (++it == members.end()) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ *document_ << ",";
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("}");
+ }
+ } break;
+ }
+}
+
+void StyledStreamWriter::writeArrayValue(const Value& value) {
+ unsigned size = value.size();
+ if (size == 0)
+ pushValue("[]");
+ else {
+ bool isArrayMultiLine = isMultineArray(value);
+ if (isArrayMultiLine) {
+ writeWithIndent("[");
+ indent();
+ bool hasChildValue = !childValues_.empty();
+ unsigned index = 0;
+ for (;;) {
+ const Value& childValue = value[index];
+ writeCommentBeforeValue(childValue);
+ if (hasChildValue)
+ writeWithIndent(childValues_[index]);
+ else {
+ if (!indented_) writeIndent();
+ indented_ = true;
+ writeValue(childValue);
+ indented_ = false;
+ }
+ if (++index == size) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ *document_ << ",";
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("]");
+ } else // output on a single line
+ {
+ assert(childValues_.size() == size);
+ *document_ << "[ ";
+ for (unsigned index = 0; index < size; ++index) {
+ if (index > 0)
+ *document_ << ", ";
+ *document_ << childValues_[index];
+ }
+ *document_ << " ]";
+ }
+ }
+}
+
+bool StyledStreamWriter::isMultineArray(const Value& value) {
+ int size = value.size();
+ bool isMultiLine = size * 3 >= rightMargin_;
+ childValues_.clear();
+ for (int index = 0; index < size && !isMultiLine; ++index) {
+ const Value& childValue = value[index];
+ isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
+ childValue.size() > 0);
+ }
+ if (!isMultiLine) // check if line length > max line length
+ {
+ childValues_.reserve(size);
+ addChildValues_ = true;
+ int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
+ for (int index = 0; index < size; ++index) {
+ if (hasCommentForValue(value[index])) {
+ isMultiLine = true;
+ }
+ writeValue(value[index]);
+ lineLength += int(childValues_[index].length());
+ }
+ addChildValues_ = false;
+ isMultiLine = isMultiLine || lineLength >= rightMargin_;
+ }
+ return isMultiLine;
+}
+
+void StyledStreamWriter::pushValue(const std::string& value) {
+ if (addChildValues_)
+ childValues_.push_back(value);
+ else
+ *document_ << value;
+}
+
+void StyledStreamWriter::writeIndent() {
+ // blep intended this to look at the so-far-written string
+ // to determine whether we are already indented, but
+ // with a stream we cannot do that. So we rely on some saved state.
+ // The caller checks indented_.
+ *document_ << '\n' << indentString_;
+}
+
+void StyledStreamWriter::writeWithIndent(const std::string& value) {
+ if (!indented_) writeIndent();
+ *document_ << value;
+ indented_ = false;
+}
+
+void StyledStreamWriter::indent() { indentString_ += indentation_; }
+
+void StyledStreamWriter::unindent() {
+ assert(indentString_.size() >= indentation_.size());
+ indentString_.resize(indentString_.size() - indentation_.size());
+}
+
+void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {
+ if (!root.hasComment(commentBefore))
+ return;
+
+ if (!indented_) writeIndent();
+ const std::string& comment = root.getComment(commentBefore);
+ std::string::const_iterator iter = comment.begin();
+ while (iter != comment.end()) {
+ *document_ << *iter;
+ if (*iter == '\n' &&
+ (iter != comment.end() && *(iter + 1) == '/'))
+ // writeIndent(); // would include newline
+ *document_ << indentString_;
+ ++iter;
+ }
+ indented_ = false;
+}
+
+void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) {
+ if (root.hasComment(commentAfterOnSameLine))
+ *document_ << ' ' << root.getComment(commentAfterOnSameLine);
+
+ if (root.hasComment(commentAfter)) {
+ writeIndent();
+ *document_ << root.getComment(commentAfter);
+ }
+ indented_ = false;
+}
+
+bool StyledStreamWriter::hasCommentForValue(const Value& value) {
+ return value.hasComment(commentBefore) ||
+ value.hasComment(commentAfterOnSameLine) ||
+ value.hasComment(commentAfter);
+}
+
+//////////////////////////
+// BuiltStyledStreamWriter
+
+/// Scoped enums are not available until C++11.
+struct CommentStyle {
+ /// Decide whether to write comments.
+ enum Enum {
+ None, ///< Drop all comments.
+ Most, ///< Recover odd behavior of previous versions (not implemented yet).
+ All ///< Keep all comments.
+ };
+};
+
+struct BuiltStyledStreamWriter : public StreamWriter
+{
+ BuiltStyledStreamWriter(
+ std::string const& indentation,
+ CommentStyle::Enum cs,
+ std::string const& colonSymbol,
+ std::string const& nullSymbol,
+ std::string const& endingLineFeedSymbol,
+ bool useSpecialFloats,
+ unsigned int precision);
+ int write(Value const& root, std::ostream* sout);
+private:
+ void writeValue(Value const& value);
+ void writeArrayValue(Value const& value);
+ bool isMultineArray(Value const& value);
+ void pushValue(std::string const& value);
+ void writeIndent();
+ void writeWithIndent(std::string const& value);
+ void indent();
+ void unindent();
+ void writeCommentBeforeValue(Value const& root);
+ void writeCommentAfterValueOnSameLine(Value const& root);
+ static bool hasCommentForValue(const Value& value);
+
+ typedef std::vector<std::string> ChildValues;
+
+ ChildValues childValues_;
+ std::string indentString_;
+ int rightMargin_;
+ std::string indentation_;
+ CommentStyle::Enum cs_;
+ std::string colonSymbol_;
+ std::string nullSymbol_;
+ std::string endingLineFeedSymbol_;
+ bool addChildValues_ : 1;
+ bool indented_ : 1;
+ bool useSpecialFloats_ : 1;
+ unsigned int precision_;
+};
+BuiltStyledStreamWriter::BuiltStyledStreamWriter(
+ std::string const& indentation,
+ CommentStyle::Enum cs,
+ std::string const& colonSymbol,
+ std::string const& nullSymbol,
+ std::string const& endingLineFeedSymbol,
+ bool useSpecialFloats,
+ unsigned int precision)
+ : rightMargin_(74)
+ , indentation_(indentation)
+ , cs_(cs)
+ , colonSymbol_(colonSymbol)
+ , nullSymbol_(nullSymbol)
+ , endingLineFeedSymbol_(endingLineFeedSymbol)
+ , addChildValues_(false)
+ , indented_(false)
+ , useSpecialFloats_(useSpecialFloats)
+ , precision_(precision)
+{
+}
+int BuiltStyledStreamWriter::write(Value const& root, std::ostream* sout)
+{
+ sout_ = sout;
+ addChildValues_ = false;
+ indented_ = true;
+ indentString_ = "";
+ writeCommentBeforeValue(root);
+ if (!indented_) writeIndent();
+ indented_ = true;
+ writeValue(root);
+ writeCommentAfterValueOnSameLine(root);
+ *sout_ << endingLineFeedSymbol_;
+ sout_ = NULL;
+ return 0;
+}
+void BuiltStyledStreamWriter::writeValue(Value const& value) {
+ switch (value.type()) {
+ case nullValue:
+ pushValue(nullSymbol_);
+ break;
+ case intValue:
+ pushValue(valueToString(value.asLargestInt()));
+ break;
+ case uintValue:
+ pushValue(valueToString(value.asLargestUInt()));
+ break;
+ case realValue:
+ pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_));
+ break;
+ case stringValue:
+ {
+ // Is NULL is possible for value.string_?
+ char const* str;
+ char const* end;
+ bool ok = value.getString(&str, &end);
+ if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
+ else pushValue("");
+ break;
+ }
+ case booleanValue:
+ pushValue(valueToString(value.asBool()));
+ break;
+ case arrayValue:
+ writeArrayValue(value);
+ break;
+ case objectValue: {
+ Value::Members members(value.getMemberNames());
+ if (members.empty())
+ pushValue("{}");
+ else {
+ writeWithIndent("{");
+ indent();
+ Value::Members::iterator it = members.begin();
+ for (;;) {
+ std::string const& name = *it;
+ Value const& childValue = value[name];
+ writeCommentBeforeValue(childValue);
+ writeWithIndent(valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())));
+ *sout_ << colonSymbol_;
+ writeValue(childValue);
+ if (++it == members.end()) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ *sout_ << ",";
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("}");
+ }
+ } break;
+ }
+}
+
+void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
+ unsigned size = value.size();
+ if (size == 0)
+ pushValue("[]");
+ else {
+ bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value);
+ if (isMultiLine) {
+ writeWithIndent("[");
+ indent();
+ bool hasChildValue = !childValues_.empty();
+ unsigned index = 0;
+ for (;;) {
+ Value const& childValue = value[index];
+ writeCommentBeforeValue(childValue);
+ if (hasChildValue)
+ writeWithIndent(childValues_[index]);
+ else {
+ if (!indented_) writeIndent();
+ indented_ = true;
+ writeValue(childValue);
+ indented_ = false;
+ }
+ if (++index == size) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ *sout_ << ",";
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("]");
+ } else // output on a single line
+ {
+ assert(childValues_.size() == size);
+ *sout_ << "[";
+ if (!indentation_.empty()) *sout_ << " ";
+ for (unsigned index = 0; index < size; ++index) {
+ if (index > 0)
+ *sout_ << ", ";
+ *sout_ << childValues_[index];
+ }
+ if (!indentation_.empty()) *sout_ << " ";
+ *sout_ << "]";
+ }
+ }
+}
+
+bool BuiltStyledStreamWriter::isMultineArray(Value const& value) {
+ int size = value.size();
+ bool isMultiLine = size * 3 >= rightMargin_;
+ childValues_.clear();
+ for (int index = 0; index < size && !isMultiLine; ++index) {
+ Value const& childValue = value[index];
+ isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
+ childValue.size() > 0);
+ }
+ if (!isMultiLine) // check if line length > max line length
+ {
+ childValues_.reserve(size);
+ addChildValues_ = true;
+ int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
+ for (int index = 0; index < size; ++index) {
+ if (hasCommentForValue(value[index])) {
+ isMultiLine = true;
+ }
+ writeValue(value[index]);
+ lineLength += int(childValues_[index].length());
+ }
+ addChildValues_ = false;
+ isMultiLine = isMultiLine || lineLength >= rightMargin_;
+ }
+ return isMultiLine;
+}
+
+void BuiltStyledStreamWriter::pushValue(std::string const& value) {
+ if (addChildValues_)
+ childValues_.push_back(value);
+ else
+ *sout_ << value;
+}
+
+void BuiltStyledStreamWriter::writeIndent() {
+ // blep intended this to look at the so-far-written string
+ // to determine whether we are already indented, but
+ // with a stream we cannot do that. So we rely on some saved state.
+ // The caller checks indented_.
+
+ if (!indentation_.empty()) {
+ // In this case, drop newlines too.
+ *sout_ << '\n' << indentString_;
+ }
+}
+
+void BuiltStyledStreamWriter::writeWithIndent(std::string const& value) {
+ if (!indented_) writeIndent();
+ *sout_ << value;
+ indented_ = false;
+}
+
+void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; }
+
+void BuiltStyledStreamWriter::unindent() {
+ assert(indentString_.size() >= indentation_.size());
+ indentString_.resize(indentString_.size() - indentation_.size());
+}
+
+void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
+ if (cs_ == CommentStyle::None) return;
+ if (!root.hasComment(commentBefore))
+ return;
+
+ if (!indented_) writeIndent();
+ const std::string& comment = root.getComment(commentBefore);
+ std::string::const_iterator iter = comment.begin();
+ while (iter != comment.end()) {
+ *sout_ << *iter;
+ if (*iter == '\n' &&
+ (iter != comment.end() && *(iter + 1) == '/'))
+ // writeIndent(); // would write extra newline
+ *sout_ << indentString_;
+ ++iter;
+ }
+ indented_ = false;
+}
+
+void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(Value const& root) {
+ if (cs_ == CommentStyle::None) return;
+ if (root.hasComment(commentAfterOnSameLine))
+ *sout_ << " " + root.getComment(commentAfterOnSameLine);
+
+ if (root.hasComment(commentAfter)) {
+ writeIndent();
+ *sout_ << root.getComment(commentAfter);
+ }
+}
+
+// static
+bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) {
+ return value.hasComment(commentBefore) ||
+ value.hasComment(commentAfterOnSameLine) ||
+ value.hasComment(commentAfter);
+}
+
+///////////////
+// StreamWriter
+
+StreamWriter::StreamWriter()
+ : sout_(NULL)
+{
+}
+StreamWriter::~StreamWriter()
+{
+}
+StreamWriter::Factory::~Factory()
+{}
+StreamWriterBuilder::StreamWriterBuilder()
+{
+ setDefaults(&settings_);
+}
+StreamWriterBuilder::~StreamWriterBuilder()
+{}
+StreamWriter* StreamWriterBuilder::newStreamWriter() const
+{
+ std::string indentation = settings_["indentation"].asString();
+ std::string cs_str = settings_["commentStyle"].asString();
+ bool eyc = settings_["enableYAMLCompatibility"].asBool();
+ bool dnp = settings_["dropNullPlaceholders"].asBool();
+ bool usf = settings_["useSpecialFloats"].asBool();
+ unsigned int pre = settings_["precision"].asUInt();
+ CommentStyle::Enum cs = CommentStyle::All;
+ if (cs_str == "All") {
+ cs = CommentStyle::All;
+ } else if (cs_str == "None") {
+ cs = CommentStyle::None;
+ } else {
+ throwRuntimeError("commentStyle must be 'All' or 'None'");
+ }
+ std::string colonSymbol = " : ";
+ if (eyc) {
+ colonSymbol = ": ";
+ } else if (indentation.empty()) {
+ colonSymbol = ":";
+ }
+ std::string nullSymbol = "null";
+ if (dnp) {
+ nullSymbol = "";
+ }
+ if (pre > 17) pre = 17;
+ std::string endingLineFeedSymbol = "";
+ return new BuiltStyledStreamWriter(
+ indentation, cs,
+ colonSymbol, nullSymbol, endingLineFeedSymbol, usf, pre);
+}
+static void getValidWriterKeys(std::set<std::string>* valid_keys)
+{
+ valid_keys->clear();
+ valid_keys->insert("indentation");
+ valid_keys->insert("commentStyle");
+ valid_keys->insert("enableYAMLCompatibility");
+ valid_keys->insert("dropNullPlaceholders");
+ valid_keys->insert("useSpecialFloats");
+ valid_keys->insert("precision");
+}
+bool StreamWriterBuilder::validate(Json::Value* invalid) const
+{
+ Json::Value my_invalid;
+ if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
+ Json::Value& inv = *invalid;
+ std::set<std::string> valid_keys;
+ getValidWriterKeys(&valid_keys);
+ Value::Members keys = settings_.getMemberNames();
+ size_t n = keys.size();
+ for (size_t i = 0; i < n; ++i) {
+ std::string const& key = keys[i];
+ if (valid_keys.find(key) == valid_keys.end()) {
+ inv[key] = settings_[key];
+ }
+ }
+ return 0u == inv.size();
+}
+Value& StreamWriterBuilder::operator[](std::string key)
+{
+ return settings_[key];
+}
+// static
+void StreamWriterBuilder::setDefaults(Json::Value* settings)
+{
+ //! [StreamWriterBuilderDefaults]
+ (*settings)["commentStyle"] = "All";
+ (*settings)["indentation"] = "\t";
+ (*settings)["enableYAMLCompatibility"] = false;
+ (*settings)["dropNullPlaceholders"] = false;
+ (*settings)["useSpecialFloats"] = false;
+ (*settings)["precision"] = 17;
+ //! [StreamWriterBuilderDefaults]
+}
+
+std::string writeString(StreamWriter::Factory const& builder, Value const& root) {
+ std::ostringstream sout;
+ StreamWriterPtr const writer(builder.newStreamWriter());
+ writer->write(root, &sout);
+ return sout.str();
+}
+
+std::ostream& operator<<(std::ostream& sout, Value const& root) {
+ StreamWriterBuilder builder;
+ StreamWriterPtr const writer(builder.newStreamWriter());
+ writer->write(root, &sout);
+ return sout;
+}
+
+} // namespace Json
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: src/lib_json/json_writer.cpp
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
diff --git a/src/openvr_api_public.cpp b/src/openvr_api_public.cpp
new file mode 100644
index 0000000..b7d0643
--- /dev/null
+++ b/src/openvr_api_public.cpp
@@ -0,0 +1,278 @@
+//========= Copyright Valve Corporation ============//
+#define VR_API_EXPORT 1
+#include "openvr.h"
+#include "ivrclientcore.h"
+#include "vrcommon/pathtools.h"
+#include "vrcommon/sharedlibtools.h"
+#include "vrcommon/envvartools.h"
+#include "vrcommon/hmderrors.h"
+#include "vrcommon/vrpathregistry.h"
+
+using vr::EVRInitError;
+using vr::IVRSystem;
+using vr::IVRClientCore;
+using vr::VRInitError_None;
+
+namespace vr
+{
+
+static void *g_pVRModule = NULL;
+static IVRClientCore *g_pHmdSystem = NULL;
+
+
+typedef void* (*VRClientCoreFactoryFn)(const char *pInterfaceName, int *pReturnCode);
+
+static uint32_t g_nVRToken = 0;
+
+uint32_t VR_GetInitToken()
+{
+ return g_nVRToken;
+}
+
+EVRInitError VR_LoadHmdSystemInternal();
+
+uint32_t VR_InitInternal( EVRInitError *peError, vr::EVRApplicationType eApplicationType )
+{
+ EVRInitError err = VR_LoadHmdSystemInternal();
+ if (err != vr::VRInitError_None)
+ {
+ SharedLib_Unload(g_pVRModule);
+ g_pHmdSystem = NULL;
+ g_pVRModule = NULL;
+
+ if (peError)
+ *peError = err;
+
+ return 0;
+ }
+
+ err = g_pHmdSystem->Init(eApplicationType);
+ if (err != VRInitError_None)
+ {
+ SharedLib_Unload(g_pVRModule);
+ g_pHmdSystem = NULL;
+ g_pVRModule = NULL;
+
+ if (peError)
+ *peError = err;
+
+ return 0;
+ }
+
+ if (peError)
+ *peError = VRInitError_None;
+
+ return ++g_nVRToken;
+}
+
+void VR_ShutdownInternal()
+{
+ if (g_pHmdSystem)
+ {
+ g_pHmdSystem->Cleanup();
+ g_pHmdSystem = NULL;
+ }
+ if (g_pVRModule)
+ {
+ SharedLib_Unload(g_pVRModule);
+ g_pVRModule = NULL;
+ }
+
+ ++g_nVRToken;
+}
+
+EVRInitError VR_LoadHmdSystemInternal()
+{
+ std::string sRuntimePath, sConfigPath, sLogPath;
+
+ bool bReadPathRegistry = CVRPathRegistry::GetPaths( &sRuntimePath, &sConfigPath, &sLogPath, NULL, NULL );
+ if( !bReadPathRegistry )
+ {
+ return vr::VRInitError_Init_PathRegistryNotFound;
+ }
+
+ // figure out where we're going to look for vrclient.dll
+ // see if the specified path actually exists.
+ if( !Path_IsDirectory( sRuntimePath ) )
+ {
+ return vr::VRInitError_Init_InstallationNotFound;
+ }
+
+ // Because we don't have a way to select debug vs. release yet we'll just
+ // use debug if it's there
+#if defined( LINUX64 )
+ std::string sTestPath = Path_Join( sRuntimePath, "bin", PLATSUBDIR );
+#else
+ std::string sTestPath = Path_Join( sRuntimePath, "bin" );
+#endif
+ if( !Path_IsDirectory( sTestPath ) )
+ {
+ return vr::VRInitError_Init_InstallationCorrupt;
+ }
+
+#if defined( WIN64 )
+ std::string sDLLPath = Path_Join( sTestPath, "vrclient_x64" DYNAMIC_LIB_EXT );
+#else
+ std::string sDLLPath = Path_Join( sTestPath, "vrclient" DYNAMIC_LIB_EXT );
+#endif
+
+ // only look in the override
+ void *pMod = SharedLib_Load( sDLLPath.c_str() );
+ // nothing more to do if we can't load the DLL
+ if( !pMod )
+ {
+ return vr::VRInitError_Init_VRClientDLLNotFound;
+ }
+
+ VRClientCoreFactoryFn fnFactory = ( VRClientCoreFactoryFn )( SharedLib_GetFunction( pMod, "VRClientCoreFactory" ) );
+ if( !fnFactory )
+ {
+ SharedLib_Unload( pMod );
+ return vr::VRInitError_Init_FactoryNotFound;
+ }
+
+ int nReturnCode = 0;
+ g_pHmdSystem = static_cast< IVRClientCore * > ( fnFactory( vr::IVRClientCore_Version, &nReturnCode ) );
+ if( !g_pHmdSystem )
+ {
+ SharedLib_Unload( pMod );
+ return vr::VRInitError_Init_InterfaceNotFound;
+ }
+
+ g_pVRModule = pMod;
+ return VRInitError_None;
+}
+
+
+void *VR_GetGenericInterface(const char *pchInterfaceVersion, EVRInitError *peError)
+{
+ if (!g_pHmdSystem)
+ {
+ if (peError)
+ *peError = vr::VRInitError_Init_NotInitialized;
+ return NULL;
+ }
+
+ return g_pHmdSystem->GetGenericInterface(pchInterfaceVersion, peError);
+}
+
+bool VR_IsInterfaceVersionValid(const char *pchInterfaceVersion)
+{
+ if (!g_pHmdSystem)
+ {
+ return false;
+ }
+
+ return g_pHmdSystem->IsInterfaceVersionValid(pchInterfaceVersion) == VRInitError_None;
+}
+
+bool VR_IsHmdPresent()
+{
+ if( g_pHmdSystem )
+ {
+ // if we're already initialized, just call through
+ return g_pHmdSystem->BIsHmdPresent();
+ }
+ else
+ {
+ // otherwise we need to do a bit more work
+ EVRInitError err = VR_LoadHmdSystemInternal();
+ if( err != VRInitError_None )
+ return false;
+
+ bool bHasHmd = g_pHmdSystem->BIsHmdPresent();
+
+ g_pHmdSystem = NULL;
+ SharedLib_Unload( g_pVRModule );
+ g_pVRModule = NULL;
+
+ return bHasHmd;
+ }
+}
+
+/** Returns true if the OpenVR runtime is installed. */
+bool VR_IsRuntimeInstalled()
+{
+ if( g_pHmdSystem )
+ {
+ // if we're already initialized, OpenVR is obviously installed
+ return true;
+ }
+ else
+ {
+ // otherwise we need to do a bit more work
+ std::string sRuntimePath, sConfigPath, sLogPath;
+
+ bool bReadPathRegistry = CVRPathRegistry::GetPaths( &sRuntimePath, &sConfigPath, &sLogPath, NULL, NULL );
+ if( !bReadPathRegistry )
+ {
+ return false;
+ }
+
+ // figure out where we're going to look for vrclient.dll
+ // see if the specified path actually exists.
+ if( !Path_IsDirectory( sRuntimePath ) )
+ {
+ return false;
+ }
+
+ // the installation may be corrupt in some way, but it certainly looks installed
+ return true;
+ }
+}
+
+
+/** Returns where OpenVR runtime is installed. */
+const char *VR_RuntimePath()
+{
+ // otherwise we need to do a bit more work
+ static std::string sRuntimePath;
+ std::string sConfigPath, sLogPath;
+
+ bool bReadPathRegistry = CVRPathRegistry::GetPaths( &sRuntimePath, &sConfigPath, &sLogPath, NULL, NULL );
+ if ( !bReadPathRegistry )
+ {
+ return nullptr;
+ }
+
+ // figure out where we're going to look for vrclient.dll
+ // see if the specified path actually exists.
+ if ( !Path_IsDirectory( sRuntimePath ) )
+ {
+ return nullptr;
+ }
+
+ return sRuntimePath.c_str();
+}
+
+
+/** Returns the symbol version of an HMD error. */
+const char *VR_GetVRInitErrorAsSymbol( EVRInitError error )
+{
+ if( g_pHmdSystem )
+ return g_pHmdSystem->GetIDForVRInitError( error );
+ else
+ return GetIDForVRInitError( error );
+}
+
+
+/** Returns the english string version of an HMD error. */
+const char *VR_GetVRInitErrorAsEnglishDescription( EVRInitError error )
+{
+ if ( g_pHmdSystem )
+ return g_pHmdSystem->GetEnglishStringForHmdError( error );
+ else
+ return GetEnglishStringForHmdError( error );
+}
+
+
+VR_INTERFACE const char *VR_CALLTYPE VR_GetStringForHmdError( vr::EVRInitError error );
+
+/** Returns the english string version of an HMD error. */
+const char *VR_GetStringForHmdError( EVRInitError error )
+{
+ return VR_GetVRInitErrorAsEnglishDescription( error );
+}
+
+}
+
diff --git a/src/vrcommon/dirtools.h b/src/vrcommon/dirtools.h
new file mode 100644
index 0000000..b048b41
--- /dev/null
+++ b/src/vrcommon/dirtools.h
@@ -0,0 +1,17 @@
+//========= Copyright Valve Corporation ============//
+#pragma once
+
+#include <stdint.h>
+#include <string>
+
+
+#if !defined(_WIN32)
+#include <sys/types.h>
+#include <sys/stat.h>
+#endif
+
+
+extern bool BCreateDirectoryRecursive( const char *pchPath );
+extern bool BCreateDirectory( const char *pchPath );
+
+
diff --git a/src/vrcommon/dirtools_public.cpp b/src/vrcommon/dirtools_public.cpp
new file mode 100644
index 0000000..287832a
--- /dev/null
+++ b/src/vrcommon/dirtools_public.cpp
@@ -0,0 +1,100 @@
+//========= Copyright Valve Corporation ============//
+#include "dirtools.h"
+#include "strtools.h"
+#include "pathtools.h"
+
+#include <errno.h>
+
+#ifdef _WIN32
+#include "windows.h"
+#else
+#include <stdlib.h>
+#include <stdio.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#endif
+
+#if defined( OSX )
+#include <sys/syslimits.h>
+#endif
+
+
+//-----------------------------------------------------------------------------
+// Purpose: utility function to create dirs & subdirs
+//-----------------------------------------------------------------------------
+bool BCreateDirectoryRecursive( const char *pchPath )
+{
+ // Does it already exist?
+ if ( Path_IsDirectory( pchPath ) )
+ return true;
+
+ // copy the path into something we can munge
+ int len = (int)strlen( pchPath );
+ char *path = (char *)malloc( len + 1 );
+ strcpy( path, pchPath );
+
+ // Walk backwards to first non-existing dir that we find
+ char *s = path + len - 1;
+
+ const char slash = Path_GetSlash();
+ while ( s > path )
+ {
+ if ( *s == slash )
+ {
+ *s = '\0';
+ bool bExists = Path_IsDirectory( path );
+ *s = slash;
+
+ if ( bExists )
+ {
+ ++s;
+ break;
+ }
+ }
+ --s;
+ }
+
+ // and then move forwards from there
+
+ while ( *s )
+ {
+ if ( *s == slash )
+ {
+ *s = '\0';
+ BCreateDirectory( path );
+ *s = slash;
+ }
+ s++;
+ }
+
+ bool bRetVal = BCreateDirectory( path );
+ free( path );
+ return bRetVal;
+}
+
+
+//-----------------------------------------------------------------------------
+// Purpose: Creates the directory, returning true if it is created, or if it already existed
+//-----------------------------------------------------------------------------
+bool BCreateDirectory( const char *pchPath )
+{
+#ifdef WIN32
+ std::wstring wPath = UTF8to16( pchPath );
+ if ( ::CreateDirectoryW( wPath.c_str(), NULL ) )
+ return true;
+
+ if ( ::GetLastError() == ERROR_ALREADY_EXISTS )
+ return true;
+
+ return false;
+#else
+ int i = mkdir( pchPath, S_IRWXU | S_IRWXG | S_IRWXO );
+ if ( i == 0 )
+ return true;
+ if ( errno == EEXIST )
+ return true;
+
+ return false;
+#endif
+}
+
diff --git a/src/vrcommon/envvartools.h b/src/vrcommon/envvartools.h
new file mode 100644
index 0000000..7de981a
--- /dev/null
+++ b/src/vrcommon/envvartools.h
@@ -0,0 +1,7 @@
+//========= Copyright Valve Corporation ============//
+#pragma once
+
+#include <string>
+
+std::string GetEnvironmentVariable( const char *pchVarName );
+bool SetEnvironmentVariable( const char *pchVarName, const char *pchVarValue );
diff --git a/src/vrcommon/envvartools_public.cpp b/src/vrcommon/envvartools_public.cpp
new file mode 100644
index 0000000..231dee4
--- /dev/null
+++ b/src/vrcommon/envvartools_public.cpp
@@ -0,0 +1,46 @@
+//========= Copyright Valve Corporation ============//
+#include "envvartools.h"
+#include <stdlib.h>
+
+#if defined(_WIN32)
+#include <Windows.h>
+
+#undef GetEnvironmentVariable
+#undef SetEnvironmentVariable
+#endif
+
+
+std::string GetEnvironmentVariable( const char *pchVarName )
+{
+#if defined(_WIN32)
+ char rchValue[32767]; // max size for an env var on Windows
+ DWORD cChars = GetEnvironmentVariableA( pchVarName, rchValue, sizeof( rchValue ) );
+ if( cChars == 0 )
+ return "";
+ else
+ return rchValue;
+#elif defined(POSIX)
+ char *pchValue = getenv( pchVarName );
+ if( pchValue )
+ return pchValue;
+ else
+ return "";
+#else
+#error "Unsupported Platform"
+#endif
+}
+
+
+bool SetEnvironmentVariable( const char *pchVarName, const char *pchVarValue )
+{
+#if defined(_WIN32)
+ return 0 != SetEnvironmentVariableA( pchVarName, pchVarValue );
+#elif defined(POSIX)
+ if( pchVarValue == NULL )
+ return 0 == unsetenv( pchVarName );
+ else
+ return 0 == setenv( pchVarName, pchVarValue, 1 );
+#else
+#error "Unsupported Platform"
+#endif
+}
diff --git a/src/vrcommon/hmderrors.h b/src/vrcommon/hmderrors.h
new file mode 100644
index 0000000..4bce5e3
--- /dev/null
+++ b/src/vrcommon/hmderrors.h
@@ -0,0 +1,8 @@
+//========= Copyright Valve Corporation ============//
+#pragma once
+#include "openvr.h"
+
+
+const char *GetEnglishStringForHmdError( vr::EVRInitError eError );
+const char *GetIDForVRInitError( vr::EVRInitError eError );
+
diff --git a/src/vrcommon/hmderrors_public.cpp b/src/vrcommon/hmderrors_public.cpp
new file mode 100644
index 0000000..f2409fe
--- /dev/null
+++ b/src/vrcommon/hmderrors_public.cpp
@@ -0,0 +1,204 @@
+//========= Copyright Valve Corporation ============//
+#include "hmderrors.h"
+#include <stdio.h>
+#include <algorithm>
+
+using namespace vr;
+
+#define RETURN_ENUM_AS_STRING(enumValue) case enumValue: return #enumValue;
+
+
+const char *GetEnglishStringForHmdError( vr::EVRInitError eError )
+{
+ switch( eError )
+ {
+ case VRInitError_None: return "No Error (0)";
+
+ case VRInitError_Init_InstallationNotFound: return "Installation Not Found (100)";
+ case VRInitError_Init_InstallationCorrupt: return "Installation Corrupt (101)";
+ case VRInitError_Init_VRClientDLLNotFound: return "vrclient Shared Lib Not Found (102)";
+ case VRInitError_Init_FileNotFound: return "File Not Found (103)";
+ case VRInitError_Init_FactoryNotFound: return "Factory Function Not Found (104)";
+ case VRInitError_Init_InterfaceNotFound: return "Interface Not Found (105)";
+ case VRInitError_Init_InvalidInterface: return "Invalid Interface (106)";
+ case VRInitError_Init_UserConfigDirectoryInvalid: return "User Config Directory Invalid (107)";
+ case VRInitError_Init_HmdNotFound: return "Hmd Not Found (108)";
+ case VRInitError_Init_NotInitialized: return "Not Initialized (109)";
+ case VRInitError_Init_PathRegistryNotFound: return "Installation path could not be located (110)";
+ case VRInitError_Init_NoConfigPath: return "Config path could not be located (111)";
+ case VRInitError_Init_NoLogPath: return "Log path could not be located (112)";
+ case VRInitError_Init_PathRegistryNotWritable: return "Unable to write path registry (113)";
+ case VRInitError_Init_AppInfoInitFailed: return "App info manager init failed (114)";
+ case VRInitError_Init_Retry: return "Internal Retry (115)";
+ case VRInitError_Init_InitCanceledByUser: return "User Canceled Init (116)";
+ case VRInitError_Init_AnotherAppLaunching: return "Another app was already launching (117)";
+ case VRInitError_Init_SettingsInitFailed: return "Settings manager init failed (118)";
+ case VRInitError_Init_ShuttingDown: return "VR system shutting down (119)";
+ case VRInitError_Init_TooManyObjects: return "Too many tracked objects (120)";
+ case VRInitError_Init_NoServerForBackgroundApp: return "Not starting vrserver for background app (121)";
+ case VRInitError_Init_NotSupportedWithCompositor: return "The requested interface is incompatible with the compositor and the compositor is running (122)";
+ case VRInitError_Init_NotAvailableToUtilityApps: return "This interface is not available to utility applications (123)";
+ case VRInitError_Init_Internal: return "vrserver internal error (124)";
+ case VRInitError_Init_HmdDriverIdIsNone: return "Hmd DriverId is invalid (125)";
+ case VRInitError_Init_HmdNotFoundPresenceFailed: return "Hmd Not Found Presence Failed (126)";
+
+ case VRInitError_Driver_Failed: return "Driver Failed (200)";
+ case VRInitError_Driver_Unknown: return "Driver Not Known (201)";
+ case VRInitError_Driver_HmdUnknown: return "HMD Not Known (202)";
+ case VRInitError_Driver_NotLoaded: return "Driver Not Loaded (203)";
+ case VRInitError_Driver_RuntimeOutOfDate: return "Driver runtime is out of date (204)";
+ case VRInitError_Driver_HmdInUse: return "HMD already in use by another application (205)";
+ case VRInitError_Driver_NotCalibrated: return "Device is not calibrated (206)";
+ case VRInitError_Driver_CalibrationInvalid: return "Device Calibration is invalid (207)";
+ case VRInitError_Driver_HmdDisplayNotFound: return "HMD detected over USB, but Monitor not found (208)";
+ case VRInitError_Driver_TrackedDeviceInterfaceUnknown: return "Driver Tracked Device Interface unknown (209)";
+ // case VRInitError_Driver_HmdDisplayNotFoundAfterFix: return "HMD detected over USB, but Monitor not found after attempt to fix (210)"; // taken out upon Ben's request: He thinks that there is no need to separate that error from 208
+ case VRInitError_Driver_HmdDriverIdOutOfBounds: return "Hmd DriverId is our of bounds (211)";
+ case VRInitError_Driver_HmdDisplayMirrored: return "HMD detected over USB, but Monitor may be mirrored instead of extended (212)";
+
+ case VRInitError_IPC_ServerInitFailed: return "VR Server Init Failed (300)";
+ case VRInitError_IPC_ConnectFailed: return "Connect to VR Server Failed (301)";
+ case VRInitError_IPC_SharedStateInitFailed: return "Shared IPC State Init Failed (302)";
+ case VRInitError_IPC_CompositorInitFailed: return "Shared IPC Compositor Init Failed (303)";
+ case VRInitError_IPC_MutexInitFailed: return "Shared IPC Mutex Init Failed (304)";
+ case VRInitError_IPC_Failed: return "Shared IPC Failed (305)";
+ case VRInitError_IPC_CompositorConnectFailed: return "Shared IPC Compositor Connect Failed (306)";
+ case VRInitError_IPC_CompositorInvalidConnectResponse: return "Shared IPC Compositor Invalid Connect Response (307)";
+ case VRInitError_IPC_ConnectFailedAfterMultipleAttempts: return "Shared IPC Connect Failed After Multiple Attempts (308)";
+
+ case VRInitError_Compositor_Failed: return "Compositor failed to initialize (400)";
+ case VRInitError_Compositor_D3D11HardwareRequired: return "Compositor failed to find DX11 hardware (401)";
+ case VRInitError_Compositor_FirmwareRequiresUpdate: return "Compositor requires mandatory firmware update (402)";
+ case VRInitError_Compositor_OverlayInitFailed: return "Compositor initialization succeeded, but overlay init failed (403)";
+
+ // Oculus
+ case VRInitError_VendorSpecific_UnableToConnectToOculusRuntime: return "Unable to connect to Oculus Runtime (1000)";
+
+ // Lighthouse
+ case VRInitError_VendorSpecific_HmdFound_CantOpenDevice: return "HMD found, but can not open device (1101)";
+ case VRInitError_VendorSpecific_HmdFound_UnableToRequestConfigStart: return "HMD found, but unable to request config (1102)";
+ case VRInitError_VendorSpecific_HmdFound_NoStoredConfig: return "HMD found, but no stored config (1103)";
+ case VRInitError_VendorSpecific_HmdFound_ConfigFailedSanityCheck: return "HMD found, but failed configuration check (1113)";
+ case VRInitError_VendorSpecific_HmdFound_ConfigTooBig: return "HMD found, but config too big (1104)";
+ case VRInitError_VendorSpecific_HmdFound_ConfigTooSmall: return "HMD found, but config too small (1105)";
+ case VRInitError_VendorSpecific_HmdFound_UnableToInitZLib: return "HMD found, but unable to init ZLib (1106)";
+ case VRInitError_VendorSpecific_HmdFound_CantReadFirmwareVersion: return "HMD found, but problems with the data (1107)";
+ case VRInitError_VendorSpecific_HmdFound_UnableToSendUserDataStart: return "HMD found, but problems with the data (1108)";
+ case VRInitError_VendorSpecific_HmdFound_UnableToGetUserDataStart: return "HMD found, but problems with the data (1109)";
+ case VRInitError_VendorSpecific_HmdFound_UnableToGetUserDataNext: return "HMD found, but problems with the data (1110)";
+ case VRInitError_VendorSpecific_HmdFound_UserDataAddressRange: return "HMD found, but problems with the data (1111)";
+ case VRInitError_VendorSpecific_HmdFound_UserDataError: return "HMD found, but problems with the data (1112)";
+
+ case VRInitError_Steam_SteamInstallationNotFound: return "Unable to find Steam installation (2000)";
+
+ default:
+ {
+ static char buf[128];
+ sprintf( buf, "Unknown error (%d)", eError );
+ return buf;
+ }
+ }
+
+}
+
+
+const char *GetIDForVRInitError( vr::EVRInitError eError )
+{
+ switch( eError )
+ {
+ RETURN_ENUM_AS_STRING( VRInitError_None );
+ RETURN_ENUM_AS_STRING( VRInitError_Unknown );
+
+ RETURN_ENUM_AS_STRING( VRInitError_Init_InstallationNotFound );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_InstallationCorrupt );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_VRClientDLLNotFound );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_FileNotFound );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_FactoryNotFound );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_InterfaceNotFound );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_InvalidInterface );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_UserConfigDirectoryInvalid );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_HmdNotFound );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_NotInitialized );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_PathRegistryNotFound );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_NoConfigPath );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_NoLogPath );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_PathRegistryNotWritable );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_AppInfoInitFailed );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_Retry );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_InitCanceledByUser );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_AnotherAppLaunching );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_SettingsInitFailed );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_ShuttingDown );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_TooManyObjects );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_NoServerForBackgroundApp );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_NotSupportedWithCompositor );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_NotAvailableToUtilityApps );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_Internal );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_VRMonitorNotFound );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_VRMonitorStartupFailed );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_LowPowerWatchdogNotSupported );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_InvalidApplicationType );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_NotAvailableToWatchdogApps );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_WatchdogDisabledInSettings );
+
+ RETURN_ENUM_AS_STRING( VRInitError_Init_HmdDriverIdIsNone );
+ RETURN_ENUM_AS_STRING( VRInitError_Init_HmdNotFoundPresenceFailed );
+
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_Failed );
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_Unknown );
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_HmdUnknown);
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_NotLoaded);
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_RuntimeOutOfDate);
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_HmdInUse);
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_NotCalibrated);
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_CalibrationInvalid);
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_HmdDisplayNotFound);
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_TrackedDeviceInterfaceUnknown );
+ // RETURN_ENUM_AS_STRING( VRInitError_Driver_HmdDisplayNotFoundAfterFix );
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_HmdDriverIdOutOfBounds );
+ RETURN_ENUM_AS_STRING( VRInitError_Driver_HmdDisplayMirrored );
+
+ RETURN_ENUM_AS_STRING( VRInitError_IPC_ServerInitFailed);
+ RETURN_ENUM_AS_STRING( VRInitError_IPC_ConnectFailed);
+ RETURN_ENUM_AS_STRING( VRInitError_IPC_SharedStateInitFailed);
+ RETURN_ENUM_AS_STRING( VRInitError_IPC_CompositorInitFailed);
+ RETURN_ENUM_AS_STRING( VRInitError_IPC_MutexInitFailed);
+ RETURN_ENUM_AS_STRING( VRInitError_IPC_Failed);
+ RETURN_ENUM_AS_STRING( VRInitError_IPC_CompositorConnectFailed);
+ RETURN_ENUM_AS_STRING( VRInitError_IPC_CompositorInvalidConnectResponse);
+ RETURN_ENUM_AS_STRING( VRInitError_IPC_ConnectFailedAfterMultipleAttempts);
+
+ RETURN_ENUM_AS_STRING( VRInitError_Compositor_Failed );
+ RETURN_ENUM_AS_STRING( VRInitError_Compositor_D3D11HardwareRequired );
+ RETURN_ENUM_AS_STRING( VRInitError_Compositor_FirmwareRequiresUpdate );
+ RETURN_ENUM_AS_STRING( VRInitError_Compositor_OverlayInitFailed );
+
+ // Oculus
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_UnableToConnectToOculusRuntime);
+
+ // Lighthouse
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_CantOpenDevice);
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_UnableToRequestConfigStart);
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_NoStoredConfig);
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_ConfigFailedSanityCheck );
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_ConfigTooBig );
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_ConfigTooSmall );
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_UnableToInitZLib );
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_CantReadFirmwareVersion );
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_UnableToSendUserDataStart );
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_UnableToGetUserDataStart );
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_UnableToGetUserDataNext );
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_UserDataAddressRange );
+ RETURN_ENUM_AS_STRING( VRInitError_VendorSpecific_HmdFound_UserDataError );
+
+ RETURN_ENUM_AS_STRING( VRInitError_Steam_SteamInstallationNotFound );
+
+ default:
+ {
+ static char buf[128];
+ sprintf( buf, "Unknown error (%d)", eError );
+ return buf;
+ }
+ }
+}
+
diff --git a/src/vrcommon/pathtools.h b/src/vrcommon/pathtools.h
new file mode 100644
index 0000000..7c34a71
--- /dev/null
+++ b/src/vrcommon/pathtools.h
@@ -0,0 +1,129 @@
+//========= Copyright Valve Corporation ============//
+#pragma once
+
+#include <string>
+#include <stdint.h>
+
+/** Returns the path (including filename) to the current executable */
+std::string Path_GetExecutablePath();
+
+/** Returns the path of the current working directory */
+std::string Path_GetWorkingDirectory();
+
+/** Sets the path of the current working directory. Returns true if this was successful. */
+bool Path_SetWorkingDirectory( const std::string & sPath );
+
+/** returns the path (including filename) of the current shared lib or DLL */
+std::string Path_GetThisModulePath();
+
+/** Returns the specified path without its filename.
+* If slash is unspecified the native path separator of the current platform
+* will be used. */
+std::string Path_StripFilename( const std::string & sPath, char slash = 0 );
+
+/** returns just the filename from the provided full or relative path. */
+std::string Path_StripDirectory( const std::string & sPath, char slash = 0 );
+
+/** returns just the filename with no extension of the provided filename.
+* If there is a path the path is left intact. */
+std::string Path_StripExtension( const std::string & sPath );
+
+/** returns just extension of the provided filename (if any). */
+std::string Path_GetExtension( const std::string & sPath );
+
+/** Returns true if the path is absolute */
+bool Path_IsAbsolute( const std::string & sPath );
+
+/** Makes an absolute path from a relative path and a base path */
+std::string Path_MakeAbsolute( const std::string & sRelativePath, const std::string & sBasePath, char slash = 0 );
+
+/** Fixes the directory separators for the current platform.
+* If slash is unspecified the native path separator of the current platform
+* will be used. */
+std::string Path_FixSlashes( const std::string & sPath, char slash = 0 );
+
+/** Returns the path separator for the current platform */
+char Path_GetSlash();
+
+/** Jams two paths together with the right kind of slash */
+std::string Path_Join( const std::string & first, const std::string & second, char slash = 0 );
+std::string Path_Join( const std::string & first, const std::string & second, const std::string & third, char slash = 0 );
+std::string Path_Join( const std::string & first, const std::string & second, const std::string & third, const std::string &fourth, char slash = 0 );
+std::string Path_Join(
+ const std::string & first,
+ const std::string & second,
+ const std::string & third,
+ const std::string & fourth,
+ const std::string & fifth,
+ char slash = 0 );
+
+
+/** Removes redundant <dir>/.. elements in the path. Returns an empty path if the
+* specified path has a broken number of directories for its number of ..s.
+* If slash is unspecified the native path separator of the current platform
+* will be used. */
+std::string Path_Compact( const std::string & sRawPath, char slash = 0 );
+
+//** Removed trailing slashes */
+std::string Path_RemoveTrailingSlash( const std::string & sRawPath, char slash = 0 );
+
+/** returns true if the specified path exists and is a directory */
+bool Path_IsDirectory( const std::string & sPath );
+
+/** returns true if the specified path represents an app bundle */
+bool Path_IsAppBundle( const std::string & sPath );
+
+/** returns true if the the path exists */
+bool Path_Exists( const std::string & sPath );
+
+/** Helper functions to find parent directories or subdirectories of parent directories */
+std::string Path_FindParentDirectoryRecursively( const std::string &strStartDirectory, const std::string &strDirectoryName );
+std::string Path_FindParentSubDirectoryRecursively( const std::string &strStartDirectory, const std::string &strDirectoryName );
+
+/** Path operations to read or write text/binary files */
+unsigned char * Path_ReadBinaryFile( const std::string &strFilename, int *pSize );
+uint32_t Path_ReadBinaryFile( const std::string &strFilename, unsigned char *pBuffer, uint32_t unSize );
+bool Path_WriteBinaryFile( const std::string &strFilename, unsigned char *pData, unsigned nSize );
+std::string Path_ReadTextFile( const std::string &strFilename );
+bool Path_WriteStringToTextFile( const std::string &strFilename, const char *pchData );
+bool Path_WriteStringToTextFileAtomic( const std::string &strFilename, const char *pchData );
+
+/** Returns a file:// url for paths, or an http or https url if that's what was provided */
+std::string Path_FilePathToUrl( const std::string & sRelativePath, const std::string & sBasePath );
+
+/** Strips off file:// off a URL and returns the path. For other kinds of URLs an empty string is returned */
+std::string Path_UrlToFilePath( const std::string & sFileUrl );
+
+/** Returns the root of the directory the system wants us to store user documents in */
+std::string GetUserDocumentsPath();
+
+#ifndef MAX_UNICODE_PATH
+ #define MAX_UNICODE_PATH 32767
+#endif
+
+#ifndef MAX_UNICODE_PATH_IN_UTF8
+ #define MAX_UNICODE_PATH_IN_UTF8 (MAX_UNICODE_PATH * 4)
+#endif
+
+//-----------------------------------------------------------------------------
+#if defined(WIN32)
+#define DYNAMIC_LIB_EXT ".dll"
+#ifdef _WIN64
+#define PLATSUBDIR "win64"
+#else
+#define PLATSUBDIR "win32"
+#endif
+#elif defined(OSX)
+#define DYNAMIC_LIB_EXT ".dylib"
+#define PLATSUBDIR "osx32"
+#elif defined(LINUX)
+#define DYNAMIC_LIB_EXT ".so"
+#if defined( LINUX32 )
+#define PLATSUBDIR "linux32"
+#else
+#define PLATSUBDIR "linux64"
+#endif
+#else
+#warning "Unknown platform for PLATSUBDIR"
+#define PLATSUBDIR "unknown_platform"
+#endif
diff --git a/src/vrcommon/pathtools_public.cpp b/src/vrcommon/pathtools_public.cpp
new file mode 100644
index 0000000..f132c2e
--- /dev/null
+++ b/src/vrcommon/pathtools_public.cpp
@@ -0,0 +1,817 @@
+//========= Copyright Valve Corporation ============//
+#include "strtools.h"
+#include "pathtools.h"
+
+#if defined( _WIN32)
+#include <Windows.h>
+#include <direct.h>
+#include <Shobjidl.h>
+#include <KnownFolders.h>
+#include <Shlobj.h>
+
+#undef GetEnvironmentVariable
+#else
+#include <dlfcn.h>
+#include <stdio.h>
+#include <unistd.h>
+#endif
+#if defined OSX
+#include <Foundation/Foundation.h>
+#include <AppKit/AppKit.h>
+#include <mach-o/dyld.h>
+#define _S_IFDIR S_IFDIR // really from tier0/platform.h which we dont have yet
+#endif
+
+#include <sys/stat.h>
+
+#include <algorithm>
+
+/** Returns the path (including filename) to the current executable */
+std::string Path_GetExecutablePath()
+{
+#if defined( _WIN32 )
+ wchar_t *pwchPath = new wchar_t[MAX_UNICODE_PATH];
+ char *pchPath = new char[MAX_UNICODE_PATH_IN_UTF8];
+ ::GetModuleFileNameW( NULL, pwchPath, MAX_UNICODE_PATH );
+ WideCharToMultiByte( CP_UTF8, 0, pwchPath, -1, pchPath, MAX_UNICODE_PATH_IN_UTF8, NULL, NULL );
+ delete[] pwchPath;
+
+ std::string sPath = pchPath;
+ delete[] pchPath;
+ return sPath;
+#elif defined( OSX )
+ char rchPath[1024];
+ uint32_t nBuff = sizeof( rchPath );
+ bool bSuccess = _NSGetExecutablePath(rchPath, &nBuff) == 0;
+ rchPath[nBuff-1] = '\0';
+ if( bSuccess )
+ return rchPath;
+ else
+ return "";
+#elif defined LINUX
+ char rchPath[1024];
+ size_t nBuff = sizeof( rchPath );
+ ssize_t nRead = readlink("/proc/self/exe", rchPath, nBuff-1 );
+ if ( nRead != -1 )
+ {
+ rchPath[ nRead ] = 0;
+ return rchPath;
+ }
+ else
+ {
+ return "";
+ }
+#else
+ AssertMsg( false, "Implement Plat_GetExecutablePath" );
+ return "";
+#endif
+
+}
+
+/** Returns the path of the current working directory */
+std::string Path_GetWorkingDirectory()
+{
+ std::string sPath;
+#if defined( _WIN32 )
+ wchar_t buf[MAX_UNICODE_PATH];
+ sPath = UTF16to8( _wgetcwd( buf, MAX_UNICODE_PATH ) );
+#else
+ char buf[ 1024 ];
+ sPath = getcwd( buf, sizeof( buf ) );
+#endif
+ return sPath;
+}
+
+/** Sets the path of the current working directory. Returns true if this was successful. */
+bool Path_SetWorkingDirectory( const std::string & sPath )
+{
+ bool bSuccess;
+#if defined( _WIN32 )
+ std::wstring wsPath = UTF8to16( sPath.c_str() );
+ bSuccess = 0 == _wchdir( wsPath.c_str() );
+#else
+ bSuccess = 0 == chdir( sPath.c_str() );
+#endif
+ return bSuccess;
+}
+
+/** Returns the specified path without its filename */
+std::string Path_StripFilename( const std::string & sPath, char slash )
+{
+ if( slash == 0 )
+ slash = Path_GetSlash();
+
+ std::string::size_type n = sPath.find_last_of( slash );
+ if( n == std::string::npos )
+ return sPath;
+ else
+ return std::string( sPath.begin(), sPath.begin() + n );
+}
+
+/** returns just the filename from the provided full or relative path. */
+std::string Path_StripDirectory( const std::string & sPath, char slash )
+{
+ if( slash == 0 )
+ slash = Path_GetSlash();
+
+ std::string::size_type n = sPath.find_last_of( slash );
+ if( n == std::string::npos )
+ return sPath;
+ else
+ return std::string( sPath.begin() + n + 1, sPath.end() );
+}
+
+/** returns just the filename with no extension of the provided filename.
+* If there is a path the path is left intact. */
+std::string Path_StripExtension( const std::string & sPath )
+{
+ for( std::string::const_reverse_iterator i = sPath.rbegin(); i != sPath.rend(); i++ )
+ {
+ if( *i == '.' )
+ {
+ return std::string( sPath.begin(), i.base() - 1 );
+ }
+
+ // if we find a slash there is no extension
+ if( *i == '\\' || *i == '/' )
+ break;
+ }
+
+ // we didn't find an extension
+ return sPath;
+}
+
+/** returns just extension of the provided filename (if any). */
+std::string Path_GetExtension( const std::string & sPath )
+{
+ for ( std::string::const_reverse_iterator i = sPath.rbegin(); i != sPath.rend(); i++ )
+ {
+ if ( *i == '.' )
+ {
+ return std::string( i.base(), sPath.end() );
+ }
+
+ // if we find a slash there is no extension
+ if ( *i == '\\' || *i == '/' )
+ break;
+ }
+
+ // we didn't find an extension
+ return "";
+}
+
+bool Path_IsAbsolute( const std::string & sPath )
+{
+ if( sPath.empty() )
+ return false;
+
+#if defined( WIN32 )
+ if ( sPath.size() < 3 ) // must be c:\x or \\x at least
+ return false;
+
+ if ( sPath[1] == ':' ) // drive letter plus slash, but must test both slash cases
+ {
+ if ( sPath[2] == '\\' || sPath[2] == '/' )
+ return true;
+ }
+ else if ( sPath[0] == '\\' && sPath[1] == '\\' ) // UNC path
+ return true;
+#else
+ if( sPath[0] == '\\' || sPath[0] == '/' ) // any leading slash
+ return true;
+#endif
+
+ return false;
+}
+
+
+/** Makes an absolute path from a relative path and a base path */
+std::string Path_MakeAbsolute( const std::string & sRelativePath, const std::string & sBasePath, char slash )
+{
+ if( slash == 0 )
+ slash = Path_GetSlash();
+
+ if( Path_IsAbsolute( sRelativePath ) )
+ return sRelativePath;
+ else
+ {
+ if( !Path_IsAbsolute( sBasePath ) )
+ return "";
+
+ std::string sCompacted = Path_Compact( Path_Join( sBasePath, sRelativePath, slash ), slash );
+ if( Path_IsAbsolute( sCompacted ) )
+ return sCompacted;
+ else
+ return "";
+ }
+}
+
+
+/** Fixes the directory separators for the current platform */
+std::string Path_FixSlashes( const std::string & sPath, char slash )
+{
+ if( slash == 0 )
+ slash = Path_GetSlash();
+
+ std::string sFixed = sPath;
+ for( std::string::iterator i = sFixed.begin(); i != sFixed.end(); i++ )
+ {
+ if( *i == '/' || *i == '\\' )
+ *i = slash;
+ }
+
+ return sFixed;
+}
+
+
+char Path_GetSlash()
+{
+#if defined(_WIN32)
+ return '\\';
+#else
+ return '/';
+#endif
+}
+
+/** Jams two paths together with the right kind of slash */
+std::string Path_Join( const std::string & first, const std::string & second, char slash )
+{
+ if( slash == 0 )
+ slash = Path_GetSlash();
+
+ // only insert a slash if we don't already have one
+ std::string::size_type nLen = first.length();
+ if( !nLen )
+ return second;
+#if defined(_WIN32)
+ if( first.back() == '\\' || first.back() == '/' )
+ nLen--;
+#else
+ char last_char = first[first.length()-1];
+ if (last_char == '\\' || last_char == '/')
+ nLen--;
+#endif
+
+ return first.substr( 0, nLen ) + std::string( 1, slash ) + second;
+}
+
+
+std::string Path_Join( const std::string & first, const std::string & second, const std::string & third, char slash )
+{
+ return Path_Join( Path_Join( first, second, slash ), third, slash );
+}
+
+std::string Path_Join( const std::string & first, const std::string & second, const std::string & third, const std::string &fourth, char slash )
+{
+ return Path_Join( Path_Join( Path_Join( first, second, slash ), third, slash ), fourth, slash );
+}
+
+std::string Path_Join(
+ const std::string & first,
+ const std::string & second,
+ const std::string & third,
+ const std::string & fourth,
+ const std::string & fifth,
+ char slash )
+{
+ return Path_Join( Path_Join( Path_Join( Path_Join( first, second, slash ), third, slash ), fourth, slash ), fifth, slash );
+}
+
+
+std::string Path_RemoveTrailingSlash( const std::string & sRawPath, char slash )
+{
+ if ( slash == 0 )
+ slash = Path_GetSlash();
+
+ std::string sPath = sRawPath;
+ std::string::size_type nCurrent = sRawPath.length();
+ if ( nCurrent == 0 )
+ return sPath;
+
+ int nLastFound = -1;
+ nCurrent--;
+ while( nCurrent != 0 )
+ {
+ if ( sRawPath[ nCurrent ] == slash )
+ {
+ nLastFound = (int)nCurrent;
+ nCurrent--;
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ if ( nLastFound >= 0 )
+ {
+ sPath.erase( nLastFound, std::string::npos );
+ }
+
+ return sPath;
+}
+
+
+/** Removes redundant <dir>/.. elements in the path. Returns an empty path if the
+* specified path has a broken number of directories for its number of ..s */
+std::string Path_Compact( const std::string & sRawPath, char slash )
+{
+ if( slash == 0 )
+ slash = Path_GetSlash();
+
+ std::string sPath = Path_FixSlashes( sRawPath, slash );
+ std::string sSlashString( 1, slash );
+
+ // strip out all /./
+ for( std::string::size_type i = 0; (i + 3) < sPath.length(); )
+ {
+ if( sPath[ i ] == slash && sPath[ i+1 ] == '.' && sPath[ i+2 ] == slash )
+ {
+ sPath.replace( i, 3, sSlashString );
+ }
+ else
+ {
+ ++i;
+ }
+ }
+
+
+ // get rid of trailing /. but leave the path separator
+ if( sPath.length() > 2 )
+ {
+ std::string::size_type len = sPath.length();
+ if( sPath[ len-1 ] == '.' && sPath[ len-2 ] == slash )
+ {
+ // sPath.pop_back();
+ sPath[len-1] = 0; // for now, at least
+ }
+ }
+
+ // get rid of leading ./
+ if( sPath.length() > 2 )
+ {
+ if( sPath[ 0 ] == '.' && sPath[ 1 ] == slash )
+ {
+ sPath.replace( 0, 2, "" );
+ }
+ }
+
+ // each time we encounter .. back up until we've found the previous directory name
+ // then get rid of both
+ std::string::size_type i = 0;
+ while( i < sPath.length() )
+ {
+ if( i > 0 && sPath.length() - i >= 2
+ && sPath[i] == '.'
+ && sPath[i+1] == '.'
+ && ( i + 2 == sPath.length() || sPath[ i+2 ] == slash )
+ && sPath[ i-1 ] == slash )
+ {
+ // check if we've hit the start of the string and have a bogus path
+ if( i == 1 )
+ return "";
+
+ // find the separator before i-1
+ std::string::size_type iDirStart = i-2;
+ while( iDirStart > 0 && sPath[ iDirStart - 1 ] != slash )
+ --iDirStart;
+
+ // remove everything from iDirStart to i+2
+ sPath.replace( iDirStart, (i - iDirStart) + 3, "" );
+
+ // start over
+ i = 0;
+ }
+ else
+ {
+ ++i;
+ }
+ }
+
+ return sPath;
+}
+
+
+/** Returns the path to the current DLL or exe */
+std::string Path_GetThisModulePath()
+{
+ // gets the path of vrclient.dll itself
+#ifdef WIN32
+ HMODULE hmodule = NULL;
+
+ ::GetModuleHandleEx( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast<LPCTSTR>(Path_GetThisModulePath), &hmodule );
+
+ wchar_t *pwchPath = new wchar_t[MAX_UNICODE_PATH];
+ char *pchPath = new char[ MAX_UNICODE_PATH_IN_UTF8 ];
+ ::GetModuleFileNameW( hmodule, pwchPath, MAX_UNICODE_PATH );
+ WideCharToMultiByte( CP_UTF8, 0, pwchPath, -1, pchPath, MAX_UNICODE_PATH_IN_UTF8, NULL, NULL );
+ delete[] pwchPath;
+
+ std::string sPath = pchPath;
+ delete [] pchPath;
+ return sPath;
+
+#elif defined( OSX ) || defined( LINUX )
+ // get the addr of a function in vrclient.so and then ask the dlopen system about it
+ Dl_info info;
+ dladdr( (void *)Path_GetThisModulePath, &info );
+ return info.dli_fname;
+#endif
+
+}
+
+
+/** returns true if the specified path exists and is a directory */
+bool Path_IsDirectory( const std::string & sPath )
+{
+ std::string sFixedPath = Path_FixSlashes( sPath );
+ if( sFixedPath.empty() )
+ return false;
+ char cLast = sFixedPath[ sFixedPath.length() - 1 ];
+ if( cLast == '/' || cLast == '\\' )
+ sFixedPath.erase( sFixedPath.end() - 1, sFixedPath.end() );
+
+ // see if the specified path actually exists.
+
+#if defined(POSIX)
+ struct stat buf;
+ if ( stat( sFixedPath.c_str(), &buf ) == -1 )
+ {
+ return false;
+ }
+
+#if defined( LINUX ) || defined( OSX )
+ return S_ISDIR( buf.st_mode );
+#else
+ return (buf.st_mode & _S_IFDIR) != 0;
+#endif
+
+#else
+ struct _stat buf;
+ std::wstring wsFixedPath = UTF8to16( sFixedPath.c_str() );
+ if ( _wstat( wsFixedPath.c_str(), &buf ) == -1 )
+ {
+ return false;
+ }
+
+ return (buf.st_mode & _S_IFDIR) != 0;
+#endif
+}
+
+/** returns true if the specified path represents an app bundle */
+bool Path_IsAppBundle( const std::string & sPath )
+{
+#if defined(OSX)
+ NSBundle *bundle = [ NSBundle bundleWithPath: [ NSString stringWithUTF8String:sPath.c_str() ] ];
+ bool bisAppBundle = ( nullptr != bundle );
+ [ bundle release ];
+ return bisAppBundle;
+#else
+ return false;
+#endif
+}
+
+//-----------------------------------------------------------------------------
+// Purpose: returns true if the the path exists
+//-----------------------------------------------------------------------------
+bool Path_Exists( const std::string & sPath )
+{
+ std::string sFixedPath = Path_FixSlashes( sPath );
+ if( sFixedPath.empty() )
+ return false;
+
+#if defined( WIN32 )
+ struct _stat buf;
+ std::wstring wsFixedPath = UTF8to16( sFixedPath.c_str() );
+ if ( _wstat( wsFixedPath.c_str(), &buf ) == -1 )
+ {
+ return false;
+ }
+#else
+ struct stat buf;
+ if ( stat ( sFixedPath.c_str(), &buf ) == -1)
+ {
+ return false;
+ }
+#endif
+
+ return true;
+}
+
+
+//-----------------------------------------------------------------------------
+// Purpose: helper to find a directory upstream from a given path
+//-----------------------------------------------------------------------------
+std::string Path_FindParentDirectoryRecursively( const std::string &strStartDirectory, const std::string &strDirectoryName )
+{
+ std::string strFoundPath = "";
+ std::string strCurrentPath = Path_FixSlashes( strStartDirectory );
+ if ( strCurrentPath.length() == 0 )
+ return "";
+
+ bool bExists = Path_Exists( strCurrentPath );
+ std::string strCurrentDirectoryName = Path_StripDirectory( strCurrentPath );
+ if ( bExists && stricmp( strCurrentDirectoryName.c_str(), strDirectoryName.c_str() ) == 0 )
+ return strCurrentPath;
+
+ while( bExists && strCurrentPath.length() != 0 )
+ {
+ strCurrentPath = Path_StripFilename( strCurrentPath );
+ strCurrentDirectoryName = Path_StripDirectory( strCurrentPath );
+ bExists = Path_Exists( strCurrentPath );
+ if ( bExists && stricmp( strCurrentDirectoryName.c_str(), strDirectoryName.c_str() ) == 0 )
+ return strCurrentPath;
+ }
+
+ return "";
+}
+
+
+//-----------------------------------------------------------------------------
+// Purpose: helper to find a subdirectory upstream from a given path
+//-----------------------------------------------------------------------------
+std::string Path_FindParentSubDirectoryRecursively( const std::string &strStartDirectory, const std::string &strDirectoryName )
+{
+ std::string strFoundPath = "";
+ std::string strCurrentPath = Path_FixSlashes( strStartDirectory );
+ if ( strCurrentPath.length() == 0 )
+ return "";
+
+ bool bExists = Path_Exists( strCurrentPath );
+ while( bExists && strCurrentPath.length() != 0 )
+ {
+ strCurrentPath = Path_StripFilename( strCurrentPath );
+ bExists = Path_Exists( strCurrentPath );
+
+ if( Path_Exists( Path_Join( strCurrentPath, strDirectoryName ) ) )
+ {
+ strFoundPath = Path_Join( strCurrentPath, strDirectoryName );
+ break;
+ }
+ }
+ return strFoundPath;
+}
+
+
+//-----------------------------------------------------------------------------
+// Purpose: reading and writing files in the vortex directory
+//-----------------------------------------------------------------------------
+unsigned char * Path_ReadBinaryFile( const std::string &strFilename, int *pSize )
+{
+ FILE *f;
+#if defined( POSIX )
+ f = fopen( strFilename.c_str(), "rb" );
+#else
+ std::wstring wstrFilename = UTF8to16( strFilename.c_str() );
+ // the open operation needs to be sharable, therefore use of _wfsopen instead of _wfopen_s
+ f = _wfsopen( wstrFilename.c_str(), L"rb", _SH_DENYNO );
+#endif
+
+ unsigned char* buf = NULL;
+
+ if ( f != NULL )
+ {
+ fseek(f, 0, SEEK_END);
+ int size = ftell(f);
+ fseek(f, 0, SEEK_SET);
+
+ buf = new unsigned char[size];
+ if (buf && fread(buf, size, 1, f) == 1)
+ {
+ if (pSize)
+ *pSize = size;
+ }
+ else
+ {
+ delete[] buf;
+ buf = 0;
+ }
+
+ fclose(f);
+ }
+
+ return buf;
+}
+
+uint32_t Path_ReadBinaryFile( const std::string &strFilename, unsigned char *pBuffer, uint32_t unSize )
+{
+ FILE *f;
+#if defined( POSIX )
+ f = fopen( strFilename.c_str(), "rb" );
+#else
+ std::wstring wstrFilename = UTF8to16( strFilename.c_str() );
+ errno_t err = _wfopen_s( &f, wstrFilename.c_str(), L"rb" );
+ if ( err != 0 )
+ {
+ f = NULL;
+ }
+#endif
+
+ uint32_t unSizeToReturn = 0;
+
+ if ( f != NULL )
+ {
+ fseek( f, 0, SEEK_END );
+ uint32_t size = (uint32_t)ftell( f );
+ fseek( f, 0, SEEK_SET );
+
+ if ( size > unSize || !pBuffer )
+ {
+ unSizeToReturn = (uint32_t)size;
+ }
+ else
+ {
+ if ( fread( pBuffer, size, 1, f ) == 1 )
+ {
+ unSizeToReturn = (uint32_t)size;
+ }
+ }
+
+ fclose( f );
+ }
+
+ return unSizeToReturn;
+}
+
+bool Path_WriteBinaryFile(const std::string &strFilename, unsigned char *pData, unsigned nSize)
+{
+ FILE *f;
+#if defined( POSIX )
+ f = fopen(strFilename.c_str(), "wb");
+#else
+ std::wstring wstrFilename = UTF8to16( strFilename.c_str() );
+ errno_t err = _wfopen_s( &f, wstrFilename.c_str(), L"wb" );
+ if (err != 0)
+ {
+ f = NULL;
+ }
+#endif
+
+ size_t written = 0;
+ if (f != NULL) {
+ written = fwrite(pData, sizeof(unsigned char), nSize, f);
+ fclose(f);
+ }
+
+ return written = nSize ? true : false;
+}
+
+std::string Path_ReadTextFile( const std::string &strFilename )
+{
+ // doing it this way seems backwards, but I don't
+ // see an easy way to do this with C/C++ style IO
+ // that isn't worse...
+ int size;
+ unsigned char* buf = Path_ReadBinaryFile( strFilename, &size );
+ if (!buf)
+ return "";
+
+ // convert CRLF -> LF
+ int outsize = 1;
+ for (int i=1; i < size; i++)
+ {
+ if (buf[i] == '\n' && buf[i-1] == '\r') // CRLF
+ buf[outsize-1] = '\n'; // ->LF
+ else
+ buf[outsize++] = buf[i]; // just copy
+ }
+
+ std::string ret((char *)buf, (char *)(buf + outsize));
+ delete[] buf;
+ return ret;
+}
+
+
+bool Path_WriteStringToTextFile( const std::string &strFilename, const char *pchData )
+{
+ FILE *f;
+#if defined( POSIX )
+ f = fopen( strFilename.c_str(), "w" );
+#else
+ std::wstring wstrFilename = UTF8to16( strFilename.c_str() );
+ errno_t err = _wfopen_s( &f, wstrFilename.c_str(), L"w" );
+ if ( err != 0 )
+ {
+ f = NULL;
+ }
+#endif
+
+ bool ok = false;
+
+ if ( f != NULL )
+ {
+ ok = fputs( pchData, f) >= 0;
+ fclose(f);
+ }
+
+ return ok;
+}
+
+bool Path_WriteStringToTextFileAtomic( const std::string &strFilename, const char *pchData )
+{
+ std::string strTmpFilename = strFilename + ".tmp";
+
+ if ( !Path_WriteStringToTextFile( strTmpFilename, pchData ) )
+ return false;
+
+ // Platform specific atomic file replacement
+#if defined( _WIN32 )
+ std::wstring wsFilename = UTF8to16( strFilename.c_str() );
+ std::wstring wsTmpFilename = UTF8to16( strTmpFilename.c_str() );
+ if ( !::ReplaceFileW( wsFilename.c_str(), wsTmpFilename.c_str(), nullptr, 0, 0, 0 ) )
+ {
+ // if we couldn't ReplaceFile, try a non-atomic write as a fallback
+ if ( !Path_WriteStringToTextFile( strFilename, pchData ) )
+ return false;
+ }
+#elif defined( POSIX )
+ if ( rename( strTmpFilename.c_str(), strFilename.c_str() ) == -1 )
+ return false;
+#else
+#error Do not know how to write atomic file
+#endif
+
+ return true;
+}
+
+
+#if defined(WIN32)
+#define FILE_URL_PREFIX "file:///"
+#else
+#define FILE_URL_PREFIX "file://"
+#endif
+
+// ----------------------------------------------------------------------------------------------------------------------------
+// Purpose: Turns a path to a file on disk into a URL (or just returns the value if it's already a URL)
+// ----------------------------------------------------------------------------------------------------------------------------
+std::string Path_FilePathToUrl( const std::string & sRelativePath, const std::string & sBasePath )
+{
+ if ( !strnicmp( sRelativePath.c_str(), "http://", 7 )
+ || !strnicmp( sRelativePath.c_str(), "https://", 8 )
+ || !strnicmp( sRelativePath.c_str(), "file://", 7 ) )
+ {
+ return sRelativePath;
+ }
+ else
+ {
+ std::string sAbsolute = Path_MakeAbsolute( sRelativePath, sBasePath );
+ if ( sAbsolute.empty() )
+ return sAbsolute;
+ return std::string( FILE_URL_PREFIX ) + sAbsolute;
+ }
+}
+
+// -----------------------------------------------------------------------------------------------------
+// Purpose: Strips off file:// off a URL and returns the path. For other kinds of URLs an empty string is returned
+// -----------------------------------------------------------------------------------------------------
+std::string Path_UrlToFilePath( const std::string & sFileUrl )
+{
+ if ( !strnicmp( sFileUrl.c_str(), FILE_URL_PREFIX, strlen( FILE_URL_PREFIX ) ) )
+ {
+ return sFileUrl.c_str() + strlen( FILE_URL_PREFIX );
+ }
+ else
+ {
+ return "";
+ }
+}
+
+
+// -----------------------------------------------------------------------------------------------------
+// Purpose: Returns the root of the directory the system wants us to store user documents in
+// -----------------------------------------------------------------------------------------------------
+std::string GetUserDocumentsPath()
+{
+#if defined( WIN32 )
+ WCHAR rwchPath[MAX_PATH];
+
+ if ( !SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_MYDOCUMENTS | CSIDL_FLAG_CREATE, NULL, 0, rwchPath ) ) )
+ {
+ return "";
+ }
+
+ // Convert the path to UTF-8 and store in the output
+ std::string sUserPath = UTF16to8( rwchPath );
+
+ return sUserPath;
+#elif defined( OSX )
+ @autoreleasepool {
+ NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
+ if ( [paths count] == 0 )
+ {
+ return "";
+ }
+
+ return [[paths objectAtIndex:0] UTF8String];
+ }
+#elif defined( LINUX )
+ // @todo: not solved/changed as part of OSX - still not real - just removed old class based steam cut and paste
+ const char *pchHome = getenv( "HOME" );
+ if ( pchHome == NULL )
+ {
+ return "";
+ }
+ return pchHome;
+#endif
+}
+
diff --git a/src/vrcommon/sharedlibtools.h b/src/vrcommon/sharedlibtools.h
new file mode 100644
index 0000000..10163db
--- /dev/null
+++ b/src/vrcommon/sharedlibtools.h
@@ -0,0 +1,10 @@
+//========= Copyright Valve Corporation ============//
+#pragma once
+
+typedef void *SharedLibHandle;
+
+SharedLibHandle SharedLib_Load( const char *pchPath );
+void *SharedLib_GetFunction( SharedLibHandle lib, const char *pchFunctionName);
+void SharedLib_Unload( SharedLibHandle lib );
+
+
diff --git a/src/vrcommon/sharedlibtools_public.cpp b/src/vrcommon/sharedlibtools_public.cpp
new file mode 100644
index 0000000..99eb150
--- /dev/null
+++ b/src/vrcommon/sharedlibtools_public.cpp
@@ -0,0 +1,41 @@
+//========= Copyright Valve Corporation ============//
+#include "sharedlibtools.h"
+#include <string.h>
+
+#if defined(_WIN32)
+#include <Windows.h>
+#endif
+
+#if defined(POSIX)
+#include <dlfcn.h>
+#endif
+
+SharedLibHandle SharedLib_Load( const char *pchPath )
+{
+#if defined( _WIN32)
+ return (SharedLibHandle)LoadLibraryEx( pchPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH );
+#elif defined(POSIX)
+ return (SharedLibHandle)dlopen(pchPath, RTLD_LOCAL|RTLD_NOW);
+#endif
+}
+
+void *SharedLib_GetFunction( SharedLibHandle lib, const char *pchFunctionName)
+{
+#if defined( _WIN32)
+ return GetProcAddress( (HMODULE)lib, pchFunctionName );
+#elif defined(POSIX)
+ return dlsym( lib, pchFunctionName );
+#endif
+}
+
+
+void SharedLib_Unload( SharedLibHandle lib )
+{
+#if defined( _WIN32)
+ FreeLibrary( (HMODULE)lib );
+#elif defined(POSIX)
+ dlclose( lib );
+#endif
+}
+
+
diff --git a/src/vrcommon/strtools.h b/src/vrcommon/strtools.h
new file mode 100644
index 0000000..4bab9b7
--- /dev/null
+++ b/src/vrcommon/strtools.h
@@ -0,0 +1,126 @@
+//========= Copyright Valve Corporation ============//
+#pragma once
+
+#include <string>
+#include <stdint.h>
+#include <sys/types.h>
+
+/** returns true if the string has the prefix */
+bool StringHasPrefix( const std::string & sString, const std::string & sPrefix );
+bool StringHasPrefixCaseSensitive( const std::string & sString, const std::string & sPrefix );
+
+/** returns if the string has the suffix */
+bool StringHasSuffix( const std::string &sString, const std::string &sSuffix );
+bool StringHasSuffixCaseSensitive( const std::string &sString, const std::string &sSuffix );
+
+/** converts a UTF-16 string to a UTF-8 string */
+std::string UTF16to8(const wchar_t * in);
+
+/** converts a UTF-8 string to a UTF-16 string */
+std::wstring UTF8to16(const char * in);
+#define Utf16FromUtf8 UTF8to16
+
+/** safely copy a string into a buffer */
+void strcpy_safe( char *pchBuffer, size_t unBufferSizeBytes, const char *pchSource );
+template< size_t bufferSize >
+void strcpy_safe( char (& buffer) [ bufferSize ], const char *pchSource )
+{
+ strcpy_safe( buffer, bufferSize, pchSource );
+}
+
+
+/** converts a string to upper case */
+std::string StringToUpper( const std::string & sString );
+
+/** converts a string to lower case */
+std::string StringToLower( const std::string & sString );
+
+// we stricmp (from WIN) but it isn't POSIX - OSX/LINUX have strcasecmp so just inline bridge to it
+#if defined( OSX ) || defined( LINUX )
+#include <strings.h>
+inline int stricmp(const char *pStr1, const char *pStr2) { return strcasecmp(pStr1,pStr2); }
+#define _stricmp stricmp
+inline int strnicmp( const char *pStr1, const char *pStr2, size_t unBufferLen ) { return strncasecmp( pStr1,pStr2, unBufferLen ); }
+#define _strnicmp strnicmp
+
+#define _vsnprintf_s vsnprintf
+
+#define _TRUNCATE ((size_t)-1)
+
+#endif
+
+#if defined( OSX )
+// behaviors ensure NULL-termination at least as well as _TRUNCATE does, but
+// wcsncpy_s/strncpy_s can non-NULL-terminate, wcslcpy/strlcpy can not.
+inline errno_t wcsncpy_s(wchar_t *strDest, size_t numberOfElements, const wchar_t *strSource, size_t count)
+{
+ return wcslcpy(strDest, strSource, numberOfElements);
+}
+
+inline errno_t strncpy_s(char *strDest, size_t numberOfElements, const char *strSource, size_t count)
+{
+ return strlcpy(strDest, strSource, numberOfElements);
+}
+
+#endif
+
+#if defined( LINUX )
+// this implementation does not return whether or not the destination was
+// truncated, but that is straightforward to fix if anybody actually needs the
+// return code.
+#include "string.h"
+inline void wcsncpy_s(wchar_t *strDest, size_t numberOfElements, const wchar_t *strSource, size_t count)
+{
+ wcsncpy(strDest, strSource, numberOfElements);
+ strDest[numberOfElements-1] = '\0';
+}
+
+inline void strncpy_s(char *strDest, size_t numberOfElements, const char *strSource, size_t count)
+{
+ strncpy(strDest, strSource, numberOfElements);
+ strDest[numberOfElements-1] = '\0';
+}
+
+#endif
+
+#if defined( _WIN32 ) && _MSC_VER < 1800
+inline uint64_t strtoull(const char *str, char **endptr, int base) { return _strtoui64( str, endptr, base ); }
+#endif
+
+/* Handles copying a std::string into a buffer as would be provided in an API */
+uint32_t ReturnStdString( const std::string & sValue, char *pchBuffer, uint32_t unBufferLen );
+
+/* Handles copying a buffer into an std::string and auto adds null terminator */
+void BufferToStdString( std::string & sDest, const char *pchBuffer, uint32_t unBufferLen );
+
+/** Returns a std::string from a uint64_t */
+std::string Uint64ToString( uint64_t ulValue );
+
+/** returns a uint64_t from a string */
+uint64_t StringToUint64( const std::string & sValue );
+
+//-----------------------------------------------------------------------------
+// Purpose: Encodes a string (or binary data) from URL encoding format, see rfc1738 section 2.2.
+// This version of the call isn't a strict RFC implementation, but uses + for space as is
+// the standard in HTML form encoding, despite it not being part of the RFC.
+//
+// Dest buffer should be at least as large as source buffer to guarantee room for decode.
+//-----------------------------------------------------------------------------
+void V_URLEncode( char *pchDest, int nDestLen, const char *pchSource, int nSourceLen );
+
+//-----------------------------------------------------------------------------
+// Purpose: Decodes a string (or binary data) from URL encoding format, see rfc1738 section 2.2.
+// This version of the call isn't a strict RFC implementation, but uses + for space as is
+// the standard in HTML form encoding, despite it not being part of the RFC.
+//
+// Dest buffer should be at least as large as source buffer to guarantee room for decode.
+// Dest buffer being the same as the source buffer (decode in-place) is explicitly allowed.
+//-----------------------------------------------------------------------------
+size_t V_URLDecode( char *pchDecodeDest, int nDecodeDestLen, const char *pchEncodedSource, int nEncodedSourceLen );
+
+//-----------------------------------------------------------------------------
+// Purpose: strip extension from a path
+//-----------------------------------------------------------------------------
+void V_StripExtension( std::string &in );
+
+
diff --git a/src/vrcommon/strtools_public.cpp b/src/vrcommon/strtools_public.cpp
new file mode 100644
index 0000000..6166db4
--- /dev/null
+++ b/src/vrcommon/strtools_public.cpp
@@ -0,0 +1,437 @@
+//========= Copyright Valve Corporation ============//
+#include "strtools.h"
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+//-----------------------------------------------------------------------------
+// Purpose:
+//-----------------------------------------------------------------------------
+bool StringHasPrefix( const std::string & sString, const std::string & sPrefix )
+{
+ return 0 == strnicmp( sString.c_str(), sPrefix.c_str(), sPrefix.length() );
+}
+
+bool StringHasPrefixCaseSensitive( const std::string & sString, const std::string & sPrefix )
+{
+ return 0 == strncmp( sString.c_str(), sPrefix.c_str(), sPrefix.length() );
+}
+
+
+bool StringHasSuffix( const std::string &sString, const std::string &sSuffix )
+{
+ size_t cStrLen = sString.length();
+ size_t cSuffixLen = sSuffix.length();
+
+ if ( cSuffixLen > cStrLen )
+ return false;
+
+ std::string sStringSuffix = sString.substr( cStrLen - cSuffixLen, cSuffixLen );
+
+ return 0 == stricmp( sStringSuffix.c_str(), sSuffix.c_str() );
+}
+
+bool StringHasSuffixCaseSensitive( const std::string &sString, const std::string &sSuffix )
+{
+ size_t cStrLen = sString.length();
+ size_t cSuffixLen = sSuffix.length();
+
+ if ( cSuffixLen > cStrLen )
+ return false;
+
+ std::string sStringSuffix = sString.substr( cStrLen - cSuffixLen, cSuffixLen );
+
+ return 0 == strncmp( sStringSuffix.c_str(), sSuffix.c_str(),cSuffixLen );
+}
+
+//-----------------------------------------------------------------------------
+// Purpose:
+//-----------------------------------------------------------------------------
+std::string UTF16to8(const wchar_t * in)
+{
+ std::string out;
+ unsigned int codepoint = 0;
+ for ( ; in && *in != 0; ++in )
+ {
+ if (*in >= 0xd800 && *in <= 0xdbff)
+ codepoint = ((*in - 0xd800) << 10) + 0x10000;
+ else
+ {
+ if (*in >= 0xdc00 && *in <= 0xdfff)
+ codepoint |= *in - 0xdc00;
+ else
+ codepoint = *in;
+
+ if (codepoint <= 0x7f)
+ out.append(1, static_cast<char>(codepoint));
+ else if (codepoint <= 0x7ff)
+ {
+ out.append(1, static_cast<char>(0xc0 | ((codepoint >> 6) & 0x1f)));
+ out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));
+ }
+ else if (codepoint <= 0xffff)
+ {
+ out.append(1, static_cast<char>(0xe0 | ((codepoint >> 12) & 0x0f)));
+ out.append(1, static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));
+ out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));
+ }
+ else
+ {
+ out.append(1, static_cast<char>(0xf0 | ((codepoint >> 18) & 0x07)));
+ out.append(1, static_cast<char>(0x80 | ((codepoint >> 12) & 0x3f)));
+ out.append(1, static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));
+ out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));
+ }
+ codepoint = 0;
+ }
+ }
+ return out;
+}
+
+std::wstring UTF8to16(const char * in)
+{
+ std::wstring out;
+ unsigned int codepoint = 0;
+ int following = 0;
+ for ( ; in && *in != 0; ++in )
+ {
+ unsigned char ch = *in;
+ if (ch <= 0x7f)
+ {
+ codepoint = ch;
+ following = 0;
+ }
+ else if (ch <= 0xbf)
+ {
+ if (following > 0)
+ {
+ codepoint = (codepoint << 6) | (ch & 0x3f);
+ --following;
+ }
+ }
+ else if (ch <= 0xdf)
+ {
+ codepoint = ch & 0x1f;
+ following = 1;
+ }
+ else if (ch <= 0xef)
+ {
+ codepoint = ch & 0x0f;
+ following = 2;
+ }
+ else
+ {
+ codepoint = ch & 0x07;
+ following = 3;
+ }
+ if (following == 0)
+ {
+ if (codepoint > 0xffff)
+ {
+ out.append(1, static_cast<wchar_t>(0xd800 + (codepoint >> 10)));
+ out.append(1, static_cast<wchar_t>(0xdc00 + (codepoint & 0x03ff)));
+ }
+ else
+ out.append(1, static_cast<wchar_t>(codepoint));
+ codepoint = 0;
+ }
+ }
+ return out;
+}
+
+
+void strcpy_safe( char *pchBuffer, size_t unBufferSizeBytes, const char *pchSource )
+{
+ pchBuffer[ unBufferSizeBytes - 1 ] = '\0';
+ strncpy( pchBuffer, pchSource, unBufferSizeBytes - 1 );
+}
+
+
+// --------------------------------------------------------------------
+// Purpose: converts a string to upper case
+// --------------------------------------------------------------------
+std::string StringToUpper( const std::string & sString )
+{
+ std::string sOut;
+ sOut.reserve( sString.size() + 1 );
+ for( std::string::const_iterator i = sString.begin(); i != sString.end(); i++ )
+ {
+ sOut.push_back( (char)toupper( *i ) );
+ }
+
+ return sOut;
+}
+
+
+// --------------------------------------------------------------------
+// Purpose: converts a string to lower case
+// --------------------------------------------------------------------
+std::string StringToLower( const std::string & sString )
+{
+ std::string sOut;
+ sOut.reserve( sString.size() + 1 );
+ for( std::string::const_iterator i = sString.begin(); i != sString.end(); i++ )
+ {
+ sOut.push_back( (char)tolower( *i ) );
+ }
+
+ return sOut;
+}
+
+
+uint32_t ReturnStdString( const std::string & sValue, char *pchBuffer, uint32_t unBufferLen )
+{
+ uint32_t unLen = (uint32_t)sValue.length() + 1;
+ if( !pchBuffer || !unBufferLen )
+ return unLen;
+
+ if( unBufferLen < unLen )
+ {
+ pchBuffer[0] = '\0';
+ }
+ else
+ {
+ memcpy( pchBuffer, sValue.c_str(), unLen );
+ }
+
+ return unLen;
+}
+
+void BufferToStdString( std::string & sDest, const char *pchBuffer, uint32_t unBufferLen )
+{
+ sDest.resize( unBufferLen + 1 );
+ memcpy( const_cast< char* >( sDest.c_str() ), pchBuffer, unBufferLen );
+ const_cast< char* >( sDest.c_str() )[ unBufferLen ] = '\0';
+}
+
+/** Returns a std::string from a uint64_t */
+std::string Uint64ToString( uint64_t ulValue )
+{
+ char buf[ 22 ];
+#if defined( _WIN32 )
+ sprintf_s( buf, "%llu", ulValue );
+#else
+ snprintf( buf, sizeof( buf ), "%llu", (long long unsigned int ) ulValue );
+#endif
+ return buf;
+}
+
+
+/** returns a uint64_t from a string */
+uint64_t StringToUint64( const std::string & sValue )
+{
+ return strtoull( sValue.c_str(), NULL, 0 );
+}
+
+//-----------------------------------------------------------------------------
+// Purpose: Helper for converting a numeric value to a hex digit, value should be 0-15.
+//-----------------------------------------------------------------------------
+char cIntToHexDigit( int nValue )
+{
+ //Assert( nValue >= 0 && nValue <= 15 );
+ return "0123456789ABCDEF"[ nValue & 15 ];
+}
+
+//-----------------------------------------------------------------------------
+// Purpose: Helper for converting a hex char value to numeric, return -1 if the char
+// is not a valid hex digit.
+//-----------------------------------------------------------------------------
+int iHexCharToInt( char cValue )
+{
+ int32_t iValue = cValue;
+ if ( (uint32_t)( iValue - '0' ) < 10 )
+ return iValue - '0';
+
+ iValue |= 0x20;
+ if ( (uint32_t)( iValue - 'a' ) < 6 )
+ return iValue - 'a' + 10;
+
+ return -1;
+}
+
+//-----------------------------------------------------------------------------
+// Purpose: Internal implementation of encode, works in the strict RFC manner, or
+// with spaces turned to + like HTML form encoding.
+//-----------------------------------------------------------------------------
+void V_URLEncodeInternal( char *pchDest, int nDestLen, const char *pchSource, int nSourceLen, bool bUsePlusForSpace )
+{
+ //AssertMsg( nDestLen > 3*nSourceLen, "Target buffer for V_URLEncode should be 3x source length, plus one for terminating null\n" );
+
+ int iDestPos = 0;
+ for ( int i=0; i < nSourceLen; ++i )
+ {
+ // worst case we need 3 additional chars
+ if( (iDestPos+3) > nDestLen )
+ {
+ pchDest[0] = '\0';
+// AssertMsg( false, "Target buffer too short\n" );
+ return;
+ }
+
+ // We allow only a-z, A-Z, 0-9, period, underscore, and hyphen to pass through unescaped.
+ // These are the characters allowed by both the original RFC 1738 and the latest RFC 3986.
+ // Current specs also allow '~', but that is forbidden under original RFC 1738.
+ if ( !( pchSource[i] >= 'a' && pchSource[i] <= 'z' ) && !( pchSource[i] >= 'A' && pchSource[i] <= 'Z' ) && !(pchSource[i] >= '0' && pchSource[i] <= '9' )
+ && pchSource[i] != '-' && pchSource[i] != '_' && pchSource[i] != '.'
+ )
+ {
+ if ( bUsePlusForSpace && pchSource[i] == ' ' )
+ {
+ pchDest[iDestPos++] = '+';
+ }
+ else
+ {
+ pchDest[iDestPos++] = '%';
+ uint8_t iValue = pchSource[i];
+ if ( iValue == 0 )
+ {
+ pchDest[iDestPos++] = '0';
+ pchDest[iDestPos++] = '0';
+ }
+ else
+ {
+ char cHexDigit1 = cIntToHexDigit( iValue % 16 );
+ iValue /= 16;
+ char cHexDigit2 = cIntToHexDigit( iValue );
+ pchDest[iDestPos++] = cHexDigit2;
+ pchDest[iDestPos++] = cHexDigit1;
+ }
+ }
+ }
+ else
+ {
+ pchDest[iDestPos++] = pchSource[i];
+ }
+ }
+
+ if( (iDestPos+1) > nDestLen )
+ {
+ pchDest[0] = '\0';
+ //AssertMsg( false, "Target buffer too short to terminate\n" );
+ return;
+ }
+
+ // Null terminate
+ pchDest[iDestPos++] = 0;
+}
+
+
+//-----------------------------------------------------------------------------
+// Purpose: Internal implementation of decode, works in the strict RFC manner, or
+// with spaces turned to + like HTML form encoding.
+//
+// Returns the amount of space used in the output buffer.
+//-----------------------------------------------------------------------------
+size_t V_URLDecodeInternal( char *pchDecodeDest, int nDecodeDestLen, const char *pchEncodedSource, int nEncodedSourceLen, bool bUsePlusForSpace )
+{
+ if ( nDecodeDestLen < nEncodedSourceLen )
+ {
+ //AssertMsg( false, "V_URLDecode needs a dest buffer at least as large as the source" );
+ return 0;
+ }
+
+ int iDestPos = 0;
+ for( int i=0; i < nEncodedSourceLen; ++i )
+ {
+ if ( bUsePlusForSpace && pchEncodedSource[i] == '+' )
+ {
+ pchDecodeDest[ iDestPos++ ] = ' ';
+ }
+ else if ( pchEncodedSource[i] == '%' )
+ {
+ // Percent signifies an encoded value, look ahead for the hex code, convert to numeric, and use that
+
+ // First make sure we have 2 more chars
+ if ( i < nEncodedSourceLen - 2 )
+ {
+ char cHexDigit1 = pchEncodedSource[i+1];
+ char cHexDigit2 = pchEncodedSource[i+2];
+
+ // Turn the chars into a hex value, if they are not valid, then we'll
+ // just place the % and the following two chars direct into the string,
+ // even though this really shouldn't happen, who knows what bad clients
+ // may do with encoding.
+ bool bValid = false;
+ int iValue = iHexCharToInt( cHexDigit1 );
+ if ( iValue != -1 )
+ {
+ iValue *= 16;
+ int iValue2 = iHexCharToInt( cHexDigit2 );
+ if ( iValue2 != -1 )
+ {
+ iValue += iValue2;
+ pchDecodeDest[ iDestPos++ ] = (char)iValue;
+ bValid = true;
+ }
+ }
+
+ if ( !bValid )
+ {
+ pchDecodeDest[ iDestPos++ ] = '%';
+ pchDecodeDest[ iDestPos++ ] = cHexDigit1;
+ pchDecodeDest[ iDestPos++ ] = cHexDigit2;
+ }
+ }
+
+ // Skip ahead
+ i += 2;
+ }
+ else
+ {
+ pchDecodeDest[ iDestPos++ ] = pchEncodedSource[i];
+ }
+ }
+
+ // We may not have extra room to NULL terminate, since this can be used on raw data, but if we do
+ // go ahead and do it as this can avoid bugs.
+ if ( iDestPos < nDecodeDestLen )
+ {
+ pchDecodeDest[iDestPos] = 0;
+ }
+
+ return (size_t)iDestPos;
+}
+
+//-----------------------------------------------------------------------------
+// Purpose: Encodes a string (or binary data) from URL encoding format, see rfc1738 section 2.2.
+// This version of the call isn't a strict RFC implementation, but uses + for space as is
+// the standard in HTML form encoding, despite it not being part of the RFC.
+//
+// Dest buffer should be at least as large as source buffer to guarantee room for decode.
+//-----------------------------------------------------------------------------
+void V_URLEncode( char *pchDest, int nDestLen, const char *pchSource, int nSourceLen )
+{
+ return V_URLEncodeInternal( pchDest, nDestLen, pchSource, nSourceLen, true );
+}
+
+
+//-----------------------------------------------------------------------------
+// Purpose: Decodes a string (or binary data) from URL encoding format, see rfc1738 section 2.2.
+// This version of the call isn't a strict RFC implementation, but uses + for space as is
+// the standard in HTML form encoding, despite it not being part of the RFC.
+//
+// Dest buffer should be at least as large as source buffer to guarantee room for decode.
+// Dest buffer being the same as the source buffer (decode in-place) is explicitly allowed.
+//-----------------------------------------------------------------------------
+size_t V_URLDecode( char *pchDecodeDest, int nDecodeDestLen, const char *pchEncodedSource, int nEncodedSourceLen )
+{
+ return V_URLDecodeInternal( pchDecodeDest, nDecodeDestLen, pchEncodedSource, nEncodedSourceLen, true );
+}
+
+//-----------------------------------------------------------------------------
+void V_StripExtension( std::string &in )
+{
+ // Find the last dot. If it's followed by a dot or a slash, then it's part of a
+ // directory specifier like ../../somedir/./blah.
+ std::string::size_type test = in.rfind( '.' );
+ if ( test != std::string::npos )
+ {
+ // This handles things like ".\blah" or "c:\my@email.com\abc\def\geh"
+ // Which would otherwise wind up with "" and "c:\my@email", respectively.
+ if ( in.rfind( '\\' ) < test && in.rfind( '/' ) < test )
+ {
+ in.resize( test );
+ }
+ }
+}
+
diff --git a/src/vrcommon/vrpathregistry.h b/src/vrcommon/vrpathregistry.h
new file mode 100644
index 0000000..80ebeb7
--- /dev/null
+++ b/src/vrcommon/vrpathregistry.h
@@ -0,0 +1,46 @@
+//========= Copyright Valve Corporation ============//
+#pragma once
+
+#include <string>
+#include <vector>
+#include <stdint.h>
+
+static const char *k_pchRuntimeOverrideVar = "VR_OVERRIDE";
+static const char *k_pchConfigOverrideVar = "VR_CONFIG_PATH";
+static const char *k_pchLogOverrideVar = "VR_LOG_PATH";
+
+class CVRPathRegistry
+{
+public:
+ static std::string GetVRPathRegistryFilename();
+ static std::string GetOpenVRConfigPath();
+
+public:
+ CVRPathRegistry();
+
+ /** Returns paths using the path registry and the provided override values. Pass NULL for any paths you don't care about.
+ * Returns false if the path registry could not be read. Valid paths might still be returned based on environment variables. */
+ static bool GetPaths( std::string *psRuntimePath, std::string *psConfigPath, std::string *psLogPath, const char *pchConfigPathOverride, const char *pchLogPathOverride, std::vector<std::string> *pvecExternalDrivers = NULL );
+
+ bool BLoadFromFile();
+ bool BSaveToFile() const;
+
+ bool ToJsonString( std::string &sJsonString );
+
+ // methods to get the current values
+ std::string GetRuntimePath() const;
+ std::string GetConfigPath() const;
+ std::string GetLogPath() const;
+
+
+private:
+ typedef std::vector< std::string > StringVector_t;
+
+ // index 0 is the current setting
+ StringVector_t m_vecRuntimePath;
+ StringVector_t m_vecLogPath;
+ StringVector_t m_vecConfigPath;
+
+ // full list of external drivers
+ StringVector_t m_vecExternalDrivers;
+};
diff --git a/src/vrcommon/vrpathregistry_public.cpp b/src/vrcommon/vrpathregistry_public.cpp
new file mode 100644
index 0000000..5f171fa
--- /dev/null
+++ b/src/vrcommon/vrpathregistry_public.cpp
@@ -0,0 +1,406 @@
+//========= Copyright Valve Corporation ============//
+
+#include "vrpathregistry.h"
+#include "json/json.h"
+#include "pathtools.h"
+#include "envvartools.h"
+#include "strtools.h"
+#include "dirtools.h"
+
+#if defined( WIN32 )
+#include <windows.h>
+#include <Shlobj.h>
+
+#undef GetEnvironmentVariable
+#elif defined OSX
+#include <Foundation/Foundation.h>
+#include <AppKit/AppKit.h>
+#elif defined(LINUX)
+#include <dlfcn.h>
+#include <stdio.h>
+#endif
+
+#include <algorithm>
+
+#ifndef VRLog
+ #if defined( WIN32 )
+ #define VRLog(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)
+ #else
+ #define VRLog(args...) fprintf(stderr, args)
+ #endif
+#endif
+
+/** Returns the root of the directory the system wants us to store user config data in */
+static std::string GetAppSettingsPath()
+{
+#if defined( WIN32 )
+ WCHAR rwchPath[MAX_PATH];
+
+ if( !SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, rwchPath ) ) )
+ {
+ return "";
+ }
+
+ // Convert the path to UTF-8 and store in the output
+ std::string sUserPath = UTF16to8( rwchPath );
+
+ return sUserPath;
+#elif defined( OSX )
+ std::string sSettingsDir;
+ @autoreleasepool {
+ // Search for the path
+ NSArray *paths = NSSearchPathForDirectoriesInDomains( NSApplicationSupportDirectory, NSUserDomainMask, YES );
+ if ( [paths count] == 0 )
+ {
+ return "";
+ }
+
+ NSString *resolvedPath = [paths objectAtIndex:0];
+ resolvedPath = [resolvedPath stringByAppendingPathComponent: @"OpenVR"];
+
+ if ( ![[NSFileManager new] createDirectoryAtPath: resolvedPath withIntermediateDirectories:YES attributes:nil error:nil] )
+ {
+ return "";
+ }
+
+ sSettingsDir.assign( [resolvedPath UTF8String] );
+ }
+ return sSettingsDir;
+#elif defined( LINUX )
+
+ // As defined by XDG Base Directory Specification
+ // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
+
+ const char *pchHome = getenv("XDG_CONFIG_HOME");
+ if ( ( pchHome != NULL) && ( pchHome[0] != '\0' ) )
+ {
+ return pchHome;
+ }
+
+ //
+ // XDG_CONFIG_HOME is not defined, use ~/.config instead
+ //
+ pchHome = getenv( "HOME" );
+ if ( pchHome == NULL )
+ {
+ return "";
+ }
+
+ std::string sUserPath( pchHome );
+ sUserPath = Path_Join( sUserPath, ".config" );
+ return sUserPath;
+#else
+ #warning "Unsupported platform"
+#endif
+}
+
+
+
+// ---------------------------------------------------------------------------
+// Purpose: Constructor
+// ---------------------------------------------------------------------------
+CVRPathRegistry::CVRPathRegistry()
+{
+
+}
+
+// ---------------------------------------------------------------------------
+// Purpose: Computes the registry filename
+// ---------------------------------------------------------------------------
+std::string CVRPathRegistry::GetOpenVRConfigPath()
+{
+ std::string sConfigPath = GetAppSettingsPath();
+ if( sConfigPath.empty() )
+ return "";
+
+#if defined( _WIN32 ) || defined( LINUX )
+ sConfigPath = Path_Join( sConfigPath, "openvr" );
+#elif defined ( OSX )
+ sConfigPath = Path_Join( sConfigPath, ".openvr" );
+#else
+ #warning "Unsupported platform"
+#endif
+ sConfigPath = Path_FixSlashes( sConfigPath );
+ return sConfigPath;
+}
+
+
+
+//-----------------------------------------------------------------------------
+// Purpose:
+//-----------------------------------------------------------------------------
+std::string CVRPathRegistry::GetVRPathRegistryFilename()
+{
+ std::string sPath = GetOpenVRConfigPath();
+ if ( sPath.empty() )
+ return "";
+
+#if defined( _WIN32 )
+ sPath = Path_Join( sPath, "openvrpaths.vrpath" );
+#elif defined ( POSIX )
+ sPath = Path_Join( sPath, "openvrpaths.vrpath" );
+#else
+ #error "Unsupported platform"
+#endif
+ sPath = Path_FixSlashes( sPath );
+ return sPath;
+}
+
+
+// ---------------------------------------------------------------------------
+// Purpose: Converts JSON to a history array
+// ---------------------------------------------------------------------------
+static void ParseStringListFromJson( std::vector< std::string > *pvecHistory, const Json::Value & root, const char *pchArrayName )
+{
+ if( !root.isMember( pchArrayName ) )
+ return;
+
+ const Json::Value & arrayNode = root[ pchArrayName ];
+ if( !arrayNode )
+ {
+ VRLog( "VR Path Registry node %s is not an array\n", pchArrayName );
+ return;
+ }
+
+ pvecHistory->clear();
+ pvecHistory->reserve( arrayNode.size() );
+ for( uint32_t unIndex = 0; unIndex < arrayNode.size(); unIndex++ )
+ {
+ std::string sPath( arrayNode[ unIndex ].asString() );
+ pvecHistory->push_back( sPath );
+ }
+}
+
+
+// ---------------------------------------------------------------------------
+// Purpose: Converts a history array to JSON
+// ---------------------------------------------------------------------------
+static void StringListToJson( const std::vector< std::string > & vecHistory, Json::Value & root, const char *pchArrayName )
+{
+ Json::Value & arrayNode = root[ pchArrayName ];
+ for( auto i = vecHistory.begin(); i != vecHistory.end(); i++ )
+ {
+ arrayNode.append( *i );
+ }
+}
+
+
+//-----------------------------------------------------------------------------
+// Purpose:
+//-----------------------------------------------------------------------------
+bool CVRPathRegistry::ToJsonString( std::string &sJsonString )
+{
+ std::string sRegPath = GetVRPathRegistryFilename();
+ if( sRegPath.empty() )
+ return false;
+
+ std::string sRegistryContents = Path_ReadTextFile( sRegPath );
+ if( sRegistryContents.empty() )
+ return false;
+
+ sJsonString = sRegistryContents;
+
+ return true;
+}
+
+
+// ---------------------------------------------------------------------------
+// Purpose: Loads the config file from its well known location
+// ---------------------------------------------------------------------------
+bool CVRPathRegistry::BLoadFromFile()
+{
+ std::string sRegPath = GetVRPathRegistryFilename();
+ if( sRegPath.empty() )
+ {
+ VRLog( "Unable to determine VR Path Registry filename\n" );
+ return false;
+ }
+
+ std::string sRegistryContents = Path_ReadTextFile( sRegPath );
+ if( sRegistryContents.empty() )
+ {
+ VRLog( "Unable to read VR Path Registry from %s\n", sRegPath.c_str() );
+ return false;
+ }
+
+ Json::Value root;
+ Json::Reader reader;
+
+ if( !reader.parse( sRegistryContents, root ) )
+ {
+ VRLog( "Unable to parse %s: %s\n", sRegPath.c_str(), reader.getFormattedErrorMessages().c_str() );
+ return false;
+ }
+
+ ParseStringListFromJson( &m_vecRuntimePath, root, "runtime" );
+ ParseStringListFromJson( &m_vecConfigPath, root, "config" );
+ ParseStringListFromJson( &m_vecLogPath, root, "log" );
+ if (root.isMember( "external_drivers" ) && root[ "external_drivers" ].isArray() )
+ {
+ ParseStringListFromJson( &m_vecExternalDrivers, root, "external_drivers" );
+ }
+
+ return true;
+}
+
+
+// ---------------------------------------------------------------------------
+// Purpose: Saves the config file to its well known location
+// ---------------------------------------------------------------------------
+bool CVRPathRegistry::BSaveToFile() const
+{
+#if defined( DASHBOARD_BUILD_MODE )
+ return false;
+#else
+ std::string sRegPath = GetVRPathRegistryFilename();
+ if( sRegPath.empty() )
+ return false;
+
+ Json::Value root;
+ StringListToJson( m_vecRuntimePath, root, "runtime" );
+ StringListToJson( m_vecConfigPath, root, "config" );
+ StringListToJson( m_vecLogPath, root, "log" );
+ StringListToJson( m_vecExternalDrivers, root, "external_drivers" );
+
+ Json::StyledWriter writer;
+ std::string sRegistryContents = writer.write( root );
+
+ // make sure the directory we're writing into actually exists
+ std::string sRegDirectory = Path_StripFilename( sRegPath );
+ if( !BCreateDirectoryRecursive( sRegDirectory.c_str() ) )
+ {
+ VRLog( "Unable to create path registry directory %s\n", sRegDirectory.c_str() );
+ return false;
+ }
+
+ if( !Path_WriteStringToTextFile( sRegPath, sRegistryContents.c_str() ) )
+ {
+ VRLog( "Unable to write VR path registry to %s\n", sRegPath.c_str() );
+ return false;
+ }
+
+ return true;
+#endif
+}
+
+
+// ---------------------------------------------------------------------------
+// Purpose: Returns the current runtime path or NULL if no path is configured.
+// ---------------------------------------------------------------------------
+std::string CVRPathRegistry::GetRuntimePath() const
+{
+ if( m_vecRuntimePath.empty() )
+ return "";
+ else
+ return m_vecRuntimePath.front().c_str();
+}
+
+
+// ---------------------------------------------------------------------------
+// Purpose: Returns the current config path or NULL if no path is configured.
+// ---------------------------------------------------------------------------
+std::string CVRPathRegistry::GetConfigPath() const
+{
+ if( m_vecConfigPath.empty() )
+ return "";
+ else
+ return m_vecConfigPath.front().c_str();
+}
+
+
+// ---------------------------------------------------------------------------
+// Purpose: Returns the current log path or NULL if no path is configured.
+// ---------------------------------------------------------------------------
+std::string CVRPathRegistry::GetLogPath() const
+{
+ if( m_vecLogPath.empty() )
+ return "";
+ else
+ return m_vecLogPath.front().c_str();
+}
+
+
+
+// ---------------------------------------------------------------------------
+// Purpose: Returns paths using the path registry and the provided override
+// values. Pass NULL for any paths you don't care about.
+// ---------------------------------------------------------------------------
+bool CVRPathRegistry::GetPaths( std::string *psRuntimePath, std::string *psConfigPath, std::string *psLogPath, const char *pchConfigPathOverride, const char *pchLogPathOverride, std::vector<std::string> *pvecExternalDrivers )
+{
+ CVRPathRegistry pathReg;
+ bool bLoadedRegistry = pathReg.BLoadFromFile();
+ int nCountEnvironmentVariables = 0;
+
+ if( psRuntimePath )
+ {
+ if ( GetEnvironmentVariable( k_pchRuntimeOverrideVar ).length() != 0 )
+ {
+ *psRuntimePath = GetEnvironmentVariable( k_pchRuntimeOverrideVar );
+ nCountEnvironmentVariables++;
+ }
+ else if( !pathReg.GetRuntimePath().empty() )
+ {
+ *psRuntimePath = pathReg.GetRuntimePath();
+ }
+ else
+ {
+ *psRuntimePath = "";
+ }
+ }
+
+ if( psConfigPath )
+ {
+ if ( GetEnvironmentVariable( k_pchConfigOverrideVar ).length() != 0 )
+ {
+ *psConfigPath = GetEnvironmentVariable( k_pchConfigOverrideVar );
+ nCountEnvironmentVariables++;
+ }
+ else if( pchConfigPathOverride )
+ {
+ *psConfigPath = pchConfigPathOverride;
+ }
+ else if( !pathReg.GetConfigPath().empty() )
+ {
+ *psConfigPath = pathReg.GetConfigPath();
+ }
+ else
+ {
+ *psConfigPath = "";
+ }
+ }
+
+ if( psLogPath )
+ {
+ if ( GetEnvironmentVariable( k_pchLogOverrideVar ).length() != 0 )
+ {
+ *psLogPath = GetEnvironmentVariable( k_pchLogOverrideVar );
+ nCountEnvironmentVariables++;
+ }
+ else if( pchLogPathOverride )
+ {
+ *psLogPath = pchLogPathOverride;
+ }
+ else if( !pathReg.GetLogPath().empty() )
+ {
+ *psLogPath = pathReg.GetLogPath();
+ }
+ else
+ {
+ *psLogPath = "";
+ }
+ }
+
+ if ( pvecExternalDrivers )
+ {
+ *pvecExternalDrivers = pathReg.m_vecExternalDrivers;
+ }
+
+ if ( nCountEnvironmentVariables == 3 )
+ {
+ // all three environment variables where set, so we don't need the physical file
+ return true;
+ }
+
+ return bLoadedRegistry;
+}
+
diff --git a/unity_package/Assets/Plugins/openvr_api.cs b/unity_package/Assets/Plugins/openvr_api.cs
index 8fcac88..517e2af 100644
--- a/unity_package/Assets/Plugins/openvr_api.cs
+++ b/unity_package/Assets/Plugins/openvr_api.cs
@@ -31,7 +31,7 @@ public struct IVRSystem
internal _GetProjectionRaw GetProjectionRaw;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
- internal delegate DistortionCoordinates_t _ComputeDistortion(EVREye eEye, float fU, float fV);
+ internal delegate bool _ComputeDistortion(EVREye eEye, float fU, float fV, ref DistortionCoordinates_t pDistortionCoordinates);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _ComputeDistortion ComputeDistortion;
@@ -171,17 +171,17 @@ public struct IVRSystem
internal _GetEventTypeNameFromEnum GetEventTypeNameFromEnum;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
- internal delegate HiddenAreaMesh_t _GetHiddenAreaMesh(EVREye eEye);
+ internal delegate HiddenAreaMesh_t _GetHiddenAreaMesh(EVREye eEye, EHiddenAreaMeshType type);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _GetHiddenAreaMesh GetHiddenAreaMesh;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
- internal delegate bool _GetControllerState(uint unControllerDeviceIndex, ref VRControllerState_t pControllerState);
+ internal delegate bool _GetControllerState(uint unControllerDeviceIndex, ref VRControllerState_t pControllerState, uint unControllerStateSize);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _GetControllerState GetControllerState;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
- internal delegate bool _GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin, uint unControllerDeviceIndex, ref VRControllerState_t pControllerState, ref TrackedDevicePose_t pTrackedDevicePose);
+ internal delegate bool _GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin, uint unControllerDeviceIndex, ref VRControllerState_t pControllerState, uint unControllerStateSize, ref TrackedDevicePose_t pTrackedDevicePose);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _GetControllerStateWithPose GetControllerStateWithPose;
@@ -676,6 +676,11 @@ public struct IVRCompositor
internal _GetFrameTiming GetFrameTiming;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ internal delegate uint _GetFrameTimings(ref Compositor_FrameTiming pTiming, uint nFrames);
+ [MarshalAs(UnmanagedType.FunctionPtr)]
+ internal _GetFrameTimings GetFrameTimings;
+
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate float _GetFrameTimeRemaining();
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _GetFrameTimeRemaining GetFrameTimeRemaining;
@@ -691,11 +696,21 @@ public struct IVRCompositor
internal _FadeToColor FadeToColor;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ internal delegate HmdColor_t _GetCurrentFadeColor(bool bBackground);
+ [MarshalAs(UnmanagedType.FunctionPtr)]
+ internal _GetCurrentFadeColor GetCurrentFadeColor;
+
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void _FadeGrid(float fSeconds, bool bFadeIn);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _FadeGrid FadeGrid;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ internal delegate float _GetCurrentGridAlpha();
+ [MarshalAs(UnmanagedType.FunctionPtr)]
+ internal _GetCurrentGridAlpha GetCurrentGridAlpha;
+
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate EVRCompositorError _SetSkyboxOverride([In, Out] Texture_t[] pTextures, uint unTextureCount);
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _SetSkyboxOverride SetSkyboxOverride;
@@ -1170,6 +1185,11 @@ public struct IVROverlay
[MarshalAs(UnmanagedType.FunctionPtr)]
internal _SetKeyboardPositionForOverlay SetKeyboardPositionForOverlay;
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ internal delegate EVROverlayError _SetOverlayIntersectionMask(ulong ulOverlayHandle, ref VROverlayIntersectionMaskPrimitive_t pMaskPrimitives, uint unNumMaskPrimitives, uint unPrimitiveSize);
+ [MarshalAs(UnmanagedType.FunctionPtr)]
+ internal _SetOverlayIntersectionMask SetOverlayIntersectionMask;
+
}
[StructLayout(LayoutKind.Sequential)]
@@ -1429,9 +1449,9 @@ public class CVRSystem
pfBottom = 0;
FnTable.GetProjectionRaw(eEye,ref pfLeft,ref pfRight,ref pfTop,ref pfBottom);
}
- public DistortionCoordinates_t ComputeDistortion(EVREye eEye,float fU,float fV)
+ public bool ComputeDistortion(EVREye eEye,float fU,float fV,ref DistortionCoordinates_t pDistortionCoordinates)
{
- DistortionCoordinates_t result = FnTable.ComputeDistortion(eEye,fU,fV);
+ bool result = FnTable.ComputeDistortion(eEye,fU,fV,ref pDistortionCoordinates);
return result;
}
public HmdMatrix34_t GetEyeToHeadTransform(EVREye eEye)
@@ -1568,19 +1588,19 @@ public class CVRSystem
IntPtr result = FnTable.GetEventTypeNameFromEnum(eType);
return Marshal.PtrToStringAnsi(result);
}
- public HiddenAreaMesh_t GetHiddenAreaMesh(EVREye eEye)
+ public HiddenAreaMesh_t GetHiddenAreaMesh(EVREye eEye,EHiddenAreaMeshType type)
{
- HiddenAreaMesh_t result = FnTable.GetHiddenAreaMesh(eEye);
+ HiddenAreaMesh_t result = FnTable.GetHiddenAreaMesh(eEye,type);
return result;
}
- public bool GetControllerState(uint unControllerDeviceIndex,ref VRControllerState_t pControllerState)
+ public bool GetControllerState(uint unControllerDeviceIndex,ref VRControllerState_t pControllerState,uint unControllerStateSize)
{
- bool result = FnTable.GetControllerState(unControllerDeviceIndex,ref pControllerState);
+ bool result = FnTable.GetControllerState(unControllerDeviceIndex,ref pControllerState,unControllerStateSize);
return result;
}
- public bool GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin,uint unControllerDeviceIndex,ref VRControllerState_t pControllerState,ref TrackedDevicePose_t pTrackedDevicePose)
+ public bool GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin,uint unControllerDeviceIndex,ref VRControllerState_t pControllerState,uint unControllerStateSize,ref TrackedDevicePose_t pTrackedDevicePose)
{
- bool result = FnTable.GetControllerStateWithPose(eOrigin,unControllerDeviceIndex,ref pControllerState,ref pTrackedDevicePose);
+ bool result = FnTable.GetControllerStateWithPose(eOrigin,unControllerDeviceIndex,ref pControllerState,unControllerStateSize,ref pTrackedDevicePose);
return result;
}
public void TriggerHapticPulse(uint unControllerDeviceIndex,uint unAxisId,char usDurationMicroSec)
@@ -2117,6 +2137,11 @@ public class CVRCompositor
bool result = FnTable.GetFrameTiming(ref pTiming,unFramesAgo);
return result;
}
+ public uint GetFrameTimings(ref Compositor_FrameTiming pTiming,uint nFrames)
+ {
+ uint result = FnTable.GetFrameTimings(ref pTiming,nFrames);
+ return result;
+ }
public float GetFrameTimeRemaining()
{
float result = FnTable.GetFrameTimeRemaining();
@@ -2130,10 +2155,20 @@ public class CVRCompositor
{
FnTable.FadeToColor(fSeconds,fRed,fGreen,fBlue,fAlpha,bBackground);
}
+ public HmdColor_t GetCurrentFadeColor(bool bBackground)
+ {
+ HmdColor_t result = FnTable.GetCurrentFadeColor(bBackground);
+ return result;
+ }
public void FadeGrid(float fSeconds,bool bFadeIn)
{
FnTable.FadeGrid(fSeconds,bFadeIn);
}
+ public float GetCurrentGridAlpha()
+ {
+ float result = FnTable.GetCurrentGridAlpha();
+ return result;
+ }
public EVRCompositorError SetSkyboxOverride(Texture_t [] pTextures)
{
EVRCompositorError result = FnTable.SetSkyboxOverride(pTextures,(uint) pTextures.Length);
@@ -2623,6 +2658,11 @@ public class CVROverlay
{
FnTable.SetKeyboardPositionForOverlay(ulOverlayHandle,avoidRect);
}
+ public EVROverlayError SetOverlayIntersectionMask(ulong ulOverlayHandle,ref VROverlayIntersectionMaskPrimitive_t pMaskPrimitives,uint unNumMaskPrimitives,uint unPrimitiveSize)
+ {
+ EVROverlayError result = FnTable.SetOverlayIntersectionMask(ulOverlayHandle,ref pMaskPrimitives,unNumMaskPrimitives,unPrimitiveSize);
+ return result;
+ }
}
@@ -2876,21 +2916,21 @@ public class CVRResources
public class OpenVRInterop
{
- [DllImportAttribute("openvr_api", EntryPoint = "VR_InitInternal")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_InitInternal", CallingConvention = CallingConvention.Cdecl)]
internal static extern uint InitInternal(ref EVRInitError peError, EVRApplicationType eApplicationType);
- [DllImportAttribute("openvr_api", EntryPoint = "VR_ShutdownInternal")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_ShutdownInternal", CallingConvention = CallingConvention.Cdecl)]
internal static extern void ShutdownInternal();
- [DllImportAttribute("openvr_api", EntryPoint = "VR_IsHmdPresent")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_IsHmdPresent", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool IsHmdPresent();
- [DllImportAttribute("openvr_api", EntryPoint = "VR_IsRuntimeInstalled")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_IsRuntimeInstalled", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool IsRuntimeInstalled();
- [DllImportAttribute("openvr_api", EntryPoint = "VR_GetStringForHmdError")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_GetStringForHmdError", CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr GetStringForHmdError(EVRInitError error);
- [DllImportAttribute("openvr_api", EntryPoint = "VR_GetGenericInterface")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_GetGenericInterface", CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr GetGenericInterface([In, MarshalAs(UnmanagedType.LPStr)] string pchInterfaceVersion, ref EVRInitError peError);
- [DllImportAttribute("openvr_api", EntryPoint = "VR_IsInterfaceVersionValid")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_IsInterfaceVersionValid", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool IsInterfaceVersionValid([In, MarshalAs(UnmanagedType.LPStr)] string pchInterfaceVersion);
- [DllImportAttribute("openvr_api", EntryPoint = "VR_GetInitToken")]
+ [DllImportAttribute("openvr_api", EntryPoint = "VR_GetInitToken", CallingConvention = CallingConvention.Cdecl)]
internal static extern uint GetInitToken();
}
@@ -2975,6 +3015,7 @@ public enum ETrackedDeviceProperty
Prop_HasCamera_Bool = 1030,
Prop_DriverVersion_String = 1031,
Prop_Firmware_ForceUpdateRequired_Bool = 1032,
+ Prop_ViveSystemButtonFixRequired_Bool = 1033,
Prop_ReportsTimeSinceVSync_Bool = 2000,
Prop_SecondsFromVsyncToPhotons_Float = 2001,
Prop_DisplayFrequency_Float = 2002,
@@ -3012,6 +3053,7 @@ public enum ETrackedDeviceProperty
Prop_ScreenshotHorizontalFieldOfViewDegrees_Float = 2034,
Prop_ScreenshotVerticalFieldOfViewDegrees_Float = 2035,
Prop_DisplaySuppressed_Bool = 2036,
+ Prop_DisplayAllowNightMode_Bool = 2037,
Prop_AttachedDeviceId_String = 3000,
Prop_SupportedButtons_Uint64 = 3001,
Prop_Axis0Type_Int32 = 3002,
@@ -3214,6 +3256,12 @@ public enum EVRMouseButton
Right = 2,
Middle = 4,
}
+public enum EHiddenAreaMeshType
+{
+ k_eHiddenAreaMesh_Standard = 0,
+ k_eHiddenAreaMesh_Inverse = 1,
+ k_eHiddenAreaMesh_LineLoop = 2,
+}
public enum EVRControllerAxisType
{
k_eControllerAxis_None = 0,
@@ -3256,6 +3304,8 @@ public enum EVROverlayError
UnableToLoadFile = 25,
KeyboardAlreadyInUse = 26,
NoNeighbor = 27,
+ TooManyMaskPrimitives = 29,
+ BadMaskPrimitive = 30,
}
public enum EVRApplicationType
{
@@ -3483,6 +3533,7 @@ public enum EVRCompositorError
TextureUsesUnsupportedFormat = 105,
SharedTexturesNotSupported = 106,
IndexOutOfRange = 107,
+ AlreadySubmitted = 108,
}
public enum VROverlayInputMethod
{
@@ -3533,6 +3584,11 @@ public enum EOverlayDirection
Right = 3,
Count = 4,
}
+public enum EVROverlayIntersectionMaskPrimitiveType
+{
+ OverlayIntersectionPrimitiveType_Rectangle = 0,
+ OverlayIntersectionPrimitiveType_Circle = 1,
+}
public enum EVRRenderModelError
{
None = 0,
@@ -3609,6 +3665,13 @@ public enum EVRScreenshotError
[FieldOffset(0)] public VREvent_Keyboard_t keyboard; // This has to be at the end due to a mono bug
}
+
+[StructLayout(LayoutKind.Explicit)] public struct VROverlayIntersectionMaskPrimitive_Data_t
+{
+ [FieldOffset(0)] public IntersectionMaskRectangle_t m_Rectangle;
+ [FieldOffset(0)] public IntersectionMaskCircle_t m_Circle;
+}
+
[StructLayout(LayoutKind.Sequential)] public struct HmdMatrix34_t
{
public float m0; //float[3][4]
@@ -3898,6 +3961,7 @@ public enum EVRScreenshotError
public uint m_nSize;
public uint m_nFrameIndex;
public uint m_nNumFramePresents;
+ public uint m_nNumMisPresented;
public uint m_nNumDroppedFrames;
public uint m_nReprojectionFlags;
public double m_flSystemTimeInSeconds;
@@ -3950,6 +4014,24 @@ public enum EVRScreenshotError
public HmdVector2_t vUVs;
public float fDistance;
}
+[StructLayout(LayoutKind.Sequential)] public struct IntersectionMaskRectangle_t
+{
+ public float m_flTopLeftX;
+ public float m_flTopLeftY;
+ public float m_flWidth;
+ public float m_flHeight;
+}
+[StructLayout(LayoutKind.Sequential)] public struct IntersectionMaskCircle_t
+{
+ public float m_flCenterX;
+ public float m_flCenterY;
+ public float m_flRadius;
+}
+[StructLayout(LayoutKind.Sequential)] public struct VROverlayIntersectionMaskPrimitive_t
+{
+ public EVROverlayIntersectionMaskPrimitiveType m_nPrimitiveType;
+ public VROverlayIntersectionMaskPrimitive_Data_t m_Primitive;
+}
[StructLayout(LayoutKind.Sequential)] public struct RenderModel_ComponentState_t
{
public HmdMatrix34_t mTrackingToComponentRenderModel;
@@ -4048,7 +4130,6 @@ public class OpenVR
return OpenVRInterop.GetInitToken();
}
- public const uint k_unTrackingStringSize = 32;
public const uint k_unMaxDriverDebugResponseSize = 32768;
public const uint k_unTrackedDeviceIndex_Hmd = 0;
public const uint k_unMaxTrackedDeviceCount = 16;
@@ -4058,7 +4139,7 @@ public class OpenVR
public const uint k_unControllerStateAxisCount = 5;
public const ulong k_ulOverlayHandleInvalid = 0;
public const uint k_unScreenshotHandleInvalid = 0;
- public const string IVRSystem_Version = "IVRSystem_012";
+ public const string IVRSystem_Version = "IVRSystem_014";
public const string IVRExtendedDisplay_Version = "IVRExtendedDisplay_001";
public const string IVRTrackedCamera_Version = "IVRTrackedCamera_003";
public const uint k_unMaxApplicationKeyLength = 128;
@@ -4067,10 +4148,11 @@ public class OpenVR
public const string IVRApplications_Version = "IVRApplications_006";
public const string IVRChaperone_Version = "IVRChaperone_003";
public const string IVRChaperoneSetup_Version = "IVRChaperoneSetup_005";
- public const string IVRCompositor_Version = "IVRCompositor_016";
+ public const string IVRCompositor_Version = "IVRCompositor_018";
public const uint k_unVROverlayMaxKeyLength = 128;
public const uint k_unVROverlayMaxNameLength = 128;
public const uint k_unMaxOverlayCount = 64;
+ public const uint k_unMaxOverlayIntersectionMaskPrimitivesCount = 32;
public const string IVROverlay_Version = "IVROverlay_013";
public const string k_pch_Controller_Component_GDC2015 = "gdc2015";
public const string k_pch_Controller_Component_Base = "base";
@@ -4095,9 +4177,9 @@ public class OpenVR
public const string k_pch_SteamVR_LogLevel_Int32 = "loglevel";
public const string k_pch_SteamVR_IPD_Float = "ipd";
public const string k_pch_SteamVR_Background_String = "background";
+ public const string k_pch_SteamVR_BackgroundUseDomeProjection_Bool = "backgroundUseDomeProjection";
public const string k_pch_SteamVR_BackgroundCameraHeight_Float = "backgroundCameraHeight";
public const string k_pch_SteamVR_BackgroundDomeRadius_Float = "backgroundDomeRadius";
- public const string k_pch_SteamVR_Environment_String = "environment";
public const string k_pch_SteamVR_GridColor_String = "gridColor";
public const string k_pch_SteamVR_PlayAreaColor_String = "playAreaColor";
public const string k_pch_SteamVR_ShowStage_Bool = "showStage";
@@ -4110,7 +4192,8 @@ public class OpenVR
public const string k_pch_SteamVR_BaseStationPowerManagement_Bool = "basestationPowerManagement";
public const string k_pch_SteamVR_NeverKillProcesses_Bool = "neverKillProcesses";
public const string k_pch_SteamVR_RenderTargetMultiplier_Float = "renderTargetMultiplier";
- public const string k_pch_SteamVR_AllowReprojection_Bool = "allowReprojection";
+ public const string k_pch_SteamVR_AllowAsyncReprojection_Bool = "allowAsyncReprojection";
+ public const string k_pch_SteamVR_AllowReprojection_Bool = "allowInterleavedReprojection";
public const string k_pch_SteamVR_ForceReprojection_Bool = "forceReprojection";
public const string k_pch_SteamVR_ForceFadeOnBadTracking_Bool = "forceFadeOnBadTracking";
public const string k_pch_SteamVR_DefaultMirrorView_Int32 = "defaultMirrorView";
@@ -4121,6 +4204,7 @@ public class OpenVR
public const string k_pch_SteamVR_SetInitialDefaultHomeApp = "setInitialDefaultHomeApp";
public const string k_pch_SteamVR_CycleBackgroundImageTimeSec_Int32 = "CycleBackgroundImageTimeSec";
public const string k_pch_SteamVR_RetailDemo_Bool = "retailDemo";
+ public const string k_pch_SteamVR_IpdOffset_Float = "ipdOffset";
public const string k_pch_Lighthouse_Section = "driver_lighthouse";
public const string k_pch_Lighthouse_DisableIMU_Bool = "disableimu";
public const string k_pch_Lighthouse_UseDisambiguation_String = "usedisambiguation";
@@ -4141,6 +4225,7 @@ public class OpenVR
public const string k_pch_Null_DisplayFrequency_Float = "displayFrequency";
public const string k_pch_UserInterface_Section = "userinterface";
public const string k_pch_UserInterface_StatusAlwaysOnTop_Bool = "StatusAlwaysOnTop";
+ public const string k_pch_UserInterface_MinimizeToTray_Bool = "MinimizeToTray";
public const string k_pch_UserInterface_Screenshots_Bool = "screenshots";
public const string k_pch_UserInterface_ScreenshotType_Int = "screenshotType";
public const string k_pch_Notifications_Section = "notifications";
diff --git a/unity_package/Assets/SteamVR/Extras/SteamVR_TrackedController.cs b/unity_package/Assets/SteamVR/Extras/SteamVR_TrackedController.cs
index 32e9f5a..5556bbe 100644
--- a/unity_package/Assets/SteamVR/Extras/SteamVR_TrackedController.cs
+++ b/unity_package/Assets/SteamVR/Extras/SteamVR_TrackedController.cs
@@ -131,7 +131,7 @@ public class SteamVR_TrackedController : MonoBehaviour
void Update()
{
var system = OpenVR.System;
- if (system != null && system.GetControllerState(controllerIndex, ref controllerState))
+ if (system != null && system.GetControllerState(controllerIndex, ref controllerState, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t))))
{
ulong trigger = controllerState.ulButtonPressed & (1UL << ((int)EVRButtonId.k_EButton_SteamVR_Trigger));
if (trigger > 0L && !triggerPressed)
diff --git a/unity_package/Assets/SteamVR/Scripts/SteamVR_CameraMask.cs b/unity_package/Assets/SteamVR/Scripts/SteamVR_CameraMask.cs
index 654f70a..3a527ad 100644
--- a/unity_package/Assets/SteamVR/Scripts/SteamVR_CameraMask.cs
+++ b/unity_package/Assets/SteamVR/Scripts/SteamVR_CameraMask.cs
@@ -5,8 +5,8 @@
//=============================================================================
using UnityEngine;
-using System.Collections;
using UnityEngine.Rendering;
+using Valve.VR;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class SteamVR_CameraMask : MonoBehaviour
@@ -39,7 +39,7 @@ public class SteamVR_CameraMask : MonoBehaviour
{
int i = (int)eye;
if (hiddenAreaMeshes[i] == null)
- hiddenAreaMeshes[i] = SteamVR_Utils.CreateHiddenAreaMesh(vr.hmd.GetHiddenAreaMesh(eye), vr.textureBounds[i]);
+ hiddenAreaMeshes[i] = SteamVR_Utils.CreateHiddenAreaMesh(vr.hmd.GetHiddenAreaMesh(eye, EHiddenAreaMeshType.k_eHiddenAreaMesh_Standard), vr.textureBounds[i]);
meshFilter.mesh = hiddenAreaMeshes[i];
}
diff --git a/unity_package/Assets/SteamVR/Scripts/SteamVR_Controller.cs b/unity_package/Assets/SteamVR/Scripts/SteamVR_Controller.cs
index 219da8a..bfaef94 100644
--- a/unity_package/Assets/SteamVR/Scripts/SteamVR_Controller.cs
+++ b/unity_package/Assets/SteamVR/Scripts/SteamVR_Controller.cs
@@ -65,7 +65,7 @@ public class SteamVR_Controller
var system = OpenVR.System;
if (system != null)
{
- valid = system.GetControllerStateWithPose(SteamVR_Render.instance.trackingSpace, index, ref state, ref pose);
+ valid = system.GetControllerStateWithPose(SteamVR_Render.instance.trackingSpace, index, ref state, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t)), ref pose);
UpdateHairTrigger();
}
}