vkjson: initial commit
authorAntoine Labour <piman@chromium.org>
Tue, 27 Oct 2015 19:21:09 +0000 (12:21 -0700)
committerJon Ashburn <jon@lunarg.com>
Wed, 20 Jan 2016 22:36:25 +0000 (15:36 -0700)
CMakeLists.txt
libs/vkjson/CMakeLists.txt [new file with mode: 0644]
libs/vkjson/vkjson.cc [new file with mode: 0644]
libs/vkjson/vkjson.h [new file with mode: 0644]
libs/vkjson/vkjson_device.cc [new file with mode: 0644]
libs/vkjson/vkjson_info.cc [new file with mode: 0644]
libs/vkjson/vkjson_unittest.cc [new file with mode: 0644]

index ba76eee..ab8ed7c 100755 (executable)
@@ -74,6 +74,7 @@ option(BUILD_TESTS "Build tests" ON)
 option(BUILD_LAYERS "Build layers" ON)
 option(BUILD_DEMOS "Build demos" ON)
 option(BUILD_VKTRACE "Build VkTrace" ON)
+option(BUILD_VKJSON "Build vkjson" ON)
 
 if (BUILD_ICD OR BUILD_TESTS)
     # Hard code our glslang path for now
@@ -135,3 +136,7 @@ endif()
 if(BUILD_VKTRACE)
     add_subdirectory(vktrace)
 endif()
+
+if(BUILD_VKJSON)
+    add_subdirectory(libs/vkjson)
+endif()
diff --git a/libs/vkjson/CMakeLists.txt b/libs/vkjson/CMakeLists.txt
new file mode 100644 (file)
index 0000000..aec36f5
--- /dev/null
@@ -0,0 +1,43 @@
+# Copyright 2015 Google Inc. All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+#     * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#     * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+#     * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+if (NOT WIN32)
+    set (CMAKE_CXX_FLAGS "-std=c++11")
+endif()
+
+add_library(vkjson STATIC vkjson.cc vkjson_device.cc ../../loader/cJSON.c)
+
+if(UNIX)
+    add_executable(vkjson_unittest vkjson_unittest.cc)
+    add_executable(vkjson_info vkjson_info.cc)
+else()
+    add_executable(vkjson_unittest WIN32 vkjson_unittest.cc)
+    add_executable(vkjson_info WIN32 vkjson_info.cc)
+endif()
+target_link_libraries(vkjson_unittest vkjson)
+target_link_libraries(vkjson_info vkjson vulkan-${MAJOR})
diff --git a/libs/vkjson/vkjson.cc b/libs/vkjson/vkjson.cc
new file mode 100644 (file)
index 0000000..6d204a0
--- /dev/null
@@ -0,0 +1,686 @@
+// Copyright 2015 Google Inc. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include "vkjson.h"
+
+#include <assert.h>
+#include <string.h>
+
+#include <cmath>
+#include <limits>
+#include <memory>
+#include <sstream>
+#include <type_traits>
+#include <utility>
+
+#include "../../loader/cJSON.h"
+
+namespace {
+
+inline bool IsIntegral(double value) {
+  return std::trunc(value) == value;
+}
+
+template <typename T> struct EnumTraits;
+template <> struct EnumTraits<VkPhysicalDeviceType> {
+  static uint32_t min() { return VK_PHYSICAL_DEVICE_TYPE_BEGIN_RANGE; }
+  static uint32_t max() { return VK_PHYSICAL_DEVICE_TYPE_END_RANGE; }
+};
+
+template <> struct EnumTraits<VkFormat> {
+  static uint32_t min() { return VK_FORMAT_BEGIN_RANGE; }
+  static uint32_t max() { return VK_FORMAT_END_RANGE; }
+};
+
+
+// VkSparseImageFormatProperties
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkExtent3D* extents) {
+  return
+    visitor->Visit("width", &extents->width) &&
+    visitor->Visit("height", &extents->height) &&
+    visitor->Visit("depth", &extents->depth);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkImageFormatProperties* properties) {
+  return
+    visitor->Visit("maxExtent", &properties->maxExtent) &&
+    visitor->Visit("maxMipLevels", &properties->maxMipLevels) &&
+    visitor->Visit("maxArrayLayers", &properties->maxArrayLayers) &&
+    visitor->Visit("sampleCounts", &properties->sampleCounts) &&
+    visitor->Visit("maxResourceSize", &properties->maxResourceSize);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkPhysicalDeviceLimits* limits) {
+  return
+    visitor->Visit("maxImageDimension1D", &limits->maxImageDimension1D) &&
+    visitor->Visit("maxImageDimension2D", &limits->maxImageDimension2D) &&
+    visitor->Visit("maxImageDimension3D", &limits->maxImageDimension3D) &&
+    visitor->Visit("maxImageDimensionCube", &limits->maxImageDimensionCube) &&
+    visitor->Visit("maxImageArrayLayers", &limits->maxImageArrayLayers) &&
+    visitor->Visit("maxTexelBufferElements", &limits->maxTexelBufferElements) &&
+    visitor->Visit("maxUniformBufferRange", &limits->maxUniformBufferRange) &&
+    visitor->Visit("maxStorageBufferRange", &limits->maxStorageBufferRange) &&
+    visitor->Visit("maxPushConstantsSize", &limits->maxPushConstantsSize) &&
+    visitor->Visit("maxMemoryAllocationCount", &limits->maxMemoryAllocationCount) &&
+    visitor->Visit("maxSamplerAllocationCount", &limits->maxSamplerAllocationCount) &&
+    visitor->Visit("bufferImageGranularity", &limits->bufferImageGranularity) &&
+    visitor->Visit("sparseAddressSpaceSize", &limits->sparseAddressSpaceSize) &&
+    visitor->Visit("maxBoundDescriptorSets", &limits->maxBoundDescriptorSets) &&
+    visitor->Visit("maxPerStageDescriptorSamplers", &limits->maxPerStageDescriptorSamplers) &&
+    visitor->Visit("maxPerStageDescriptorUniformBuffers", &limits->maxPerStageDescriptorUniformBuffers) &&
+    visitor->Visit("maxPerStageDescriptorStorageBuffers", &limits->maxPerStageDescriptorStorageBuffers) &&
+    visitor->Visit("maxPerStageDescriptorSampledImages", &limits->maxPerStageDescriptorSampledImages) &&
+    visitor->Visit("maxPerStageDescriptorStorageImages", &limits->maxPerStageDescriptorStorageImages) &&
+    visitor->Visit("maxPerStageDescriptorInputAttachments", &limits->maxPerStageDescriptorInputAttachments) &&
+    visitor->Visit("maxPerStageResources", &limits->maxPerStageResources) &&
+    visitor->Visit("maxDescriptorSetSamplers", &limits->maxDescriptorSetSamplers) &&
+    visitor->Visit("maxDescriptorSetUniformBuffers", &limits->maxDescriptorSetUniformBuffers) &&
+    visitor->Visit("maxDescriptorSetUniformBuffersDynamic", &limits->maxDescriptorSetUniformBuffersDynamic) &&
+    visitor->Visit("maxDescriptorSetStorageBuffers", &limits->maxDescriptorSetStorageBuffers) &&
+    visitor->Visit("maxDescriptorSetStorageBuffersDynamic", &limits->maxDescriptorSetStorageBuffersDynamic) &&
+    visitor->Visit("maxDescriptorSetSampledImages", &limits->maxDescriptorSetSampledImages) &&
+    visitor->Visit("maxDescriptorSetStorageImages", &limits->maxDescriptorSetStorageImages) &&
+    visitor->Visit("maxDescriptorSetInputAttachments", &limits->maxDescriptorSetInputAttachments) &&
+    visitor->Visit("maxVertexInputAttributes", &limits->maxVertexInputAttributes) &&
+    visitor->Visit("maxVertexInputBindings", &limits->maxVertexInputBindings) &&
+    visitor->Visit("maxVertexInputAttributeOffset", &limits->maxVertexInputAttributeOffset) &&
+    visitor->Visit("maxVertexInputBindingStride", &limits->maxVertexInputBindingStride) &&
+    visitor->Visit("maxVertexOutputComponents", &limits->maxVertexOutputComponents) &&
+    visitor->Visit("maxTessellationGenerationLevel", &limits->maxTessellationGenerationLevel) &&
+    visitor->Visit("maxTessellationPatchSize", &limits->maxTessellationPatchSize) &&
+    visitor->Visit("maxTessellationControlPerVertexInputComponents", &limits->maxTessellationControlPerVertexInputComponents) &&
+    visitor->Visit("maxTessellationControlPerVertexOutputComponents", &limits->maxTessellationControlPerVertexOutputComponents) &&
+    visitor->Visit("maxTessellationControlPerPatchOutputComponents", &limits->maxTessellationControlPerPatchOutputComponents) &&
+    visitor->Visit("maxTessellationControlTotalOutputComponents", &limits->maxTessellationControlTotalOutputComponents) &&
+    visitor->Visit("maxTessellationEvaluationInputComponents", &limits->maxTessellationEvaluationInputComponents) &&
+    visitor->Visit("maxTessellationEvaluationOutputComponents", &limits->maxTessellationEvaluationOutputComponents) &&
+    visitor->Visit("maxGeometryShaderInvocations", &limits->maxGeometryShaderInvocations) &&
+    visitor->Visit("maxGeometryInputComponents", &limits->maxGeometryInputComponents) &&
+    visitor->Visit("maxGeometryOutputComponents", &limits->maxGeometryOutputComponents) &&
+    visitor->Visit("maxGeometryOutputVertices", &limits->maxGeometryOutputVertices) &&
+    visitor->Visit("maxGeometryTotalOutputComponents", &limits->maxGeometryTotalOutputComponents) &&
+    visitor->Visit("maxFragmentInputComponents", &limits->maxFragmentInputComponents) &&
+    visitor->Visit("maxFragmentOutputAttachments", &limits->maxFragmentOutputAttachments) &&
+    visitor->Visit("maxFragmentDualSrcAttachments", &limits->maxFragmentDualSrcAttachments) &&
+    visitor->Visit("maxFragmentCombinedOutputResources", &limits->maxFragmentCombinedOutputResources) &&
+    visitor->Visit("maxComputeSharedMemorySize", &limits->maxComputeSharedMemorySize) &&
+    visitor->Visit("maxComputeWorkGroupCount", &limits->maxComputeWorkGroupCount) &&
+    visitor->Visit("maxComputeWorkGroupInvocations", &limits->maxComputeWorkGroupInvocations) &&
+    visitor->Visit("maxComputeWorkGroupSize", &limits->maxComputeWorkGroupSize) &&
+    visitor->Visit("subPixelPrecisionBits", &limits->subPixelPrecisionBits) &&
+    visitor->Visit("subTexelPrecisionBits", &limits->subTexelPrecisionBits) &&
+    visitor->Visit("mipmapPrecisionBits", &limits->mipmapPrecisionBits) &&
+    visitor->Visit("maxDrawIndexedIndexValue", &limits->maxDrawIndexedIndexValue) &&
+    visitor->Visit("maxDrawIndirectCount", &limits->maxDrawIndirectCount) &&
+    visitor->Visit("maxSamplerLodBias", &limits->maxSamplerLodBias) &&
+    visitor->Visit("maxSamplerAnisotropy", &limits->maxSamplerAnisotropy) &&
+    visitor->Visit("maxViewports", &limits->maxViewports) &&
+    visitor->Visit("maxViewportDimensions", &limits->maxViewportDimensions) &&
+    visitor->Visit("viewportBoundsRange", &limits->viewportBoundsRange) &&
+    visitor->Visit("viewportSubPixelBits", &limits->viewportSubPixelBits) &&
+    visitor->Visit("minMemoryMapAlignment", &limits->minMemoryMapAlignment) &&
+    visitor->Visit("minTexelBufferOffsetAlignment", &limits->minTexelBufferOffsetAlignment) &&
+    visitor->Visit("minUniformBufferOffsetAlignment", &limits->minUniformBufferOffsetAlignment) &&
+    visitor->Visit("minStorageBufferOffsetAlignment", &limits->minStorageBufferOffsetAlignment) &&
+    visitor->Visit("minTexelOffset", &limits->minTexelOffset) &&
+    visitor->Visit("maxTexelOffset", &limits->maxTexelOffset) &&
+    visitor->Visit("minTexelGatherOffset", &limits->minTexelGatherOffset) &&
+    visitor->Visit("maxTexelGatherOffset", &limits->maxTexelGatherOffset) &&
+    visitor->Visit("minInterpolationOffset", &limits->minInterpolationOffset) &&
+    visitor->Visit("maxInterpolationOffset", &limits->maxInterpolationOffset) &&
+    visitor->Visit("subPixelInterpolationOffsetBits", &limits->subPixelInterpolationOffsetBits) &&
+    visitor->Visit("maxFramebufferWidth", &limits->maxFramebufferWidth) &&
+    visitor->Visit("maxFramebufferHeight", &limits->maxFramebufferHeight) &&
+    visitor->Visit("maxFramebufferLayers", &limits->maxFramebufferLayers) &&
+    visitor->Visit("framebufferColorSampleCounts", &limits->framebufferColorSampleCounts) &&
+    visitor->Visit("framebufferDepthSampleCounts", &limits->framebufferDepthSampleCounts) &&
+    visitor->Visit("framebufferStencilSampleCounts", &limits->framebufferStencilSampleCounts) &&
+    visitor->Visit("framebufferNoAttachmentsSampleCounts", &limits->framebufferNoAttachmentsSampleCounts) &&
+    visitor->Visit("maxColorAttachments", &limits->maxColorAttachments) &&
+    visitor->Visit("sampledImageColorSampleCounts", &limits->sampledImageColorSampleCounts) &&
+    visitor->Visit("sampledImageIntegerSampleCounts", &limits->sampledImageIntegerSampleCounts) &&
+    visitor->Visit("sampledImageDepthSampleCounts", &limits->sampledImageDepthSampleCounts) &&
+    visitor->Visit("sampledImageStencilSampleCounts", &limits->sampledImageStencilSampleCounts) &&
+    visitor->Visit("storageImageSampleCounts", &limits->storageImageSampleCounts) &&
+    visitor->Visit("maxSampleMaskWords", &limits->maxSampleMaskWords) &&
+    visitor->Visit("timestampComputeAndGraphics", &limits->timestampComputeAndGraphics) &&
+    visitor->Visit("timestampPeriod", &limits->timestampPeriod) &&
+    visitor->Visit("maxClipDistances", &limits->maxClipDistances) &&
+    visitor->Visit("maxCullDistances", &limits->maxCullDistances) &&
+    visitor->Visit("maxCombinedClipAndCullDistances", &limits->maxCombinedClipAndCullDistances) &&
+    visitor->Visit("discreteQueuePriorities", &limits->discreteQueuePriorities) &&
+    visitor->Visit("pointSizeRange", &limits->pointSizeRange) &&
+    visitor->Visit("lineWidthRange", &limits->lineWidthRange) &&
+    visitor->Visit("pointSizeGranularity", &limits->pointSizeGranularity) &&
+    visitor->Visit("lineWidthGranularity", &limits->lineWidthGranularity) &&
+    visitor->Visit("strictLines", &limits->strictLines) &&
+    visitor->Visit("standardSampleLocations", &limits->standardSampleLocations) &&
+    visitor->Visit("optimalBufferCopyOffsetAlignment", &limits->optimalBufferCopyOffsetAlignment) &&
+    visitor->Visit("optimalBufferCopyRowPitchAlignment", &limits->optimalBufferCopyRowPitchAlignment) &&
+    visitor->Visit("nonCoherentAtomSize", &limits->nonCoherentAtomSize);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor,
+                    VkPhysicalDeviceSparseProperties* properties) {
+  return
+    visitor->Visit("residencyStandard2DBlockShape", &properties->residencyStandard2DBlockShape) &&
+    visitor->Visit("residencyStandard2DMultisampleBlockShape", &properties->residencyStandard2DMultisampleBlockShape) &&
+    visitor->Visit("residencyStandard3DBlockShape", &properties->residencyStandard3DBlockShape) &&
+    visitor->Visit("residencyAlignedMipSize", &properties->residencyAlignedMipSize) &&
+    visitor->Visit("residencyNonResidentStrict", &properties->residencyNonResidentStrict);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor,
+                    VkPhysicalDeviceProperties* properties) {
+  return
+    visitor->Visit("apiVersion", &properties->apiVersion) &&
+    visitor->Visit("driverVersion", &properties->driverVersion) &&
+    visitor->Visit("vendorID", &properties->vendorID) &&
+    visitor->Visit("deviceID", &properties->deviceID) &&
+    visitor->Visit("deviceType", &properties->deviceType) &&
+    visitor->Visit("deviceName", &properties->deviceName) &&
+    visitor->Visit("pipelineCacheUUID", &properties->pipelineCacheUUID) &&
+    visitor->Visit("limits", &properties->limits) &&
+    visitor->Visit("sparseProperties", &properties->sparseProperties);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkPhysicalDeviceFeatures* features) {
+  return
+    visitor->Visit("robustBufferAccess", &features->robustBufferAccess) &&
+    visitor->Visit("fullDrawIndexUint32", &features->fullDrawIndexUint32) &&
+    visitor->Visit("imageCubeArray", &features->imageCubeArray) &&
+    visitor->Visit("independentBlend", &features->independentBlend) &&
+    visitor->Visit("geometryShader", &features->geometryShader) &&
+    visitor->Visit("tessellationShader", &features->tessellationShader) &&
+    visitor->Visit("sampleRateShading", &features->sampleRateShading) &&
+    visitor->Visit("dualSrcBlend", &features->dualSrcBlend) &&
+    visitor->Visit("logicOp", &features->logicOp) &&
+    visitor->Visit("multiDrawIndirect", &features->multiDrawIndirect) &&
+    visitor->Visit("drawIndirectFirstInstance", &features->drawIndirectFirstInstance) &&
+    visitor->Visit("depthClamp", &features->depthClamp) &&
+    visitor->Visit("depthBiasClamp", &features->depthBiasClamp) &&
+    visitor->Visit("fillModeNonSolid", &features->fillModeNonSolid) &&
+    visitor->Visit("depthBounds", &features->depthBounds) &&
+    visitor->Visit("wideLines", &features->wideLines) &&
+    visitor->Visit("largePoints", &features->largePoints) &&
+    visitor->Visit("alphaToOne", &features->alphaToOne) &&
+    visitor->Visit("multiViewport", &features->multiViewport) &&
+    visitor->Visit("samplerAnisotropy", &features->samplerAnisotropy) &&
+    visitor->Visit("textureCompressionETC2", &features->textureCompressionETC2) &&
+    visitor->Visit("textureCompressionASTC_LDR", &features->textureCompressionASTC_LDR) &&
+    visitor->Visit("textureCompressionBC", &features->textureCompressionBC) &&
+    visitor->Visit("occlusionQueryPrecise", &features->occlusionQueryPrecise) &&
+    visitor->Visit("pipelineStatisticsQuery", &features->pipelineStatisticsQuery) &&
+    visitor->Visit("vertexPipelineStoresAndAtomics", &features->vertexPipelineStoresAndAtomics) &&
+    visitor->Visit("fragmentStoresAndAtomics", &features->fragmentStoresAndAtomics) &&
+    visitor->Visit("shaderTessellationAndGeometryPointSize", &features->shaderTessellationAndGeometryPointSize) &&
+    visitor->Visit("shaderImageGatherExtended", &features->shaderImageGatherExtended) &&
+    visitor->Visit("shaderStorageImageExtendedFormats", &features->shaderStorageImageExtendedFormats) &&
+    visitor->Visit("shaderStorageImageMultisample", &features->shaderStorageImageMultisample) &&
+    visitor->Visit("shaderStorageImageReadWithoutFormat", &features->shaderStorageImageReadWithoutFormat) &&
+    visitor->Visit("shaderStorageImageWriteWithoutFormat", &features->shaderStorageImageWriteWithoutFormat) &&
+    visitor->Visit("shaderUniformBufferArrayDynamicIndexing", &features->shaderUniformBufferArrayDynamicIndexing) &&
+    visitor->Visit("shaderSampledImageArrayDynamicIndexing", &features->shaderSampledImageArrayDynamicIndexing) &&
+    visitor->Visit("shaderStorageBufferArrayDynamicIndexing", &features->shaderStorageBufferArrayDynamicIndexing) &&
+    visitor->Visit("shaderStorageImageArrayDynamicIndexing", &features->shaderStorageImageArrayDynamicIndexing) &&
+    visitor->Visit("shaderClipDistance", &features->shaderClipDistance) &&
+    visitor->Visit("shaderCullDistance", &features->shaderCullDistance) &&
+    visitor->Visit("shaderFloat64", &features->shaderFloat64) &&
+    visitor->Visit("shaderInt64", &features->shaderInt64) &&
+    visitor->Visit("shaderInt16", &features->shaderInt16) &&
+    visitor->Visit("shaderResourceResidency", &features->shaderResourceResidency) &&
+    visitor->Visit("shaderResourceMinLod", &features->shaderResourceMinLod) &&
+    visitor->Visit("sparseBinding", &features->sparseBinding) &&
+    visitor->Visit("sparseResidencyBuffer", &features->sparseResidencyBuffer) &&
+    visitor->Visit("sparseResidencyImage2D", &features->sparseResidencyImage2D) &&
+    visitor->Visit("sparseResidencyImage3D", &features->sparseResidencyImage3D) &&
+    visitor->Visit("sparseResidency2Samples", &features->sparseResidency2Samples) &&
+    visitor->Visit("sparseResidency4Samples", &features->sparseResidency4Samples) &&
+    visitor->Visit("sparseResidency8Samples", &features->sparseResidency8Samples) &&
+    visitor->Visit("sparseResidency16Samples", &features->sparseResidency16Samples) &&
+    visitor->Visit("sparseResidencyAliased", &features->sparseResidencyAliased) &&
+    visitor->Visit("variableMultisampleRate", &features->variableMultisampleRate) &&
+    visitor->Visit("inheritedQueries", &features->inheritedQueries);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkMemoryType* type) {
+  return
+    visitor->Visit("propertyFlags", &type->propertyFlags) &&
+    visitor->Visit("heapIndex", &type->heapIndex);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkMemoryHeap* heap) {
+  return
+    visitor->Visit("size", &heap->size) &&
+    visitor->Visit("flags", &heap->flags);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkPhysicalDeviceMemoryProperties* properties) {
+  return
+    visitor->Visit("memoryTypeCount", &properties->memoryTypeCount) &&
+    visitor->VisitArray("memoryTypes", properties->memoryTypeCount, &properties->memoryTypes) &&
+    visitor->Visit("memoryHeapCount", &properties->memoryHeapCount) &&
+    visitor->VisitArray("memoryHeaps", properties->memoryHeapCount, &properties->memoryHeaps);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkQueueFamilyProperties* properties) {
+  return
+    visitor->Visit("queueFlags", &properties->queueFlags) &&
+    visitor->Visit("queueCount", &properties->queueCount) &&
+    visitor->Visit("timestampValidBits", &properties->timestampValidBits) &&
+    visitor->Visit("minImageTransferGranularity", &properties->minImageTransferGranularity);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkExtensionProperties* properties) {
+  return
+    visitor->Visit("extensionName", &properties->extensionName) &&
+    visitor->Visit("specVersion", &properties->specVersion);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkLayerProperties* properties) {
+  return
+    visitor->Visit("layerName", &properties->layerName) &&
+    visitor->Visit("specVersion", &properties->specVersion) &&
+    visitor->Visit("implementationVersion", &properties->implementationVersion) &&
+    visitor->Visit("description", &properties->description);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkFormatProperties* properties) {
+  return
+    visitor->Visit("linearTilingFeatures", &properties->linearTilingFeatures) &&
+    visitor->Visit("optimalTilingFeatures", &properties->optimalTilingFeatures) &&
+    visitor->Visit("bufferFeatures", &properties->bufferFeatures);
+}
+
+template <typename Visitor>
+inline bool Iterate(Visitor* visitor, VkJsonAllProperties* properties) {
+  return
+    visitor->Visit("properties", &properties->properties) &&
+    visitor->Visit("features", &properties->features) &&
+    visitor->Visit("memory", &properties->memory) &&
+    visitor->Visit("queues", &properties->queues) &&
+    visitor->Visit("extensions", &properties->extensions) &&
+    visitor->Visit("layers", &properties->layers) &&
+    visitor->Visit("formats", &properties->formats);
+}
+
+
+template <typename T>
+using EnableForArithmetic =
+    typename std::enable_if<std::is_arithmetic<T>::value, void>::type;
+
+template <typename T>
+using EnableForStruct =
+    typename std::enable_if<std::is_class<T>::value, void>::type;
+
+template <typename T>
+using EnableForEnum =
+    typename std::enable_if<std::is_enum<T>::value, void>::type;
+
+template <typename T, typename = EnableForStruct<T>, typename = void>
+cJSON* ToJsonValue(const T& value);
+
+template <typename T, typename = EnableForArithmetic<T>>
+inline cJSON* ToJsonValue(const T& value) {
+  return cJSON_CreateNumber(static_cast<double>(value));
+}
+
+template <typename T, typename = EnableForEnum<T>, typename = void,
+          typename = void>
+inline cJSON* ToJsonValue(const T& value) {
+  return cJSON_CreateNumber(static_cast<double>(value));
+}
+
+template <typename T>
+inline cJSON* ArrayToJsonValue(uint32_t count, const T* values) {
+  cJSON* array = cJSON_CreateArray();
+  for (unsigned int i = 0; i < count; ++i)
+    cJSON_AddItemToArray(array, ToJsonValue(values[i]));
+  return array;
+}
+
+template <typename T, unsigned int N>
+inline cJSON* ToJsonValue(const T (&value)[N]) {
+  return ArrayToJsonValue(N, value);
+}
+
+template <size_t N>
+inline cJSON* ToJsonValue(const char (&value)[N]) {
+  assert(strlen(value) < N);
+  return cJSON_CreateString(value);
+}
+
+template <typename T>
+inline cJSON* ToJsonValue(const std::vector<T>& value) {
+  assert(value.size() <= std::numeric_limits<uint32_t>::max());
+  return ArrayToJsonValue(static_cast<uint32_t>(value.size()), value.data());
+}
+
+template <typename F, typename S>
+inline cJSON* ToJsonValue(const std::pair<F, S>& value) {
+  cJSON* array = cJSON_CreateArray();
+  cJSON_AddItemToArray(array, ToJsonValue(value.first));
+  cJSON_AddItemToArray(array, ToJsonValue(value.second));
+  return array;
+}
+
+template <typename F, typename S>
+inline cJSON* ToJsonValue(const std::map<F, S>& value) {
+  cJSON* array = cJSON_CreateArray();
+  for (auto& kv : value)
+    cJSON_AddItemToArray(array, ToJsonValue(kv));
+  return array;
+}
+
+class JsonWriterVisitor {
+ public:
+  JsonWriterVisitor() : object_(cJSON_CreateObject()) {}
+
+  ~JsonWriterVisitor() {
+    if (object_)
+      cJSON_Delete(object_);
+  }
+
+  template <typename T> bool Visit(const char* key, const T* value) {
+    cJSON_AddItemToObjectCS(object_, key, ToJsonValue(*value));
+    return true;
+  }
+
+  template <typename T, uint32_t N>
+  bool VisitArray(const char* key, uint32_t count, const T (*value)[N]) {
+    assert(count <= N);
+    cJSON_AddItemToObjectCS(object_, key, ArrayToJsonValue(count, *value));
+    return true;
+  }
+
+  cJSON* get_object() const { return object_; }
+  cJSON* take_object() {
+    cJSON* object = object_;
+    object_ = nullptr;
+    return object;
+  }
+
+ private:
+  cJSON* object_;
+};
+
+template <typename Visitor, typename T>
+inline void VisitForWrite(Visitor* visitor, const T& t) {
+  Iterate(visitor, const_cast<T*>(&t));
+}
+
+template <typename T, typename = EnableForStruct<T>, typename = void>
+cJSON* ToJsonValue(const T& value) {
+  JsonWriterVisitor visitor;
+  VisitForWrite(&visitor, value);
+  return visitor.take_object();
+}
+
+template <typename T, typename = EnableForStruct<T>>
+bool AsValue(cJSON* json_value, T* t);
+
+inline bool AsValue(cJSON* json_value, int32_t* value) {
+  double d = json_value->valuedouble;
+  if (json_value->type != cJSON_Number || !IsIntegral(d) ||
+      d < static_cast<double>(std::numeric_limits<int32_t>::min()) ||
+      d > static_cast<double>(std::numeric_limits<int32_t>::max()))
+    return false;
+  *value = static_cast<int32_t>(d);
+  return true;
+}
+
+inline bool AsValue(cJSON* json_value, uint64_t* value) {
+  double d = json_value->valuedouble;
+  if (json_value->type != cJSON_Number || !IsIntegral(d) ||
+      d < 0.0 || d > static_cast<double>(std::numeric_limits<uint64_t>::max()))
+    return false;
+  *value = static_cast<uint64_t>(d);
+  return true;
+}
+
+inline bool AsValue(cJSON* json_value, uint32_t* value) {
+  uint64_t value64 = 0;
+  AsValue(json_value, &value64);
+  if (value64 > std::numeric_limits<uint32_t>::max())
+    return false;
+  *value = static_cast<uint32_t>(value64);
+  return true;
+}
+
+inline bool AsValue(cJSON* json_value, uint8_t* value) {
+  uint64_t value64 = 0;
+  AsValue(json_value, &value64);
+  if (value64 > std::numeric_limits<uint8_t>::max())
+    return false;
+  *value = static_cast<uint8_t>(value64);
+  return true;
+}
+
+inline bool AsValue(cJSON* json_value, float* value) {
+  if (json_value->type != cJSON_Number)
+    return false;
+  *value = static_cast<float>(json_value->valuedouble);
+  return true;
+}
+
+template <typename T>
+inline bool AsArray(cJSON* json_value, uint32_t count, T* values) {
+  if (json_value->type != cJSON_Array || cJSON_GetArraySize(json_value) != count)
+    return false;
+  for (uint32_t i = 0; i < count; ++i) {
+    if (!AsValue(cJSON_GetArrayItem(json_value, i), values + i))
+      return false;
+  }
+  return true;
+}
+
+template <typename T, unsigned int N>
+inline bool AsValue(cJSON* json_value, T (*value)[N]) {
+  return AsArray(json_value, N, *value);
+}
+
+template <size_t N>
+inline bool AsValue(cJSON* json_value, char (*value)[N]) {
+  if (json_value->type != cJSON_String)
+    return false;
+  size_t len = strlen(json_value->valuestring);
+  if (len >= N)
+    return false;
+  memcpy(*value, json_value->valuestring, len);
+  memset(*value + len, 0, N-len);
+  return true;
+}
+
+template <typename T, typename = EnableForEnum<T>, typename = void>
+inline bool AsValue(cJSON* json_value, T* t) {
+  // TODO(piman): to/from strings instead?
+  uint32_t value = 0;
+  if (!AsValue(json_value, &value))
+      return false;
+  if (value < EnumTraits<T>::min() || value > EnumTraits<T>::max())
+    return false;
+  *t = static_cast<T>(value);
+  return true;
+}
+
+template <typename T>
+inline bool AsValue(cJSON* json_value, std::vector<T>* value) {
+  if (json_value->type != cJSON_Array)
+    return false;
+  int size = cJSON_GetArraySize(json_value);
+  value->resize(size);
+  return AsArray(json_value, size, value->data());
+}
+
+template <typename F, typename S>
+inline bool AsValue(cJSON* json_value, std::pair<F, S>* value) {
+  if (json_value->type != cJSON_Array || cJSON_GetArraySize(json_value) != 2)
+    return false;
+  return AsValue(cJSON_GetArrayItem(json_value, 0), &value->first) &&
+         AsValue(cJSON_GetArrayItem(json_value, 1), &value->second);
+}
+
+template <typename F, typename S>
+inline bool AsValue(cJSON* json_value, std::map<F, S>* value) {
+  if (json_value->type != cJSON_Array)
+    return false;
+  int size = cJSON_GetArraySize(json_value);
+  for (unsigned int i = 0; i < size; ++i) {
+    std::pair<F, S> elem;
+    if (!AsValue(cJSON_GetArrayItem(json_value, i), &elem))
+      return false;
+    if (!value->insert(elem).second)
+      return false;
+  }
+  return true;
+}
+
+template <typename T>
+bool ReadValue(cJSON* object, const char* key, T* value,
+               std::string* errors) {
+  cJSON* json_value = cJSON_GetObjectItem(object, key);
+  if (!json_value) {
+    if (errors)
+      *errors = std::string(key) + " missing.";
+    return false;
+  }
+  if (AsValue(json_value, value))
+    return true;
+  if (errors)
+    *errors = std::string("Wrong type for ") + std::string(key) + ".";
+  return false;
+}
+
+template <typename Visitor, typename T>
+inline bool VisitForRead(Visitor* visitor, T* t) {
+  return Iterate(visitor, t);
+}
+
+class JsonReaderVisitor {
+ public:
+  JsonReaderVisitor(cJSON* object, std::string* errors)
+      : object_(object), errors_(errors) {}
+
+  template <typename T> bool Visit(const char* key, T* value) const {
+    return ReadValue(object_, key, value, errors_);
+  }
+
+  template <typename T, uint32_t N>
+  bool VisitArray(const char* key, uint32_t count, T (*value)[N]) {
+    if (count > N)
+      return false;
+    cJSON* json_value = cJSON_GetObjectItem(object_, key);
+    if (!json_value) {
+      if (errors_)
+        *errors_ = std::string(key) + " missing.";
+      return false;
+    }
+    if (AsArray(json_value, count, *value))
+      return true;
+    if (errors_)
+      *errors_ = std::string("Wrong type for ") + std::string(key) + ".";
+    return false;
+  }
+
+
+ private:
+  cJSON* object_;
+  std::string* errors_;
+};
+
+template <typename T, typename = EnableForStruct<T>>
+bool AsValue(cJSON* json_value, T* t) {
+  if (json_value->type != cJSON_Object)
+    return false;
+  JsonReaderVisitor visitor(json_value, nullptr);
+  return VisitForRead(&visitor, t);
+}
+
+
+template <typename T> std::string VkTypeToJson(const T& t) {
+  JsonWriterVisitor visitor;
+  VisitForWrite(&visitor, t);
+
+  char* output = cJSON_Print(visitor.get_object());
+  std::string result(output);
+  free(output);
+  return result;
+}
+
+template <typename T> bool VkTypeFromJson(const std::string& json,
+                                          T* t,
+                                          std::string* errors) {
+  *t = T();
+  cJSON* object = cJSON_Parse(json.c_str());
+  if (!object) {
+    if (errors)
+      errors->assign(cJSON_GetErrorPtr());
+    return false;
+  }
+  bool result = AsValue(object, t);
+  cJSON_Delete(object);
+  return result;
+}
+
+}  // anonymous namespace
+
+std::string VkJsonAllPropertiesToJson(
+    const VkJsonAllProperties& properties) {
+  return VkTypeToJson(properties);
+}
+
+bool VkJsonAllPropertiesFromJson(
+    const std::string& json, VkJsonAllProperties* properties,
+    std::string* errors) {
+  return VkTypeFromJson(json, properties, errors);
+};
+
+std::string VkJsonImageFormatPropertiesToJson(
+    const VkImageFormatProperties& properties) {
+  return VkTypeToJson(properties);
+}
+
+bool VkJsonImageFormatPropertiesFromJson(const std::string& json,
+                                         VkImageFormatProperties* properties,
+                                         std::string* errors) {
+  return VkTypeFromJson(json, properties, errors);
+};
diff --git a/libs/vkjson/vkjson.h b/libs/vkjson/vkjson.h
new file mode 100644 (file)
index 0000000..b85a31f
--- /dev/null
@@ -0,0 +1,61 @@
+// Copyright 2015 Google Inc. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef VKJSON_H_
+#define VKJSON_H_
+
+#include <vulkan/vulkan.h>
+#include <map>
+#include <string>
+#include <vector>
+
+struct VkJsonAllProperties {
+  VkPhysicalDeviceProperties properties = {0};
+  VkPhysicalDeviceFeatures features = {0};
+  VkPhysicalDeviceMemoryProperties memory = {0};
+  std::vector<VkQueueFamilyProperties> queues;
+  std::vector<VkExtensionProperties> extensions;
+  std::vector<VkLayerProperties> layers;
+  std::map<VkFormat, VkFormatProperties> formats;
+};
+
+VkJsonAllProperties VkJsonGetAllProperties(VkPhysicalDevice physicalDevice);
+
+std::string VkJsonAllPropertiesToJson(
+    const VkJsonAllProperties& properties);
+bool VkJsonAllPropertiesFromJson(
+    const std::string& json, VkJsonAllProperties* properties,
+    std::string* errors);
+
+std::string VkJsonImageFormatPropertiesToJson(
+    const VkImageFormatProperties& properties);
+bool VkJsonImageFormatPropertiesFromJson(const std::string& json,
+                                         VkImageFormatProperties* properties,
+                                         std::string* errors);
+
+#endif  // VKJSON_H_
diff --git a/libs/vkjson/vkjson_device.cc b/libs/vkjson/vkjson_device.cc
new file mode 100644 (file)
index 0000000..8aa14f3
--- /dev/null
@@ -0,0 +1,82 @@
+// Copyright 2015 Google Inc. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#define VK_PROTOTYPES
+#include "vkjson.h"
+
+#include <utility>
+
+VkJsonAllProperties VkJsonGetAllProperties(VkPhysicalDevice physical_device) {
+  VkJsonAllProperties properties;
+  vkGetPhysicalDeviceProperties(physical_device, &properties.properties);
+  vkGetPhysicalDeviceFeatures(physical_device, &properties.features);
+  vkGetPhysicalDeviceMemoryProperties(physical_device, &properties.memory);
+
+  uint32_t queue_family_count = 0;
+  vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &queue_family_count,
+                                           nullptr);
+  if (queue_family_count > 0) {
+    properties.queues.resize(queue_family_count);
+    vkGetPhysicalDeviceQueueFamilyProperties(
+        physical_device, &queue_family_count, properties.queues.data());
+  }
+
+  // Only device extensions.
+  // TODO(piman): do we want to show layer extensions?
+  uint32_t extension_count = 0;
+  vkEnumerateDeviceExtensionProperties(physical_device, nullptr,
+                                       &extension_count, nullptr);
+  if (extension_count > 0) {
+    properties.extensions.resize(extension_count);
+    vkEnumerateDeviceExtensionProperties(physical_device, nullptr,
+                                         &extension_count,
+                                         properties.extensions.data());
+  }
+
+  uint32_t layer_count = 0;
+  vkEnumerateDeviceLayerProperties(physical_device, &layer_count, nullptr);
+  if (layer_count > 0) {
+    properties.layers.resize(layer_count);
+    vkEnumerateDeviceLayerProperties(physical_device, &layer_count,
+                                     properties.layers.data());
+  }
+
+  VkFormatProperties format_properties = {0};
+  for (VkFormat format = VK_FORMAT_R4G4_UNORM_PACK8;
+       format <= VK_FORMAT_END_RANGE;
+       format = static_cast<VkFormat>(format + 1)) {
+    vkGetPhysicalDeviceFormatProperties(physical_device, format,
+                                        &format_properties);
+    if (format_properties.linearTilingFeatures ||
+        format_properties.optimalTilingFeatures ||
+        format_properties.bufferFeatures) {
+      properties.formats.insert(std::make_pair(format, format_properties));
+    }
+  }
+  return properties;
+}
diff --git a/libs/vkjson/vkjson_info.cc b/libs/vkjson/vkjson_info.cc
new file mode 100644 (file)
index 0000000..134a231
--- /dev/null
@@ -0,0 +1,195 @@
+// Copyright 2015 Google Inc. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#define VK_PROTOTYPES
+#include "vkjson.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#include <iostream>
+#include <vector>
+
+struct Options {
+  uint32_t device_index = -1u;
+  std::string device_name;
+  std::string output_file;
+};
+
+bool ParseOptions(int argc, char* argv[], Options* options) {
+  for (int i = 1; i < argc; ++i) {
+    std::string arg(argv[i]);
+    if (arg == "--first" || arg == "-f") {
+      options->device_index = 0;
+    } else {
+      ++i;
+      if (i >= argc) {
+        std::cerr << "Missing parameter after: " << arg << std::endl;
+        return false;
+      }
+      std::string arg2(argv[i]);
+      if (arg == "--device-index" || arg == "-d") {
+        int result = sscanf(arg2.c_str(), "%u", &options->device_index);
+        if (result != 1) {
+          options->device_index = -1;
+          std::cerr << "Unable to parse index: " << arg2 << std::endl;
+          return false;
+        }
+      } else if (arg == "--device-name" || arg == "-n") {
+        options->device_name = arg2;
+      } else if (arg == "--output" || arg == "-o") {
+        options->output_file = arg2;
+      } else {
+        std::cerr << "Unknown argument: " << arg << std::endl;
+        return false;
+      }
+    }
+  }
+  if (options->device_index != -1u && !options->device_name.empty()) {
+    std::cerr << "Must specify only one of device index and device name."
+              << std::endl;
+    return false;
+  }
+  if (!options->output_file.empty() && options->device_index == -1u &&
+      options->device_name.empty()) {
+    std::cerr << "Must specify device index or device name when specifying "
+                 "output file"
+              << std::endl;
+    return false;
+  }
+  return true;
+}
+
+bool DumpProperties(const VkJsonAllProperties& props, const Options& options) {
+  std::string device_name(props.properties.deviceName);
+  std::string output_file = options.output_file;
+  if (output_file.empty())
+    output_file = device_name + ".json";
+  FILE* file = nullptr;
+  if (output_file == "-") {
+    file = stdout;
+  } else {
+    file = fopen(output_file.c_str(), "w");
+    if (!file) {
+      std::cerr << "Unable to open file " << output_file << "." << std::endl;
+      return false;
+    }
+  }
+
+  std::string json = VkJsonAllPropertiesToJson(props) + '\n';
+  fwrite(json.data(), 1, json.size(), file);
+
+  if (output_file != "-") {
+    fclose(file);
+    std::cout << "Wrote file " << output_file << " for device " << device_name
+              << "." << std::endl;
+  }
+  return true;
+}
+
+int main(int argc, char* argv[]) {
+  Options options;
+  if (!ParseOptions(argc, argv, &options))
+    return 1;
+
+  const VkApplicationInfo app_info = {VK_STRUCTURE_TYPE_APPLICATION_INFO,
+                                      nullptr,
+                                      "vkjson_info",
+                                      1,
+                                      "",
+                                      0,
+                                      VK_API_VERSION};
+  VkInstanceCreateInfo instance_info = {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
+                                        nullptr,
+                                        0,
+                                        &app_info,
+                                        0,
+                                        nullptr,
+                                        0,
+                                        nullptr};
+  VkInstance instance;
+  VkResult result = vkCreateInstance(&instance_info, nullptr, &instance);
+  if (result != VK_SUCCESS) {
+    std::cerr << "Error: vkCreateInstance failed with error: " << result
+              << "." << std::endl;
+    return 1;
+  }
+
+  uint32_t device_count = 0;
+  result = vkEnumeratePhysicalDevices(instance, &device_count, nullptr);
+  if (result != VK_SUCCESS) {
+    std::cerr << "Error: vkEnumeratePhysicalDevices failed with error "
+              << result << "." << std::endl;
+    return 1;
+  }
+  if (device_count == 0) {
+    std::cerr << "Error: no Vulkan device found.";
+    return 1;
+  }
+
+  std::vector<VkPhysicalDevice> physical_devices(device_count,
+                                                 VkPhysicalDevice());
+  result = vkEnumeratePhysicalDevices(instance, &device_count,
+                                      physical_devices.data());
+  if (result != VK_SUCCESS) {
+    std::cerr << "Error: vkEnumeratePhysicalDevices failed with error "
+              << result << std::endl;
+    return 1;
+  }
+
+  if (options.device_index != -1u) {
+    if (static_cast<uint32_t>(options.device_index) >= device_count) {
+      std::cerr << "Error: device " << options.device_index
+                << " requested but only " << device_count << " found."
+                << std::endl;
+      return 1;
+    }
+    auto props = VkJsonGetAllProperties(physical_devices[options.device_index]);
+    if (!DumpProperties(props, options))
+      return 1;
+    return 0;
+  }
+
+  bool found = false;
+  for (auto physical_device : physical_devices) {
+    auto props = VkJsonGetAllProperties(physical_device);
+    if (!options.device_name.empty() &&
+        options.device_name != props.properties.deviceName)
+      continue;
+    if (!DumpProperties(props, options))
+      return 1;
+    found = true;
+  }
+
+  if (!found) {
+    std::cerr << "Error: device " << options.device_name << " not found."
+              << std::endl;
+    return 1;
+  }
+  return 0;
+}
diff --git a/libs/vkjson/vkjson_unittest.cc b/libs/vkjson/vkjson_unittest.cc
new file mode 100644 (file)
index 0000000..4d4efe3
--- /dev/null
@@ -0,0 +1,108 @@
+// Copyright 2015 Google Inc. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include "vkjson.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <iostream>
+
+#define EXPECT(X) if (!(X)) \
+  ReportFailure(__FILE__, __LINE__, #X);
+
+#define ASSERT(X) if (!(X)) { \
+  ReportFailure(__FILE__, __LINE__, #X); \
+  return 2; \
+}
+
+int g_failures;
+
+void ReportFailure(const char* file, int line, const char* assertion) {
+  std::cout << file << ":" << line << ": \"" << assertion << "\" failed."
+            << std::endl;
+  ++g_failures;
+}
+
+int main(int argc, char* argv[]) {
+  std::string errors;
+  bool result = false;
+
+  const char name[] = "Test device";
+  VkJsonAllProperties device_props;
+  memcpy(device_props.properties.deviceName, name, sizeof(name));
+  device_props.properties.limits.maxImageDimension1D = 3;
+  device_props.properties.limits.maxSamplerLodBias = 3.5f;
+  device_props.properties.limits.bufferImageGranularity = 0x1ffffffffull;
+  device_props.properties.limits.maxViewportDimensions[0] = 1;
+  device_props.properties.limits.maxViewportDimensions[1] = 2;
+  VkFormatProperties format_props = {
+      VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT,
+      VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT,
+      VK_FORMAT_FEATURE_BLIT_SRC_BIT | VK_FORMAT_FEATURE_BLIT_DST_BIT};
+  device_props.formats.insert(
+      std::make_pair(VK_FORMAT_R8_UNORM, format_props));
+  device_props.formats.insert(
+      std::make_pair(VK_FORMAT_R8G8_UNORM, format_props));
+  std::string json = VkJsonAllPropertiesToJson(device_props);
+  std::cout << json << std::endl;
+
+  VkJsonAllProperties device_props2;
+  result = VkJsonAllPropertiesFromJson(json, &device_props2, &errors);
+  EXPECT(result);
+  if (!result)
+    std::cout << "Error: " << errors << std::endl;
+
+  EXPECT(!memcmp(&device_props.properties,
+                 &device_props2.properties,
+                 sizeof(device_props.properties)));
+  for (auto& kv : device_props.formats) {
+    auto it = device_props2.formats.find(kv.first);
+    EXPECT(it != device_props2.formats.end());
+    EXPECT(!memcmp(&kv.second, &it->second, sizeof(kv.second)));
+  }
+
+  VkImageFormatProperties props = {0};
+  json = VkJsonImageFormatPropertiesToJson(props);
+  // std::cout << json << std::endl;
+  VkImageFormatProperties props2 = {0};
+  result = VkJsonImageFormatPropertiesFromJson(json, &props2, &errors);
+  EXPECT(result);
+  if (!result)
+    std::cout << "Error: " << errors << std::endl;
+
+  EXPECT(!memcmp(&props, &props2, sizeof(props)));
+
+  if (g_failures) {
+    std::cout << g_failures << " failures." << std::endl;
+    return 1;
+  } else {
+    std::cout << "Success." << std::endl;
+    return 0;
+  }
+}