file_path
stringlengths 20
202
| content
stringlengths 9
3.85M
| size
int64 9
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 8
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_cpuinfo.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_cpuinfo.h
*
* CPU feature detection for SDL.
*/
#ifndef SDL_cpuinfo_h_
#define SDL_cpuinfo_h_
#include "SDL_stdinc.h"
/* Need to do this here because intrin.h has C++ code in it */
/* Visual Studio 2005 has a bug where intrin.h conflicts with winnt.h */
#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (defined(_M_IX86) || defined(_M_X64))
#ifdef __clang__
/* Many of the intrinsics SDL uses are not implemented by clang with Visual Studio */
#undef __MMX__
#undef __SSE__
#undef __SSE2__
#else
#include <intrin.h>
#ifndef _WIN64
#define __MMX__
#define __3dNOW__
#endif
#define __SSE__
#define __SSE2__
#endif /* __clang__ */
#elif defined(__MINGW64_VERSION_MAJOR)
#include <intrin.h>
#else
#ifdef __ALTIVEC__
#if HAVE_ALTIVEC_H && !defined(__APPLE_ALTIVEC__) && !defined(SDL_DISABLE_ALTIVEC_H)
#include <altivec.h>
#undef pixel
#undef bool
#endif
#endif
#if defined(__3dNOW__) && !defined(SDL_DISABLE_MM3DNOW_H)
#include <mm3dnow.h>
#endif
#if HAVE_IMMINTRIN_H && !defined(SDL_DISABLE_IMMINTRIN_H)
#include <immintrin.h>
#else
#if defined(__MMX__) && !defined(SDL_DISABLE_MMINTRIN_H)
#include <mmintrin.h>
#endif
#if defined(__SSE__) && !defined(SDL_DISABLE_XMMINTRIN_H)
#include <xmmintrin.h>
#endif
#if defined(__SSE2__) && !defined(SDL_DISABLE_EMMINTRIN_H)
#include <emmintrin.h>
#endif
#if defined(__SSE3__) && !defined(SDL_DISABLE_PMMINTRIN_H)
#include <pmmintrin.h>
#endif
#endif /* HAVE_IMMINTRIN_H */
#endif /* compiler version */
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* This is a guess for the cacheline size used for padding.
* Most x86 processors have a 64 byte cache line.
* The 64-bit PowerPC processors have a 128 byte cache line.
* We'll use the larger value to be generally safe.
*/
#define SDL_CACHELINE_SIZE 128
/**
* This function returns the number of CPU cores available.
*/
extern DECLSPEC int SDLCALL SDL_GetCPUCount(void);
/**
* This function returns the L1 cache line size of the CPU
*
* This is useful for determining multi-threaded structure padding
* or SIMD prefetch sizes.
*/
extern DECLSPEC int SDLCALL SDL_GetCPUCacheLineSize(void);
/**
* This function returns true if the CPU has the RDTSC instruction.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasRDTSC(void);
/**
* This function returns true if the CPU has AltiVec features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasAltiVec(void);
/**
* This function returns true if the CPU has MMX features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasMMX(void);
/**
* This function returns true if the CPU has 3DNow! features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_Has3DNow(void);
/**
* This function returns true if the CPU has SSE features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE(void);
/**
* This function returns true if the CPU has SSE2 features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE2(void);
/**
* This function returns true if the CPU has SSE3 features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE3(void);
/**
* This function returns true if the CPU has SSE4.1 features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE41(void);
/**
* This function returns true if the CPU has SSE4.2 features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE42(void);
/**
* This function returns true if the CPU has AVX features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasAVX(void);
/**
* This function returns true if the CPU has AVX2 features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasAVX2(void);
/**
* This function returns true if the CPU has NEON (ARM SIMD) features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasNEON(void);
/**
* This function returns the amount of RAM configured in the system, in MB.
*/
extern DECLSPEC int SDLCALL SDL_GetSystemRAM(void);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_cpuinfo_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 4,937 | C | 26.131868 | 85 | 0.713794 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_vulkan.h | /*
Simple DirectMedia Layer
Copyright (C) 2017, Mark Callow
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_vulkan.h
*
* Header file for functions to creating Vulkan surfaces on SDL windows.
*/
#ifndef SDL_vulkan_h_
#define SDL_vulkan_h_
#include "SDL_video.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* Avoid including vulkan.h, don't define VkInstance if it's already included */
#ifdef VULKAN_H_
#define NO_SDL_VULKAN_TYPEDEFS
#endif
#ifndef NO_SDL_VULKAN_TYPEDEFS
#define VK_DEFINE_HANDLE(object) typedef struct object##_T* object;
#if defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
#define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object;
#else
#define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object;
#endif
VK_DEFINE_HANDLE(VkInstance)
VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR)
#endif /* !NO_SDL_VULKAN_TYPEDEFS */
typedef VkInstance SDL_vulkanInstance;
typedef VkSurfaceKHR SDL_vulkanSurface; /* for compatibility with Tizen */
/**
* \name Vulkan support functions
*
* \note SDL_Vulkan_GetInstanceExtensions & SDL_Vulkan_CreateSurface API
* is compatable with Tizen's implementation of Vulkan in SDL.
*/
/* @{ */
/**
* \brief Dynamically load a Vulkan loader library.
*
* \param [in] path The platform dependent Vulkan loader library name, or
* \c NULL.
*
* \return \c 0 on success, or \c -1 if the library couldn't be loaded.
*
* If \a path is NULL SDL will use the value of the environment variable
* \c SDL_VULKAN_LIBRARY, if set, otherwise it loads the default Vulkan
* loader library.
*
* This should be called after initializing the video driver, but before
* creating any Vulkan windows. If no Vulkan loader library is loaded, the
* default library will be loaded upon creation of the first Vulkan window.
*
* \note It is fairly common for Vulkan applications to link with \a libvulkan
* instead of explicitly loading it at run time. This will work with
* SDL provided the application links to a dynamic library and both it
* and SDL use the same search path.
*
* \note If you specify a non-NULL \c path, an application should retrieve all
* of the Vulkan functions it uses from the dynamic library using
* \c SDL_Vulkan_GetVkGetInstanceProcAddr() unless you can guarantee
* \c path points to the same vulkan loader library the application
* linked to.
*
* \note On Apple devices, if \a path is NULL, SDL will attempt to find
* the vkGetInstanceProcAddr address within all the mach-o images of
* the current process. This is because it is fairly common for Vulkan
* applications to link with libvulkan (and historically MoltenVK was
* provided as a static library). If it is not found then, on macOS, SDL
* will attempt to load \c vulkan.framework/vulkan, \c libvulkan.1.dylib,
* \c MoltenVK.framework/MoltenVK and \c libMoltenVK.dylib in that order.
* On iOS SDL will attempt to load \c libMoltenVK.dylib. Applications
* using a dynamic framework or .dylib must ensure it is included in its
* application bundle.
*
* \note On non-Apple devices, application linking with a static libvulkan is
* not supported. Either do not link to the Vulkan loader or link to a
* dynamic library version.
*
* \note This function will fail if there are no working Vulkan drivers
* installed.
*
* \sa SDL_Vulkan_GetVkGetInstanceProcAddr()
* \sa SDL_Vulkan_UnloadLibrary()
*/
extern DECLSPEC int SDLCALL SDL_Vulkan_LoadLibrary(const char *path);
/**
* \brief Get the address of the \c vkGetInstanceProcAddr function.
*
* \note This should be called after either calling SDL_Vulkan_LoadLibrary
* or creating an SDL_Window with the SDL_WINDOW_VULKAN flag.
*/
extern DECLSPEC void *SDLCALL SDL_Vulkan_GetVkGetInstanceProcAddr(void);
/**
* \brief Unload the Vulkan loader library previously loaded by
* \c SDL_Vulkan_LoadLibrary().
*
* \sa SDL_Vulkan_LoadLibrary()
*/
extern DECLSPEC void SDLCALL SDL_Vulkan_UnloadLibrary(void);
/**
* \brief Get the names of the Vulkan instance extensions needed to create
* a surface with \c SDL_Vulkan_CreateSurface().
*
* \param [in] window Window for which the required Vulkan instance
* extensions should be retrieved
* \param [in,out] count pointer to an \c unsigned related to the number of
* required Vulkan instance extensions
* \param [out] names \c NULL or a pointer to an array to be filled with the
* required Vulkan instance extensions
*
* \return \c SDL_TRUE on success, \c SDL_FALSE on error.
*
* If \a pNames is \c NULL, then the number of required Vulkan instance
* extensions is returned in pCount. Otherwise, \a pCount must point to a
* variable set to the number of elements in the \a pNames array, and on
* return the variable is overwritten with the number of names actually
* written to \a pNames. If \a pCount is less than the number of required
* extensions, at most \a pCount structures will be written. If \a pCount
* is smaller than the number of required extensions, \c SDL_FALSE will be
* returned instead of \c SDL_TRUE, to indicate that not all the required
* extensions were returned.
*
* \note The returned list of extensions will contain \c VK_KHR_surface
* and zero or more platform specific extensions
*
* \note The extension names queried here must be enabled when calling
* VkCreateInstance, otherwise surface creation will fail.
*
* \note \c window should have been created with the \c SDL_WINDOW_VULKAN flag.
*
* \code
* unsigned int count;
* // get count of required extensions
* if(!SDL_Vulkan_GetInstanceExtensions(window, &count, NULL))
* handle_error();
*
* static const char *const additionalExtensions[] =
* {
* VK_EXT_DEBUG_REPORT_EXTENSION_NAME, // example additional extension
* };
* size_t additionalExtensionsCount = sizeof(additionalExtensions) / sizeof(additionalExtensions[0]);
* size_t extensionCount = count + additionalExtensionsCount;
* const char **names = malloc(sizeof(const char *) * extensionCount);
* if(!names)
* handle_error();
*
* // get names of required extensions
* if(!SDL_Vulkan_GetInstanceExtensions(window, &count, names))
* handle_error();
*
* // copy additional extensions after required extensions
* for(size_t i = 0; i < additionalExtensionsCount; i++)
* names[i + count] = additionalExtensions[i];
*
* VkInstanceCreateInfo instanceCreateInfo = {};
* instanceCreateInfo.enabledExtensionCount = extensionCount;
* instanceCreateInfo.ppEnabledExtensionNames = names;
* // fill in rest of instanceCreateInfo
*
* VkInstance instance;
* // create the Vulkan instance
* VkResult result = vkCreateInstance(&instanceCreateInfo, NULL, &instance);
* free(names);
* \endcode
*
* \sa SDL_Vulkan_CreateSurface()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_Vulkan_GetInstanceExtensions(
SDL_Window *window,
unsigned int *pCount,
const char **pNames);
/**
* \brief Create a Vulkan rendering surface for a window.
*
* \param [in] window SDL_Window to which to attach the rendering surface.
* \param [in] instance handle to the Vulkan instance to use.
* \param [out] surface pointer to a VkSurfaceKHR handle to receive the
* handle of the newly created surface.
*
* \return \c SDL_TRUE on success, \c SDL_FALSE on error.
*
* \code
* VkInstance instance;
* SDL_Window *window;
*
* // create instance and window
*
* // create the Vulkan surface
* VkSurfaceKHR surface;
* if(!SDL_Vulkan_CreateSurface(window, instance, &surface))
* handle_error();
* \endcode
*
* \note \a window should have been created with the \c SDL_WINDOW_VULKAN flag.
*
* \note \a instance should have been created with the extensions returned
* by \c SDL_Vulkan_CreateSurface() enabled.
*
* \sa SDL_Vulkan_GetInstanceExtensions()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_Vulkan_CreateSurface(
SDL_Window *window,
VkInstance instance,
VkSurfaceKHR* surface);
/**
* \brief Get the size of a window's underlying drawable in pixels (for use
* with setting viewport, scissor & etc).
*
* \param window SDL_Window from which the drawable size should be queried
* \param w Pointer to variable for storing the width in pixels,
* may be NULL
* \param h Pointer to variable for storing the height in pixels,
* may be NULL
*
* This may differ from SDL_GetWindowSize() if we're rendering to a high-DPI
* drawable, i.e. the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a
* platform with high-DPI support (Apple calls this "Retina"), and not disabled
* by the \c SDL_HINT_VIDEO_HIGHDPI_DISABLED hint.
*
* \note On macOS high-DPI support must be enabled for an application by
* setting NSHighResolutionCapable to true in its Info.plist.
*
* \sa SDL_GetWindowSize()
* \sa SDL_CreateWindow()
*/
extern DECLSPEC void SDLCALL SDL_Vulkan_GetDrawableSize(SDL_Window * window,
int *w, int *h);
/* @} *//* Vulkan support functions */
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_vulkan_h_ */
| 10,580 | C | 37.616788 | 172 | 0.693289 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_egl.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_egl.h
*
* This is a simple file to encapsulate the EGL API headers.
*/
#if !defined(_MSC_VER) && !defined(__ANDROID__)
#include <EGL/egl.h>
#include <EGL/eglext.h>
#else /* _MSC_VER */
/* EGL headers for Visual Studio */
#ifndef __khrplatform_h_
#define __khrplatform_h_
/*
** Copyright (c) 2008-2009 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Khronos platform-specific types and definitions.
*
* $Revision: 23298 $ on $Date: 2013-09-30 17:07:13 -0700 (Mon, 30 Sep 2013) $
*
* Adopters may modify this file to suit their platform. Adopters are
* encouraged to submit platform specific modifications to the Khronos
* group so that they can be included in future versions of this file.
* Please submit changes by sending them to the public Khronos Bugzilla
* (http://khronos.org/bugzilla) by filing a bug against product
* "Khronos (general)" component "Registry".
*
* A predefined template which fills in some of the bug fields can be
* reached using http://tinyurl.com/khrplatform-h-bugreport, but you
* must create a Bugzilla login first.
*
*
* See the Implementer's Guidelines for information about where this file
* should be located on your system and for more details of its use:
* http://www.khronos.org/registry/implementers_guide.pdf
*
* This file should be included as
* #include <KHR/khrplatform.h>
* by Khronos client API header files that use its types and defines.
*
* The types in khrplatform.h should only be used to define API-specific types.
*
* Types defined in khrplatform.h:
* khronos_int8_t signed 8 bit
* khronos_uint8_t unsigned 8 bit
* khronos_int16_t signed 16 bit
* khronos_uint16_t unsigned 16 bit
* khronos_int32_t signed 32 bit
* khronos_uint32_t unsigned 32 bit
* khronos_int64_t signed 64 bit
* khronos_uint64_t unsigned 64 bit
* khronos_intptr_t signed same number of bits as a pointer
* khronos_uintptr_t unsigned same number of bits as a pointer
* khronos_ssize_t signed size
* khronos_usize_t unsigned size
* khronos_float_t signed 32 bit floating point
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
* nanoseconds
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
* khronos_boolean_enum_t enumerated boolean type. This should
* only be used as a base type when a client API's boolean type is
* an enum. Client APIs which use an integer or other type for
* booleans cannot use this as the base type for their boolean.
*
* Tokens defined in khrplatform.h:
*
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
*
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
*
* Calling convention macros defined in this file:
* KHRONOS_APICALL
* KHRONOS_APIENTRY
* KHRONOS_APIATTRIBUTES
*
* These may be used in function prototypes as:
*
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
* int arg1,
* int arg2) KHRONOS_APIATTRIBUTES;
*/
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APICALL
*-------------------------------------------------------------------------
* This precedes the return type of the function in the function prototype.
*/
#if defined(_WIN32) && !defined(__SCITECH_SNAP__) && !defined(SDL_VIDEO_STATIC_ANGLE)
# define KHRONOS_APICALL __declspec(dllimport)
#elif defined (__SYMBIAN32__)
# define KHRONOS_APICALL IMPORT_C
#else
# define KHRONOS_APICALL
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIENTRY
*-------------------------------------------------------------------------
* This follows the return type of the function and precedes the function
* name in the function prototype.
*/
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
/* Win32 but not WinCE */
# define KHRONOS_APIENTRY __stdcall
#else
# define KHRONOS_APIENTRY
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIATTRIBUTES
*-------------------------------------------------------------------------
* This follows the closing parenthesis of the function prototype arguments.
*/
#if defined (__ARMCC_2__)
#define KHRONOS_APIATTRIBUTES __softfp
#else
#define KHRONOS_APIATTRIBUTES
#endif
/*-------------------------------------------------------------------------
* basic type definitions
*-----------------------------------------------------------------------*/
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
/*
* Using <stdint.h>
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__VMS ) || defined(__sgi)
/*
* Using <inttypes.h>
*/
#include <inttypes.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
/*
* Win32
*/
typedef __int32 khronos_int32_t;
typedef unsigned __int32 khronos_uint32_t;
typedef __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__sun__) || defined(__digital__)
/*
* Sun or Digital
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#if defined(__arch64__) || defined(_LP64)
typedef long int khronos_int64_t;
typedef unsigned long int khronos_uint64_t;
#else
typedef long long int khronos_int64_t;
typedef unsigned long long int khronos_uint64_t;
#endif /* __arch64__ */
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif 0
/*
* Hypothetical platform with no float or int64 support
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#define KHRONOS_SUPPORT_INT64 0
#define KHRONOS_SUPPORT_FLOAT 0
#else
/*
* Generic fallback
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#endif
/*
* Types that are (so far) the same on all platforms
*/
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
/*
* Types that differ between LLP64 and LP64 architectures - in LLP64,
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
* to be the only LLP64 architecture in current use.
*/
#ifdef _WIN64
typedef signed long long int khronos_intptr_t;
typedef unsigned long long int khronos_uintptr_t;
typedef signed long long int khronos_ssize_t;
typedef unsigned long long int khronos_usize_t;
#else
typedef signed long int khronos_intptr_t;
typedef unsigned long int khronos_uintptr_t;
typedef signed long int khronos_ssize_t;
typedef unsigned long int khronos_usize_t;
#endif
#if KHRONOS_SUPPORT_FLOAT
/*
* Float type
*/
typedef float khronos_float_t;
#endif
#if KHRONOS_SUPPORT_INT64
/* Time types
*
* These types can be used to represent a time interval in nanoseconds or
* an absolute Unadjusted System Time. Unadjusted System Time is the number
* of nanoseconds since some arbitrary system event (e.g. since the last
* time the system booted). The Unadjusted System Time is an unsigned
* 64 bit value that wraps back to 0 every 584 years. Time intervals
* may be either signed or unsigned.
*/
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
typedef khronos_int64_t khronos_stime_nanoseconds_t;
#endif
/*
* Dummy value used to pad enum types to 32 bits.
*/
#ifndef KHRONOS_MAX_ENUM
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
#endif
/*
* Enumerated boolean type
*
* Values other than zero should be considered to be true. Therefore
* comparisons should not be made against KHRONOS_TRUE.
*/
typedef enum {
KHRONOS_FALSE = 0,
KHRONOS_TRUE = 1,
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
} khronos_boolean_enum_t;
#endif /* __khrplatform_h_ */
#ifndef __eglplatform_h_
#define __eglplatform_h_
/*
** Copyright (c) 2007-2009 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Platform-specific types and definitions for egl.h
* $Revision: 12306 $ on $Date: 2010-08-25 09:51:28 -0700 (Wed, 25 Aug 2010) $
*
* Adopters may modify khrplatform.h and this file to suit their platform.
* You are encouraged to submit all modifications to the Khronos group so that
* they can be included in future versions of this file. Please submit changes
* by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla)
* by filing a bug against product "EGL" component "Registry".
*/
/*#include <KHR/khrplatform.h>*/
/* Macros used in EGL function prototype declarations.
*
* EGL functions should be prototyped as:
*
* EGLAPI return-type EGLAPIENTRY eglFunction(arguments);
* typedef return-type (EXPAPIENTRYP PFNEGLFUNCTIONPROC) (arguments);
*
* KHRONOS_APICALL and KHRONOS_APIENTRY are defined in KHR/khrplatform.h
*/
#ifndef EGLAPI
#define EGLAPI KHRONOS_APICALL
#endif
#ifndef EGLAPIENTRY
#define EGLAPIENTRY KHRONOS_APIENTRY
#endif
#define EGLAPIENTRYP EGLAPIENTRY*
/* The types NativeDisplayType, NativeWindowType, and NativePixmapType
* are aliases of window-system-dependent types, such as X Display * or
* Windows Device Context. They must be defined in platform-specific
* code below. The EGL-prefixed versions of Native*Type are the same
* types, renamed in EGL 1.3 so all types in the API start with "EGL".
*
* Khronos STRONGLY RECOMMENDS that you use the default definitions
* provided below, since these changes affect both binary and source
* portability of applications using EGL running on different EGL
* implementations.
*/
#if defined(_WIN32) || defined(__VC32__) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) /* Win32 and WinCE */
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
#if __WINRT__
#include <Unknwn.h>
typedef IUnknown * EGLNativeWindowType;
typedef IUnknown * EGLNativePixmapType;
typedef IUnknown * EGLNativeDisplayType;
#else
typedef HDC EGLNativeDisplayType;
typedef HBITMAP EGLNativePixmapType;
typedef HWND EGLNativeWindowType;
#endif
#elif defined(__WINSCW__) || defined(__SYMBIAN32__) /* Symbian */
typedef int EGLNativeDisplayType;
typedef void *EGLNativeWindowType;
typedef void *EGLNativePixmapType;
#elif defined(WL_EGL_PLATFORM)
typedef struct wl_display *EGLNativeDisplayType;
typedef struct wl_egl_pixmap *EGLNativePixmapType;
typedef struct wl_egl_window *EGLNativeWindowType;
#elif defined(__GBM__)
typedef struct gbm_device *EGLNativeDisplayType;
typedef struct gbm_bo *EGLNativePixmapType;
typedef void *EGLNativeWindowType;
#elif defined(__ANDROID__) /* Android */
struct ANativeWindow;
struct egl_native_pixmap_t;
typedef struct ANativeWindow *EGLNativeWindowType;
typedef struct egl_native_pixmap_t *EGLNativePixmapType;
typedef void *EGLNativeDisplayType;
#elif defined(MIR_EGL_PLATFORM)
#include <mir_toolkit/mir_client_library.h>
typedef MirEGLNativeDisplayType EGLNativeDisplayType;
typedef void *EGLNativePixmapType;
typedef MirEGLNativeWindowType EGLNativeWindowType;
#elif defined(__unix__)
#ifdef MESA_EGL_NO_X11_HEADERS
typedef void *EGLNativeDisplayType;
typedef khronos_uintptr_t EGLNativePixmapType;
typedef khronos_uintptr_t EGLNativeWindowType;
#else
/* X11 (tentative) */
#include <X11/Xlib.h>
#include <X11/Xutil.h>
typedef Display *EGLNativeDisplayType;
typedef Pixmap EGLNativePixmapType;
typedef Window EGLNativeWindowType;
#endif /* MESA_EGL_NO_X11_HEADERS */
#else
#error "Platform not recognized"
#endif
/* EGL 1.2 types, renamed for consistency in EGL 1.3 */
typedef EGLNativeDisplayType NativeDisplayType;
typedef EGLNativePixmapType NativePixmapType;
typedef EGLNativeWindowType NativeWindowType;
/* Define EGLint. This must be a signed integral type large enough to contain
* all legal attribute names and values passed into and out of EGL, whether
* their type is boolean, bitmask, enumerant (symbolic constant), integer,
* handle, or other. While in general a 32-bit integer will suffice, if
* handles are 64 bit types, then EGLint should be defined as a signed 64-bit
* integer type.
*/
typedef khronos_int32_t EGLint;
#endif /* __eglplatform_h */
#ifndef __egl_h_
#define __egl_h_ 1
#ifdef __cplusplus
extern "C" {
#endif
/*
** Copyright (c) 2013-2015 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/*
** This header is generated from the Khronos OpenGL / OpenGL ES XML
** API Registry. The current version of the Registry, generator scripts
** used to make the header, and the header can be found at
** http://www.opengl.org/registry/
**
** Khronos $Revision: 31566 $ on $Date: 2015-06-23 08:48:48 -0700 (Tue, 23 Jun 2015) $
*/
/*#include <EGL/eglplatform.h>*/
/* Generated on date 20150623 */
/* Generated C header for:
* API: egl
* Versions considered: .*
* Versions emitted: .*
* Default extensions included: None
* Additional extensions included: _nomatch_^
* Extensions removed: _nomatch_^
*/
#ifndef EGL_VERSION_1_0
#define EGL_VERSION_1_0 1
typedef unsigned int EGLBoolean;
typedef void *EGLDisplay;
typedef void *EGLConfig;
typedef void *EGLSurface;
typedef void *EGLContext;
typedef void (*__eglMustCastToProperFunctionPointerType)(void);
#define EGL_ALPHA_SIZE 0x3021
#define EGL_BAD_ACCESS 0x3002
#define EGL_BAD_ALLOC 0x3003
#define EGL_BAD_ATTRIBUTE 0x3004
#define EGL_BAD_CONFIG 0x3005
#define EGL_BAD_CONTEXT 0x3006
#define EGL_BAD_CURRENT_SURFACE 0x3007
#define EGL_BAD_DISPLAY 0x3008
#define EGL_BAD_MATCH 0x3009
#define EGL_BAD_NATIVE_PIXMAP 0x300A
#define EGL_BAD_NATIVE_WINDOW 0x300B
#define EGL_BAD_PARAMETER 0x300C
#define EGL_BAD_SURFACE 0x300D
#define EGL_BLUE_SIZE 0x3022
#define EGL_BUFFER_SIZE 0x3020
#define EGL_CONFIG_CAVEAT 0x3027
#define EGL_CONFIG_ID 0x3028
#define EGL_CORE_NATIVE_ENGINE 0x305B
#define EGL_DEPTH_SIZE 0x3025
#define EGL_DONT_CARE ((EGLint)-1)
#define EGL_DRAW 0x3059
#define EGL_EXTENSIONS 0x3055
#define EGL_FALSE 0
#define EGL_GREEN_SIZE 0x3023
#define EGL_HEIGHT 0x3056
#define EGL_LARGEST_PBUFFER 0x3058
#define EGL_LEVEL 0x3029
#define EGL_MAX_PBUFFER_HEIGHT 0x302A
#define EGL_MAX_PBUFFER_PIXELS 0x302B
#define EGL_MAX_PBUFFER_WIDTH 0x302C
#define EGL_NATIVE_RENDERABLE 0x302D
#define EGL_NATIVE_VISUAL_ID 0x302E
#define EGL_NATIVE_VISUAL_TYPE 0x302F
#define EGL_NONE 0x3038
#define EGL_NON_CONFORMANT_CONFIG 0x3051
#define EGL_NOT_INITIALIZED 0x3001
#define EGL_NO_CONTEXT ((EGLContext)0)
#define EGL_NO_DISPLAY ((EGLDisplay)0)
#define EGL_NO_SURFACE ((EGLSurface)0)
#define EGL_PBUFFER_BIT 0x0001
#define EGL_PIXMAP_BIT 0x0002
#define EGL_READ 0x305A
#define EGL_RED_SIZE 0x3024
#define EGL_SAMPLES 0x3031
#define EGL_SAMPLE_BUFFERS 0x3032
#define EGL_SLOW_CONFIG 0x3050
#define EGL_STENCIL_SIZE 0x3026
#define EGL_SUCCESS 0x3000
#define EGL_SURFACE_TYPE 0x3033
#define EGL_TRANSPARENT_BLUE_VALUE 0x3035
#define EGL_TRANSPARENT_GREEN_VALUE 0x3036
#define EGL_TRANSPARENT_RED_VALUE 0x3037
#define EGL_TRANSPARENT_RGB 0x3052
#define EGL_TRANSPARENT_TYPE 0x3034
#define EGL_TRUE 1
#define EGL_VENDOR 0x3053
#define EGL_VERSION 0x3054
#define EGL_WIDTH 0x3057
#define EGL_WINDOW_BIT 0x0004
EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig (EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config);
EGLAPI EGLBoolean EGLAPIENTRY eglCopyBuffers (EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target);
EGLAPI EGLContext EGLAPIENTRY eglCreateContext (EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface (EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurface (EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreateWindowSurface (EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroyContext (EGLDisplay dpy, EGLContext ctx);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroySurface (EGLDisplay dpy, EGLSurface surface);
EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigAttrib (EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value);
EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigs (EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config);
EGLAPI EGLDisplay EGLAPIENTRY eglGetCurrentDisplay (void);
EGLAPI EGLSurface EGLAPIENTRY eglGetCurrentSurface (EGLint readdraw);
EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay (EGLNativeDisplayType display_id);
EGLAPI EGLint EGLAPIENTRY eglGetError (void);
EGLAPI __eglMustCastToProperFunctionPointerType EGLAPIENTRY eglGetProcAddress (const char *procname);
EGLAPI EGLBoolean EGLAPIENTRY eglInitialize (EGLDisplay dpy, EGLint *major, EGLint *minor);
EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent (EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
EGLAPI EGLBoolean EGLAPIENTRY eglQueryContext (EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint *value);
EGLAPI const char *EGLAPIENTRY eglQueryString (EGLDisplay dpy, EGLint name);
EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value);
EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers (EGLDisplay dpy, EGLSurface surface);
EGLAPI EGLBoolean EGLAPIENTRY eglTerminate (EGLDisplay dpy);
EGLAPI EGLBoolean EGLAPIENTRY eglWaitGL (void);
EGLAPI EGLBoolean EGLAPIENTRY eglWaitNative (EGLint engine);
#endif /* EGL_VERSION_1_0 */
#ifndef EGL_VERSION_1_1
#define EGL_VERSION_1_1 1
#define EGL_BACK_BUFFER 0x3084
#define EGL_BIND_TO_TEXTURE_RGB 0x3039
#define EGL_BIND_TO_TEXTURE_RGBA 0x303A
#define EGL_CONTEXT_LOST 0x300E
#define EGL_MIN_SWAP_INTERVAL 0x303B
#define EGL_MAX_SWAP_INTERVAL 0x303C
#define EGL_MIPMAP_TEXTURE 0x3082
#define EGL_MIPMAP_LEVEL 0x3083
#define EGL_NO_TEXTURE 0x305C
#define EGL_TEXTURE_2D 0x305F
#define EGL_TEXTURE_FORMAT 0x3080
#define EGL_TEXTURE_RGB 0x305D
#define EGL_TEXTURE_RGBA 0x305E
#define EGL_TEXTURE_TARGET 0x3081
EGLAPI EGLBoolean EGLAPIENTRY eglBindTexImage (EGLDisplay dpy, EGLSurface surface, EGLint buffer);
EGLAPI EGLBoolean EGLAPIENTRY eglReleaseTexImage (EGLDisplay dpy, EGLSurface surface, EGLint buffer);
EGLAPI EGLBoolean EGLAPIENTRY eglSurfaceAttrib (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value);
EGLAPI EGLBoolean EGLAPIENTRY eglSwapInterval (EGLDisplay dpy, EGLint interval);
#endif /* EGL_VERSION_1_1 */
#ifndef EGL_VERSION_1_2
#define EGL_VERSION_1_2 1
typedef unsigned int EGLenum;
typedef void *EGLClientBuffer;
#define EGL_ALPHA_FORMAT 0x3088
#define EGL_ALPHA_FORMAT_NONPRE 0x308B
#define EGL_ALPHA_FORMAT_PRE 0x308C
#define EGL_ALPHA_MASK_SIZE 0x303E
#define EGL_BUFFER_PRESERVED 0x3094
#define EGL_BUFFER_DESTROYED 0x3095
#define EGL_CLIENT_APIS 0x308D
#define EGL_COLORSPACE 0x3087
#define EGL_COLORSPACE_sRGB 0x3089
#define EGL_COLORSPACE_LINEAR 0x308A
#define EGL_COLOR_BUFFER_TYPE 0x303F
#define EGL_CONTEXT_CLIENT_TYPE 0x3097
#define EGL_DISPLAY_SCALING 10000
#define EGL_HORIZONTAL_RESOLUTION 0x3090
#define EGL_LUMINANCE_BUFFER 0x308F
#define EGL_LUMINANCE_SIZE 0x303D
#define EGL_OPENGL_ES_BIT 0x0001
#define EGL_OPENVG_BIT 0x0002
#define EGL_OPENGL_ES_API 0x30A0
#define EGL_OPENVG_API 0x30A1
#define EGL_OPENVG_IMAGE 0x3096
#define EGL_PIXEL_ASPECT_RATIO 0x3092
#define EGL_RENDERABLE_TYPE 0x3040
#define EGL_RENDER_BUFFER 0x3086
#define EGL_RGB_BUFFER 0x308E
#define EGL_SINGLE_BUFFER 0x3085
#define EGL_SWAP_BEHAVIOR 0x3093
#define EGL_UNKNOWN ((EGLint)-1)
#define EGL_VERTICAL_RESOLUTION 0x3091
EGLAPI EGLBoolean EGLAPIENTRY eglBindAPI (EGLenum api);
EGLAPI EGLenum EGLAPIENTRY eglQueryAPI (void);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer (EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglReleaseThread (void);
EGLAPI EGLBoolean EGLAPIENTRY eglWaitClient (void);
#endif /* EGL_VERSION_1_2 */
#ifndef EGL_VERSION_1_3
#define EGL_VERSION_1_3 1
#define EGL_CONFORMANT 0x3042
#define EGL_CONTEXT_CLIENT_VERSION 0x3098
#define EGL_MATCH_NATIVE_PIXMAP 0x3041
#define EGL_OPENGL_ES2_BIT 0x0004
#define EGL_VG_ALPHA_FORMAT 0x3088
#define EGL_VG_ALPHA_FORMAT_NONPRE 0x308B
#define EGL_VG_ALPHA_FORMAT_PRE 0x308C
#define EGL_VG_ALPHA_FORMAT_PRE_BIT 0x0040
#define EGL_VG_COLORSPACE 0x3087
#define EGL_VG_COLORSPACE_sRGB 0x3089
#define EGL_VG_COLORSPACE_LINEAR 0x308A
#define EGL_VG_COLORSPACE_LINEAR_BIT 0x0020
#endif /* EGL_VERSION_1_3 */
#ifndef EGL_VERSION_1_4
#define EGL_VERSION_1_4 1
#define EGL_DEFAULT_DISPLAY ((EGLNativeDisplayType)0)
#define EGL_MULTISAMPLE_RESOLVE_BOX_BIT 0x0200
#define EGL_MULTISAMPLE_RESOLVE 0x3099
#define EGL_MULTISAMPLE_RESOLVE_DEFAULT 0x309A
#define EGL_MULTISAMPLE_RESOLVE_BOX 0x309B
#define EGL_OPENGL_API 0x30A2
#define EGL_OPENGL_BIT 0x0008
#define EGL_SWAP_BEHAVIOR_PRESERVED_BIT 0x0400
EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext (void);
#endif /* EGL_VERSION_1_4 */
#ifndef EGL_VERSION_1_5
#define EGL_VERSION_1_5 1
typedef void *EGLSync;
typedef intptr_t EGLAttrib;
typedef khronos_utime_nanoseconds_t EGLTime;
typedef void *EGLImage;
#define EGL_CONTEXT_MAJOR_VERSION 0x3098
#define EGL_CONTEXT_MINOR_VERSION 0x30FB
#define EGL_CONTEXT_OPENGL_PROFILE_MASK 0x30FD
#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY 0x31BD
#define EGL_NO_RESET_NOTIFICATION 0x31BE
#define EGL_LOSE_CONTEXT_ON_RESET 0x31BF
#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT 0x00000001
#define EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT 0x00000002
#define EGL_CONTEXT_OPENGL_DEBUG 0x31B0
#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE 0x31B1
#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS 0x31B2
#define EGL_OPENGL_ES3_BIT 0x00000040
#define EGL_CL_EVENT_HANDLE 0x309C
#define EGL_SYNC_CL_EVENT 0x30FE
#define EGL_SYNC_CL_EVENT_COMPLETE 0x30FF
#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE 0x30F0
#define EGL_SYNC_TYPE 0x30F7
#define EGL_SYNC_STATUS 0x30F1
#define EGL_SYNC_CONDITION 0x30F8
#define EGL_SIGNALED 0x30F2
#define EGL_UNSIGNALED 0x30F3
#define EGL_SYNC_FLUSH_COMMANDS_BIT 0x0001
#define EGL_FOREVER 0xFFFFFFFFFFFFFFFFull
#define EGL_TIMEOUT_EXPIRED 0x30F5
#define EGL_CONDITION_SATISFIED 0x30F6
#define EGL_NO_SYNC ((EGLSync)0)
#define EGL_SYNC_FENCE 0x30F9
#define EGL_GL_COLORSPACE 0x309D
#define EGL_GL_COLORSPACE_SRGB 0x3089
#define EGL_GL_COLORSPACE_LINEAR 0x308A
#define EGL_GL_RENDERBUFFER 0x30B9
#define EGL_GL_TEXTURE_2D 0x30B1
#define EGL_GL_TEXTURE_LEVEL 0x30BC
#define EGL_GL_TEXTURE_3D 0x30B2
#define EGL_GL_TEXTURE_ZOFFSET 0x30BD
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x30B3
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x30B4
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x30B5
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x30B6
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x30B7
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x30B8
#define EGL_IMAGE_PRESERVED 0x30D2
#define EGL_NO_IMAGE ((EGLImage)0)
EGLAPI EGLSync EGLAPIENTRY eglCreateSync (EGLDisplay dpy, EGLenum type, const EGLAttrib *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroySync (EGLDisplay dpy, EGLSync sync);
EGLAPI EGLint EGLAPIENTRY eglClientWaitSync (EGLDisplay dpy, EGLSync sync, EGLint flags, EGLTime timeout);
EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttrib (EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLAttrib *value);
EGLAPI EGLImage EGLAPIENTRY eglCreateImage (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLAttrib *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImage (EGLDisplay dpy, EGLImage image);
EGLAPI EGLDisplay EGLAPIENTRY eglGetPlatformDisplay (EGLenum platform, void *native_display, const EGLAttrib *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformWindowSurface (EGLDisplay dpy, EGLConfig config, void *native_window, const EGLAttrib *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformPixmapSurface (EGLDisplay dpy, EGLConfig config, void *native_pixmap, const EGLAttrib *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglWaitSync (EGLDisplay dpy, EGLSync sync, EGLint flags);
#endif /* EGL_VERSION_1_5 */
#ifdef __cplusplus
}
#endif
#endif /* __egl_h_ */
#ifndef __eglext_h_
#define __eglext_h_ 1
#ifdef __cplusplus
extern "C" {
#endif
/*
** Copyright (c) 2013-2015 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/*
** This header is generated from the Khronos OpenGL / OpenGL ES XML
** API Registry. The current version of the Registry, generator scripts
** used to make the header, and the header can be found at
** http://www.opengl.org/registry/
**
** Khronos $Revision: 31566 $ on $Date: 2015-06-23 08:48:48 -0700 (Tue, 23 Jun 2015) $
*/
/*#include <EGL/eglplatform.h>*/
#define EGL_EGLEXT_VERSION 20150623
/* Generated C header for:
* API: egl
* Versions considered: .*
* Versions emitted: _nomatch_^
* Default extensions included: egl
* Additional extensions included: _nomatch_^
* Extensions removed: _nomatch_^
*/
#ifndef EGL_KHR_cl_event
#define EGL_KHR_cl_event 1
#define EGL_CL_EVENT_HANDLE_KHR 0x309C
#define EGL_SYNC_CL_EVENT_KHR 0x30FE
#define EGL_SYNC_CL_EVENT_COMPLETE_KHR 0x30FF
#endif /* EGL_KHR_cl_event */
#ifndef EGL_KHR_cl_event2
#define EGL_KHR_cl_event2 1
typedef void *EGLSyncKHR;
typedef intptr_t EGLAttribKHR;
typedef EGLSyncKHR (EGLAPIENTRYP PFNEGLCREATESYNC64KHRPROC) (EGLDisplay dpy, EGLenum type, const EGLAttribKHR *attrib_list);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateSync64KHR (EGLDisplay dpy, EGLenum type, const EGLAttribKHR *attrib_list);
#endif
#endif /* EGL_KHR_cl_event2 */
#ifndef EGL_KHR_client_get_all_proc_addresses
#define EGL_KHR_client_get_all_proc_addresses 1
#endif /* EGL_KHR_client_get_all_proc_addresses */
#ifndef EGL_KHR_config_attribs
#define EGL_KHR_config_attribs 1
#define EGL_CONFORMANT_KHR 0x3042
#define EGL_VG_COLORSPACE_LINEAR_BIT_KHR 0x0020
#define EGL_VG_ALPHA_FORMAT_PRE_BIT_KHR 0x0040
#endif /* EGL_KHR_config_attribs */
#ifndef EGL_KHR_create_context
#define EGL_KHR_create_context 1
#define EGL_CONTEXT_MAJOR_VERSION_KHR 0x3098
#define EGL_CONTEXT_MINOR_VERSION_KHR 0x30FB
#define EGL_CONTEXT_FLAGS_KHR 0x30FC
#define EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR 0x30FD
#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR 0x31BD
#define EGL_NO_RESET_NOTIFICATION_KHR 0x31BE
#define EGL_LOSE_CONTEXT_ON_RESET_KHR 0x31BF
#define EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR 0x00000001
#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR 0x00000002
#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR 0x00000004
#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR 0x00000001
#define EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR 0x00000002
#define EGL_OPENGL_ES3_BIT_KHR 0x00000040
#endif /* EGL_KHR_create_context */
#ifndef EGL_KHR_create_context_no_error
#define EGL_KHR_create_context_no_error 1
#define EGL_CONTEXT_OPENGL_NO_ERROR_KHR 0x31B3
#endif /* EGL_KHR_create_context_no_error */
#ifndef EGL_KHR_fence_sync
#define EGL_KHR_fence_sync 1
typedef khronos_utime_nanoseconds_t EGLTimeKHR;
#ifdef KHRONOS_SUPPORT_INT64
#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE_KHR 0x30F0
#define EGL_SYNC_CONDITION_KHR 0x30F8
#define EGL_SYNC_FENCE_KHR 0x30F9
typedef EGLSyncKHR (EGLAPIENTRYP PFNEGLCREATESYNCKHRPROC) (EGLDisplay dpy, EGLenum type, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync);
typedef EGLint (EGLAPIENTRYP PFNEGLCLIENTWAITSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateSyncKHR (EGLDisplay dpy, EGLenum type, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroySyncKHR (EGLDisplay dpy, EGLSyncKHR sync);
EGLAPI EGLint EGLAPIENTRY eglClientWaitSyncKHR (EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout);
EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttribKHR (EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value);
#endif
#endif /* KHRONOS_SUPPORT_INT64 */
#endif /* EGL_KHR_fence_sync */
#ifndef EGL_KHR_get_all_proc_addresses
#define EGL_KHR_get_all_proc_addresses 1
#endif /* EGL_KHR_get_all_proc_addresses */
#ifndef EGL_KHR_gl_colorspace
#define EGL_KHR_gl_colorspace 1
#define EGL_GL_COLORSPACE_KHR 0x309D
#define EGL_GL_COLORSPACE_SRGB_KHR 0x3089
#define EGL_GL_COLORSPACE_LINEAR_KHR 0x308A
#endif /* EGL_KHR_gl_colorspace */
#ifndef EGL_KHR_gl_renderbuffer_image
#define EGL_KHR_gl_renderbuffer_image 1
#define EGL_GL_RENDERBUFFER_KHR 0x30B9
#endif /* EGL_KHR_gl_renderbuffer_image */
#ifndef EGL_KHR_gl_texture_2D_image
#define EGL_KHR_gl_texture_2D_image 1
#define EGL_GL_TEXTURE_2D_KHR 0x30B1
#define EGL_GL_TEXTURE_LEVEL_KHR 0x30BC
#endif /* EGL_KHR_gl_texture_2D_image */
#ifndef EGL_KHR_gl_texture_3D_image
#define EGL_KHR_gl_texture_3D_image 1
#define EGL_GL_TEXTURE_3D_KHR 0x30B2
#define EGL_GL_TEXTURE_ZOFFSET_KHR 0x30BD
#endif /* EGL_KHR_gl_texture_3D_image */
#ifndef EGL_KHR_gl_texture_cubemap_image
#define EGL_KHR_gl_texture_cubemap_image 1
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR 0x30B3
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR 0x30B4
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR 0x30B5
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR 0x30B6
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR 0x30B7
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR 0x30B8
#endif /* EGL_KHR_gl_texture_cubemap_image */
#ifndef EGL_KHR_image
#define EGL_KHR_image 1
typedef void *EGLImageKHR;
#define EGL_NATIVE_PIXMAP_KHR 0x30B0
#define EGL_NO_IMAGE_KHR ((EGLImageKHR)0)
typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLImageKHR EGLAPIENTRY eglCreateImageKHR (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImageKHR (EGLDisplay dpy, EGLImageKHR image);
#endif
#endif /* EGL_KHR_image */
#ifndef EGL_KHR_image_base
#define EGL_KHR_image_base 1
#define EGL_IMAGE_PRESERVED_KHR 0x30D2
#endif /* EGL_KHR_image_base */
#ifndef EGL_KHR_image_pixmap
#define EGL_KHR_image_pixmap 1
#endif /* EGL_KHR_image_pixmap */
#ifndef EGL_KHR_lock_surface
#define EGL_KHR_lock_surface 1
#define EGL_READ_SURFACE_BIT_KHR 0x0001
#define EGL_WRITE_SURFACE_BIT_KHR 0x0002
#define EGL_LOCK_SURFACE_BIT_KHR 0x0080
#define EGL_OPTIMAL_FORMAT_BIT_KHR 0x0100
#define EGL_MATCH_FORMAT_KHR 0x3043
#define EGL_FORMAT_RGB_565_EXACT_KHR 0x30C0
#define EGL_FORMAT_RGB_565_KHR 0x30C1
#define EGL_FORMAT_RGBA_8888_EXACT_KHR 0x30C2
#define EGL_FORMAT_RGBA_8888_KHR 0x30C3
#define EGL_MAP_PRESERVE_PIXELS_KHR 0x30C4
#define EGL_LOCK_USAGE_HINT_KHR 0x30C5
#define EGL_BITMAP_POINTER_KHR 0x30C6
#define EGL_BITMAP_PITCH_KHR 0x30C7
#define EGL_BITMAP_ORIGIN_KHR 0x30C8
#define EGL_BITMAP_PIXEL_RED_OFFSET_KHR 0x30C9
#define EGL_BITMAP_PIXEL_GREEN_OFFSET_KHR 0x30CA
#define EGL_BITMAP_PIXEL_BLUE_OFFSET_KHR 0x30CB
#define EGL_BITMAP_PIXEL_ALPHA_OFFSET_KHR 0x30CC
#define EGL_BITMAP_PIXEL_LUMINANCE_OFFSET_KHR 0x30CD
#define EGL_LOWER_LEFT_KHR 0x30CE
#define EGL_UPPER_LEFT_KHR 0x30CF
typedef EGLBoolean (EGLAPIENTRYP PFNEGLLOCKSURFACEKHRPROC) (EGLDisplay dpy, EGLSurface surface, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNLOCKSURFACEKHRPROC) (EGLDisplay dpy, EGLSurface surface);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglLockSurfaceKHR (EGLDisplay dpy, EGLSurface surface, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglUnlockSurfaceKHR (EGLDisplay dpy, EGLSurface surface);
#endif
#endif /* EGL_KHR_lock_surface */
#ifndef EGL_KHR_lock_surface2
#define EGL_KHR_lock_surface2 1
#define EGL_BITMAP_PIXEL_SIZE_KHR 0x3110
#endif /* EGL_KHR_lock_surface2 */
#ifndef EGL_KHR_lock_surface3
#define EGL_KHR_lock_surface3 1
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSURFACE64KHRPROC) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLAttribKHR *value);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface64KHR (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLAttribKHR *value);
#endif
#endif /* EGL_KHR_lock_surface3 */
#ifndef EGL_KHR_partial_update
#define EGL_KHR_partial_update 1
#define EGL_BUFFER_AGE_KHR 0x313D
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSETDAMAGEREGIONKHRPROC) (EGLDisplay dpy, EGLSurface surface, EGLint *rects, EGLint n_rects);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglSetDamageRegionKHR (EGLDisplay dpy, EGLSurface surface, EGLint *rects, EGLint n_rects);
#endif
#endif /* EGL_KHR_partial_update */
#ifndef EGL_KHR_platform_android
#define EGL_KHR_platform_android 1
#define EGL_PLATFORM_ANDROID_KHR 0x3141
#endif /* EGL_KHR_platform_android */
#ifndef EGL_KHR_platform_gbm
#define EGL_KHR_platform_gbm 1
#define EGL_PLATFORM_GBM_KHR 0x31D7
#endif /* EGL_KHR_platform_gbm */
#ifndef EGL_KHR_platform_wayland
#define EGL_KHR_platform_wayland 1
#define EGL_PLATFORM_WAYLAND_KHR 0x31D8
#endif /* EGL_KHR_platform_wayland */
#ifndef EGL_KHR_platform_x11
#define EGL_KHR_platform_x11 1
#define EGL_PLATFORM_X11_KHR 0x31D5
#define EGL_PLATFORM_X11_SCREEN_KHR 0x31D6
#endif /* EGL_KHR_platform_x11 */
#ifndef EGL_KHR_reusable_sync
#define EGL_KHR_reusable_sync 1
#ifdef KHRONOS_SUPPORT_INT64
#define EGL_SYNC_STATUS_KHR 0x30F1
#define EGL_SIGNALED_KHR 0x30F2
#define EGL_UNSIGNALED_KHR 0x30F3
#define EGL_TIMEOUT_EXPIRED_KHR 0x30F5
#define EGL_CONDITION_SATISFIED_KHR 0x30F6
#define EGL_SYNC_TYPE_KHR 0x30F7
#define EGL_SYNC_REUSABLE_KHR 0x30FA
#define EGL_SYNC_FLUSH_COMMANDS_BIT_KHR 0x0001
#define EGL_FOREVER_KHR 0xFFFFFFFFFFFFFFFFull
#define EGL_NO_SYNC_KHR ((EGLSyncKHR)0)
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSIGNALSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglSignalSyncKHR (EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode);
#endif
#endif /* KHRONOS_SUPPORT_INT64 */
#endif /* EGL_KHR_reusable_sync */
#ifndef EGL_KHR_stream
#define EGL_KHR_stream 1
typedef void *EGLStreamKHR;
typedef khronos_uint64_t EGLuint64KHR;
#ifdef KHRONOS_SUPPORT_INT64
#define EGL_NO_STREAM_KHR ((EGLStreamKHR)0)
#define EGL_CONSUMER_LATENCY_USEC_KHR 0x3210
#define EGL_PRODUCER_FRAME_KHR 0x3212
#define EGL_CONSUMER_FRAME_KHR 0x3213
#define EGL_STREAM_STATE_KHR 0x3214
#define EGL_STREAM_STATE_CREATED_KHR 0x3215
#define EGL_STREAM_STATE_CONNECTING_KHR 0x3216
#define EGL_STREAM_STATE_EMPTY_KHR 0x3217
#define EGL_STREAM_STATE_NEW_FRAME_AVAILABLE_KHR 0x3218
#define EGL_STREAM_STATE_OLD_FRAME_AVAILABLE_KHR 0x3219
#define EGL_STREAM_STATE_DISCONNECTED_KHR 0x321A
#define EGL_BAD_STREAM_KHR 0x321B
#define EGL_BAD_STATE_KHR 0x321C
typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMKHRPROC) (EGLDisplay dpy, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSTREAMKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMATTRIBKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint value);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint *value);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMU64KHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLuint64KHR *value);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLStreamKHR EGLAPIENTRY eglCreateStreamKHR (EGLDisplay dpy, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroyStreamKHR (EGLDisplay dpy, EGLStreamKHR stream);
EGLAPI EGLBoolean EGLAPIENTRY eglStreamAttribKHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint value);
EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamKHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint *value);
EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamu64KHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLuint64KHR *value);
#endif
#endif /* KHRONOS_SUPPORT_INT64 */
#endif /* EGL_KHR_stream */
#ifndef EGL_KHR_stream_consumer_gltexture
#define EGL_KHR_stream_consumer_gltexture 1
#ifdef EGL_KHR_stream
#define EGL_CONSUMER_ACQUIRE_TIMEOUT_USEC_KHR 0x321E
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERACQUIREKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERRELEASEKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerGLTextureExternalKHR (EGLDisplay dpy, EGLStreamKHR stream);
EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerAcquireKHR (EGLDisplay dpy, EGLStreamKHR stream);
EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerReleaseKHR (EGLDisplay dpy, EGLStreamKHR stream);
#endif
#endif /* EGL_KHR_stream */
#endif /* EGL_KHR_stream_consumer_gltexture */
#ifndef EGL_KHR_stream_cross_process_fd
#define EGL_KHR_stream_cross_process_fd 1
typedef int EGLNativeFileDescriptorKHR;
#ifdef EGL_KHR_stream
#define EGL_NO_FILE_DESCRIPTOR_KHR ((EGLNativeFileDescriptorKHR)(-1))
typedef EGLNativeFileDescriptorKHR (EGLAPIENTRYP PFNEGLGETSTREAMFILEDESCRIPTORKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream);
typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMFROMFILEDESCRIPTORKHRPROC) (EGLDisplay dpy, EGLNativeFileDescriptorKHR file_descriptor);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLNativeFileDescriptorKHR EGLAPIENTRY eglGetStreamFileDescriptorKHR (EGLDisplay dpy, EGLStreamKHR stream);
EGLAPI EGLStreamKHR EGLAPIENTRY eglCreateStreamFromFileDescriptorKHR (EGLDisplay dpy, EGLNativeFileDescriptorKHR file_descriptor);
#endif
#endif /* EGL_KHR_stream */
#endif /* EGL_KHR_stream_cross_process_fd */
#ifndef EGL_KHR_stream_fifo
#define EGL_KHR_stream_fifo 1
#ifdef EGL_KHR_stream
#define EGL_STREAM_FIFO_LENGTH_KHR 0x31FC
#define EGL_STREAM_TIME_NOW_KHR 0x31FD
#define EGL_STREAM_TIME_CONSUMER_KHR 0x31FE
#define EGL_STREAM_TIME_PRODUCER_KHR 0x31FF
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMTIMEKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLTimeKHR *value);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamTimeKHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLTimeKHR *value);
#endif
#endif /* EGL_KHR_stream */
#endif /* EGL_KHR_stream_fifo */
#ifndef EGL_KHR_stream_producer_aldatalocator
#define EGL_KHR_stream_producer_aldatalocator 1
#ifdef EGL_KHR_stream
#endif /* EGL_KHR_stream */
#endif /* EGL_KHR_stream_producer_aldatalocator */
#ifndef EGL_KHR_stream_producer_eglsurface
#define EGL_KHR_stream_producer_eglsurface 1
#ifdef EGL_KHR_stream
#define EGL_STREAM_BIT_KHR 0x0800
typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATESTREAMPRODUCERSURFACEKHRPROC) (EGLDisplay dpy, EGLConfig config, EGLStreamKHR stream, const EGLint *attrib_list);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLSurface EGLAPIENTRY eglCreateStreamProducerSurfaceKHR (EGLDisplay dpy, EGLConfig config, EGLStreamKHR stream, const EGLint *attrib_list);
#endif
#endif /* EGL_KHR_stream */
#endif /* EGL_KHR_stream_producer_eglsurface */
#ifndef EGL_KHR_surfaceless_context
#define EGL_KHR_surfaceless_context 1
#endif /* EGL_KHR_surfaceless_context */
#ifndef EGL_KHR_swap_buffers_with_damage
#define EGL_KHR_swap_buffers_with_damage 1
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSWITHDAMAGEKHRPROC) (EGLDisplay dpy, EGLSurface surface, EGLint *rects, EGLint n_rects);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffersWithDamageKHR (EGLDisplay dpy, EGLSurface surface, EGLint *rects, EGLint n_rects);
#endif
#endif /* EGL_KHR_swap_buffers_with_damage */
#ifndef EGL_KHR_vg_parent_image
#define EGL_KHR_vg_parent_image 1
#define EGL_VG_PARENT_IMAGE_KHR 0x30BA
#endif /* EGL_KHR_vg_parent_image */
#ifndef EGL_KHR_wait_sync
#define EGL_KHR_wait_sync 1
typedef EGLint (EGLAPIENTRYP PFNEGLWAITSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLint flags);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLint EGLAPIENTRY eglWaitSyncKHR (EGLDisplay dpy, EGLSyncKHR sync, EGLint flags);
#endif
#endif /* EGL_KHR_wait_sync */
#ifndef EGL_ANDROID_blob_cache
#define EGL_ANDROID_blob_cache 1
typedef khronos_ssize_t EGLsizeiANDROID;
typedef void (*EGLSetBlobFuncANDROID) (const void *key, EGLsizeiANDROID keySize, const void *value, EGLsizeiANDROID valueSize);
typedef EGLsizeiANDROID (*EGLGetBlobFuncANDROID) (const void *key, EGLsizeiANDROID keySize, void *value, EGLsizeiANDROID valueSize);
typedef void (EGLAPIENTRYP PFNEGLSETBLOBCACHEFUNCSANDROIDPROC) (EGLDisplay dpy, EGLSetBlobFuncANDROID set, EGLGetBlobFuncANDROID get);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI void EGLAPIENTRY eglSetBlobCacheFuncsANDROID (EGLDisplay dpy, EGLSetBlobFuncANDROID set, EGLGetBlobFuncANDROID get);
#endif
#endif /* EGL_ANDROID_blob_cache */
#ifndef EGL_ANDROID_framebuffer_target
#define EGL_ANDROID_framebuffer_target 1
#define EGL_FRAMEBUFFER_TARGET_ANDROID 0x3147
#endif /* EGL_ANDROID_framebuffer_target */
#ifndef EGL_ANDROID_image_native_buffer
#define EGL_ANDROID_image_native_buffer 1
#define EGL_NATIVE_BUFFER_ANDROID 0x3140
#endif /* EGL_ANDROID_image_native_buffer */
#ifndef EGL_ANDROID_native_fence_sync
#define EGL_ANDROID_native_fence_sync 1
#define EGL_SYNC_NATIVE_FENCE_ANDROID 0x3144
#define EGL_SYNC_NATIVE_FENCE_FD_ANDROID 0x3145
#define EGL_SYNC_NATIVE_FENCE_SIGNALED_ANDROID 0x3146
#define EGL_NO_NATIVE_FENCE_FD_ANDROID -1
typedef EGLint (EGLAPIENTRYP PFNEGLDUPNATIVEFENCEFDANDROIDPROC) (EGLDisplay dpy, EGLSyncKHR sync);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLint EGLAPIENTRY eglDupNativeFenceFDANDROID (EGLDisplay dpy, EGLSyncKHR sync);
#endif
#endif /* EGL_ANDROID_native_fence_sync */
#ifndef EGL_ANDROID_recordable
#define EGL_ANDROID_recordable 1
#define EGL_RECORDABLE_ANDROID 0x3142
#endif /* EGL_ANDROID_recordable */
#ifndef EGL_ANGLE_d3d_share_handle_client_buffer
#define EGL_ANGLE_d3d_share_handle_client_buffer 1
#define EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE 0x3200
#endif /* EGL_ANGLE_d3d_share_handle_client_buffer */
#ifndef EGL_ANGLE_device_d3d
#define EGL_ANGLE_device_d3d 1
#define EGL_D3D9_DEVICE_ANGLE 0x33A0
#define EGL_D3D11_DEVICE_ANGLE 0x33A1
#endif /* EGL_ANGLE_device_d3d */
#ifndef EGL_ANGLE_query_surface_pointer
#define EGL_ANGLE_query_surface_pointer 1
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSURFACEPOINTERANGLEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurfacePointerANGLE (EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value);
#endif
#endif /* EGL_ANGLE_query_surface_pointer */
#ifndef EGL_ANGLE_surface_d3d_texture_2d_share_handle
#define EGL_ANGLE_surface_d3d_texture_2d_share_handle 1
#endif /* EGL_ANGLE_surface_d3d_texture_2d_share_handle */
#ifndef EGL_ANGLE_window_fixed_size
#define EGL_ANGLE_window_fixed_size 1
#define EGL_FIXED_SIZE_ANGLE 0x3201
#endif /* EGL_ANGLE_window_fixed_size */
#ifndef EGL_ARM_pixmap_multisample_discard
#define EGL_ARM_pixmap_multisample_discard 1
#define EGL_DISCARD_SAMPLES_ARM 0x3286
#endif /* EGL_ARM_pixmap_multisample_discard */
#ifndef EGL_EXT_buffer_age
#define EGL_EXT_buffer_age 1
#define EGL_BUFFER_AGE_EXT 0x313D
#endif /* EGL_EXT_buffer_age */
#ifndef EGL_EXT_client_extensions
#define EGL_EXT_client_extensions 1
#endif /* EGL_EXT_client_extensions */
#ifndef EGL_EXT_create_context_robustness
#define EGL_EXT_create_context_robustness 1
#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT 0x30BF
#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT 0x3138
#define EGL_NO_RESET_NOTIFICATION_EXT 0x31BE
#define EGL_LOSE_CONTEXT_ON_RESET_EXT 0x31BF
#endif /* EGL_EXT_create_context_robustness */
#ifndef EGL_EXT_device_base
#define EGL_EXT_device_base 1
typedef void *EGLDeviceEXT;
#define EGL_NO_DEVICE_EXT ((EGLDeviceEXT)(0))
#define EGL_BAD_DEVICE_EXT 0x322B
#define EGL_DEVICE_EXT 0x322C
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDEVICEATTRIBEXTPROC) (EGLDeviceEXT device, EGLint attribute, EGLAttrib *value);
typedef const char *(EGLAPIENTRYP PFNEGLQUERYDEVICESTRINGEXTPROC) (EGLDeviceEXT device, EGLint name);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDEVICESEXTPROC) (EGLint max_devices, EGLDeviceEXT *devices, EGLint *num_devices);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDISPLAYATTRIBEXTPROC) (EGLDisplay dpy, EGLint attribute, EGLAttrib *value);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglQueryDeviceAttribEXT (EGLDeviceEXT device, EGLint attribute, EGLAttrib *value);
EGLAPI const char *EGLAPIENTRY eglQueryDeviceStringEXT (EGLDeviceEXT device, EGLint name);
EGLAPI EGLBoolean EGLAPIENTRY eglQueryDevicesEXT (EGLint max_devices, EGLDeviceEXT *devices, EGLint *num_devices);
EGLAPI EGLBoolean EGLAPIENTRY eglQueryDisplayAttribEXT (EGLDisplay dpy, EGLint attribute, EGLAttrib *value);
#endif
#endif /* EGL_EXT_device_base */
#ifndef EGL_EXT_device_drm
#define EGL_EXT_device_drm 1
#define EGL_DRM_DEVICE_FILE_EXT 0x3233
#endif /* EGL_EXT_device_drm */
#ifndef EGL_EXT_device_enumeration
#define EGL_EXT_device_enumeration 1
#endif /* EGL_EXT_device_enumeration */
#ifndef EGL_EXT_device_openwf
#define EGL_EXT_device_openwf 1
#define EGL_OPENWF_DEVICE_ID_EXT 0x3237
#endif /* EGL_EXT_device_openwf */
#ifndef EGL_EXT_device_query
#define EGL_EXT_device_query 1
#endif /* EGL_EXT_device_query */
#ifndef EGL_EXT_image_dma_buf_import
#define EGL_EXT_image_dma_buf_import 1
#define EGL_LINUX_DMA_BUF_EXT 0x3270
#define EGL_LINUX_DRM_FOURCC_EXT 0x3271
#define EGL_DMA_BUF_PLANE0_FD_EXT 0x3272
#define EGL_DMA_BUF_PLANE0_OFFSET_EXT 0x3273
#define EGL_DMA_BUF_PLANE0_PITCH_EXT 0x3274
#define EGL_DMA_BUF_PLANE1_FD_EXT 0x3275
#define EGL_DMA_BUF_PLANE1_OFFSET_EXT 0x3276
#define EGL_DMA_BUF_PLANE1_PITCH_EXT 0x3277
#define EGL_DMA_BUF_PLANE2_FD_EXT 0x3278
#define EGL_DMA_BUF_PLANE2_OFFSET_EXT 0x3279
#define EGL_DMA_BUF_PLANE2_PITCH_EXT 0x327A
#define EGL_YUV_COLOR_SPACE_HINT_EXT 0x327B
#define EGL_SAMPLE_RANGE_HINT_EXT 0x327C
#define EGL_YUV_CHROMA_HORIZONTAL_SITING_HINT_EXT 0x327D
#define EGL_YUV_CHROMA_VERTICAL_SITING_HINT_EXT 0x327E
#define EGL_ITU_REC601_EXT 0x327F
#define EGL_ITU_REC709_EXT 0x3280
#define EGL_ITU_REC2020_EXT 0x3281
#define EGL_YUV_FULL_RANGE_EXT 0x3282
#define EGL_YUV_NARROW_RANGE_EXT 0x3283
#define EGL_YUV_CHROMA_SITING_0_EXT 0x3284
#define EGL_YUV_CHROMA_SITING_0_5_EXT 0x3285
#endif /* EGL_EXT_image_dma_buf_import */
#ifndef EGL_EXT_multiview_window
#define EGL_EXT_multiview_window 1
#define EGL_MULTIVIEW_VIEW_COUNT_EXT 0x3134
#endif /* EGL_EXT_multiview_window */
#ifndef EGL_EXT_output_base
#define EGL_EXT_output_base 1
typedef void *EGLOutputLayerEXT;
typedef void *EGLOutputPortEXT;
#define EGL_NO_OUTPUT_LAYER_EXT ((EGLOutputLayerEXT)0)
#define EGL_NO_OUTPUT_PORT_EXT ((EGLOutputPortEXT)0)
#define EGL_BAD_OUTPUT_LAYER_EXT 0x322D
#define EGL_BAD_OUTPUT_PORT_EXT 0x322E
#define EGL_SWAP_INTERVAL_EXT 0x322F
typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETOUTPUTLAYERSEXTPROC) (EGLDisplay dpy, const EGLAttrib *attrib_list, EGLOutputLayerEXT *layers, EGLint max_layers, EGLint *num_layers);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETOUTPUTPORTSEXTPROC) (EGLDisplay dpy, const EGLAttrib *attrib_list, EGLOutputPortEXT *ports, EGLint max_ports, EGLint *num_ports);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLOUTPUTLAYERATTRIBEXTPROC) (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint attribute, EGLAttrib value);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYOUTPUTLAYERATTRIBEXTPROC) (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint attribute, EGLAttrib *value);
typedef const char *(EGLAPIENTRYP PFNEGLQUERYOUTPUTLAYERSTRINGEXTPROC) (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint name);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLOUTPUTPORTATTRIBEXTPROC) (EGLDisplay dpy, EGLOutputPortEXT port, EGLint attribute, EGLAttrib value);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYOUTPUTPORTATTRIBEXTPROC) (EGLDisplay dpy, EGLOutputPortEXT port, EGLint attribute, EGLAttrib *value);
typedef const char *(EGLAPIENTRYP PFNEGLQUERYOUTPUTPORTSTRINGEXTPROC) (EGLDisplay dpy, EGLOutputPortEXT port, EGLint name);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglGetOutputLayersEXT (EGLDisplay dpy, const EGLAttrib *attrib_list, EGLOutputLayerEXT *layers, EGLint max_layers, EGLint *num_layers);
EGLAPI EGLBoolean EGLAPIENTRY eglGetOutputPortsEXT (EGLDisplay dpy, const EGLAttrib *attrib_list, EGLOutputPortEXT *ports, EGLint max_ports, EGLint *num_ports);
EGLAPI EGLBoolean EGLAPIENTRY eglOutputLayerAttribEXT (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint attribute, EGLAttrib value);
EGLAPI EGLBoolean EGLAPIENTRY eglQueryOutputLayerAttribEXT (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint attribute, EGLAttrib *value);
EGLAPI const char *EGLAPIENTRY eglQueryOutputLayerStringEXT (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint name);
EGLAPI EGLBoolean EGLAPIENTRY eglOutputPortAttribEXT (EGLDisplay dpy, EGLOutputPortEXT port, EGLint attribute, EGLAttrib value);
EGLAPI EGLBoolean EGLAPIENTRY eglQueryOutputPortAttribEXT (EGLDisplay dpy, EGLOutputPortEXT port, EGLint attribute, EGLAttrib *value);
EGLAPI const char *EGLAPIENTRY eglQueryOutputPortStringEXT (EGLDisplay dpy, EGLOutputPortEXT port, EGLint name);
#endif
#endif /* EGL_EXT_output_base */
#ifndef EGL_EXT_output_drm
#define EGL_EXT_output_drm 1
#define EGL_DRM_CRTC_EXT 0x3234
#define EGL_DRM_PLANE_EXT 0x3235
#define EGL_DRM_CONNECTOR_EXT 0x3236
#endif /* EGL_EXT_output_drm */
#ifndef EGL_EXT_output_openwf
#define EGL_EXT_output_openwf 1
#define EGL_OPENWF_PIPELINE_ID_EXT 0x3238
#define EGL_OPENWF_PORT_ID_EXT 0x3239
#endif /* EGL_EXT_output_openwf */
#ifndef EGL_EXT_platform_base
#define EGL_EXT_platform_base 1
typedef EGLDisplay (EGLAPIENTRYP PFNEGLGETPLATFORMDISPLAYEXTPROC) (EGLenum platform, void *native_display, const EGLint *attrib_list);
typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC) (EGLDisplay dpy, EGLConfig config, void *native_window, const EGLint *attrib_list);
typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPLATFORMPIXMAPSURFACEEXTPROC) (EGLDisplay dpy, EGLConfig config, void *native_pixmap, const EGLint *attrib_list);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLDisplay EGLAPIENTRY eglGetPlatformDisplayEXT (EGLenum platform, void *native_display, const EGLint *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformWindowSurfaceEXT (EGLDisplay dpy, EGLConfig config, void *native_window, const EGLint *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformPixmapSurfaceEXT (EGLDisplay dpy, EGLConfig config, void *native_pixmap, const EGLint *attrib_list);
#endif
#endif /* EGL_EXT_platform_base */
#ifndef EGL_EXT_platform_device
#define EGL_EXT_platform_device 1
#define EGL_PLATFORM_DEVICE_EXT 0x313F
#endif /* EGL_EXT_platform_device */
#ifndef EGL_EXT_platform_wayland
#define EGL_EXT_platform_wayland 1
#define EGL_PLATFORM_WAYLAND_EXT 0x31D8
#endif /* EGL_EXT_platform_wayland */
#ifndef EGL_EXT_platform_x11
#define EGL_EXT_platform_x11 1
#define EGL_PLATFORM_X11_EXT 0x31D5
#define EGL_PLATFORM_X11_SCREEN_EXT 0x31D6
#endif /* EGL_EXT_platform_x11 */
#ifndef EGL_EXT_protected_surface
#define EGL_EXT_protected_surface 1
#define EGL_PROTECTED_CONTENT_EXT 0x32C0
#endif /* EGL_EXT_protected_surface */
#ifndef EGL_EXT_stream_consumer_egloutput
#define EGL_EXT_stream_consumer_egloutput 1
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMEROUTPUTEXTPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLOutputLayerEXT layer);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerOutputEXT (EGLDisplay dpy, EGLStreamKHR stream, EGLOutputLayerEXT layer);
#endif
#endif /* EGL_EXT_stream_consumer_egloutput */
#ifndef EGL_EXT_swap_buffers_with_damage
#define EGL_EXT_swap_buffers_with_damage 1
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC) (EGLDisplay dpy, EGLSurface surface, EGLint *rects, EGLint n_rects);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffersWithDamageEXT (EGLDisplay dpy, EGLSurface surface, EGLint *rects, EGLint n_rects);
#endif
#endif /* EGL_EXT_swap_buffers_with_damage */
#ifndef EGL_EXT_yuv_surface
#define EGL_EXT_yuv_surface 1
#define EGL_YUV_ORDER_EXT 0x3301
#define EGL_YUV_NUMBER_OF_PLANES_EXT 0x3311
#define EGL_YUV_SUBSAMPLE_EXT 0x3312
#define EGL_YUV_DEPTH_RANGE_EXT 0x3317
#define EGL_YUV_CSC_STANDARD_EXT 0x330A
#define EGL_YUV_PLANE_BPP_EXT 0x331A
#define EGL_YUV_BUFFER_EXT 0x3300
#define EGL_YUV_ORDER_YUV_EXT 0x3302
#define EGL_YUV_ORDER_YVU_EXT 0x3303
#define EGL_YUV_ORDER_YUYV_EXT 0x3304
#define EGL_YUV_ORDER_UYVY_EXT 0x3305
#define EGL_YUV_ORDER_YVYU_EXT 0x3306
#define EGL_YUV_ORDER_VYUY_EXT 0x3307
#define EGL_YUV_ORDER_AYUV_EXT 0x3308
#define EGL_YUV_SUBSAMPLE_4_2_0_EXT 0x3313
#define EGL_YUV_SUBSAMPLE_4_2_2_EXT 0x3314
#define EGL_YUV_SUBSAMPLE_4_4_4_EXT 0x3315
#define EGL_YUV_DEPTH_RANGE_LIMITED_EXT 0x3318
#define EGL_YUV_DEPTH_RANGE_FULL_EXT 0x3319
#define EGL_YUV_CSC_STANDARD_601_EXT 0x330B
#define EGL_YUV_CSC_STANDARD_709_EXT 0x330C
#define EGL_YUV_CSC_STANDARD_2020_EXT 0x330D
#define EGL_YUV_PLANE_BPP_0_EXT 0x331B
#define EGL_YUV_PLANE_BPP_8_EXT 0x331C
#define EGL_YUV_PLANE_BPP_10_EXT 0x331D
#endif /* EGL_EXT_yuv_surface */
#ifndef EGL_HI_clientpixmap
#define EGL_HI_clientpixmap 1
struct EGLClientPixmapHI {
void *pData;
EGLint iWidth;
EGLint iHeight;
EGLint iStride;
};
#define EGL_CLIENT_PIXMAP_POINTER_HI 0x8F74
typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPIXMAPSURFACEHIPROC) (EGLDisplay dpy, EGLConfig config, struct EGLClientPixmapHI *pixmap);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurfaceHI (EGLDisplay dpy, EGLConfig config, struct EGLClientPixmapHI *pixmap);
#endif
#endif /* EGL_HI_clientpixmap */
#ifndef EGL_HI_colorformats
#define EGL_HI_colorformats 1
#define EGL_COLOR_FORMAT_HI 0x8F70
#define EGL_COLOR_RGB_HI 0x8F71
#define EGL_COLOR_RGBA_HI 0x8F72
#define EGL_COLOR_ARGB_HI 0x8F73
#endif /* EGL_HI_colorformats */
#ifndef EGL_IMG_context_priority
#define EGL_IMG_context_priority 1
#define EGL_CONTEXT_PRIORITY_LEVEL_IMG 0x3100
#define EGL_CONTEXT_PRIORITY_HIGH_IMG 0x3101
#define EGL_CONTEXT_PRIORITY_MEDIUM_IMG 0x3102
#define EGL_CONTEXT_PRIORITY_LOW_IMG 0x3103
#endif /* EGL_IMG_context_priority */
#ifndef EGL_MESA_drm_image
#define EGL_MESA_drm_image 1
#define EGL_DRM_BUFFER_FORMAT_MESA 0x31D0
#define EGL_DRM_BUFFER_USE_MESA 0x31D1
#define EGL_DRM_BUFFER_FORMAT_ARGB32_MESA 0x31D2
#define EGL_DRM_BUFFER_MESA 0x31D3
#define EGL_DRM_BUFFER_STRIDE_MESA 0x31D4
#define EGL_DRM_BUFFER_USE_SCANOUT_MESA 0x00000001
#define EGL_DRM_BUFFER_USE_SHARE_MESA 0x00000002
typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEDRMIMAGEMESAPROC) (EGLDisplay dpy, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLEXPORTDRMIMAGEMESAPROC) (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLImageKHR EGLAPIENTRY eglCreateDRMImageMESA (EGLDisplay dpy, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglExportDRMImageMESA (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride);
#endif
#endif /* EGL_MESA_drm_image */
#ifndef EGL_MESA_image_dma_buf_export
#define EGL_MESA_image_dma_buf_export 1
typedef EGLBoolean (EGLAPIENTRYP PFNEGLEXPORTDMABUFIMAGEQUERYMESAPROC) (EGLDisplay dpy, EGLImageKHR image, int *fourcc, int *num_planes, EGLuint64KHR *modifiers);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLEXPORTDMABUFIMAGEMESAPROC) (EGLDisplay dpy, EGLImageKHR image, int *fds, EGLint *strides, EGLint *offsets);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglExportDMABUFImageQueryMESA (EGLDisplay dpy, EGLImageKHR image, int *fourcc, int *num_planes, EGLuint64KHR *modifiers);
EGLAPI EGLBoolean EGLAPIENTRY eglExportDMABUFImageMESA (EGLDisplay dpy, EGLImageKHR image, int *fds, EGLint *strides, EGLint *offsets);
#endif
#endif /* EGL_MESA_image_dma_buf_export */
#ifndef EGL_MESA_platform_gbm
#define EGL_MESA_platform_gbm 1
#define EGL_PLATFORM_GBM_MESA 0x31D7
#endif /* EGL_MESA_platform_gbm */
#ifndef EGL_NOK_swap_region
#define EGL_NOK_swap_region 1
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSREGIONNOKPROC) (EGLDisplay dpy, EGLSurface surface, EGLint numRects, const EGLint *rects);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffersRegionNOK (EGLDisplay dpy, EGLSurface surface, EGLint numRects, const EGLint *rects);
#endif
#endif /* EGL_NOK_swap_region */
#ifndef EGL_NOK_swap_region2
#define EGL_NOK_swap_region2 1
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSREGION2NOKPROC) (EGLDisplay dpy, EGLSurface surface, EGLint numRects, const EGLint *rects);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffersRegion2NOK (EGLDisplay dpy, EGLSurface surface, EGLint numRects, const EGLint *rects);
#endif
#endif /* EGL_NOK_swap_region2 */
#ifndef EGL_NOK_texture_from_pixmap
#define EGL_NOK_texture_from_pixmap 1
#define EGL_Y_INVERTED_NOK 0x307F
#endif /* EGL_NOK_texture_from_pixmap */
#ifndef EGL_NV_3dvision_surface
#define EGL_NV_3dvision_surface 1
#define EGL_AUTO_STEREO_NV 0x3136
#endif /* EGL_NV_3dvision_surface */
#ifndef EGL_NV_coverage_sample
#define EGL_NV_coverage_sample 1
#define EGL_COVERAGE_BUFFERS_NV 0x30E0
#define EGL_COVERAGE_SAMPLES_NV 0x30E1
#endif /* EGL_NV_coverage_sample */
#ifndef EGL_NV_coverage_sample_resolve
#define EGL_NV_coverage_sample_resolve 1
#define EGL_COVERAGE_SAMPLE_RESOLVE_NV 0x3131
#define EGL_COVERAGE_SAMPLE_RESOLVE_DEFAULT_NV 0x3132
#define EGL_COVERAGE_SAMPLE_RESOLVE_NONE_NV 0x3133
#endif /* EGL_NV_coverage_sample_resolve */
#ifndef EGL_NV_cuda_event
#define EGL_NV_cuda_event 1
#define EGL_CUDA_EVENT_HANDLE_NV 0x323B
#define EGL_SYNC_CUDA_EVENT_NV 0x323C
#define EGL_SYNC_CUDA_EVENT_COMPLETE_NV 0x323D
#endif /* EGL_NV_cuda_event */
#ifndef EGL_NV_depth_nonlinear
#define EGL_NV_depth_nonlinear 1
#define EGL_DEPTH_ENCODING_NV 0x30E2
#define EGL_DEPTH_ENCODING_NONE_NV 0
#define EGL_DEPTH_ENCODING_NONLINEAR_NV 0x30E3
#endif /* EGL_NV_depth_nonlinear */
#ifndef EGL_NV_device_cuda
#define EGL_NV_device_cuda 1
#define EGL_CUDA_DEVICE_NV 0x323A
#endif /* EGL_NV_device_cuda */
#ifndef EGL_NV_native_query
#define EGL_NV_native_query 1
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYNATIVEDISPLAYNVPROC) (EGLDisplay dpy, EGLNativeDisplayType *display_id);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYNATIVEWINDOWNVPROC) (EGLDisplay dpy, EGLSurface surf, EGLNativeWindowType *window);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYNATIVEPIXMAPNVPROC) (EGLDisplay dpy, EGLSurface surf, EGLNativePixmapType *pixmap);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglQueryNativeDisplayNV (EGLDisplay dpy, EGLNativeDisplayType *display_id);
EGLAPI EGLBoolean EGLAPIENTRY eglQueryNativeWindowNV (EGLDisplay dpy, EGLSurface surf, EGLNativeWindowType *window);
EGLAPI EGLBoolean EGLAPIENTRY eglQueryNativePixmapNV (EGLDisplay dpy, EGLSurface surf, EGLNativePixmapType *pixmap);
#endif
#endif /* EGL_NV_native_query */
#ifndef EGL_NV_post_convert_rounding
#define EGL_NV_post_convert_rounding 1
#endif /* EGL_NV_post_convert_rounding */
#ifndef EGL_NV_post_sub_buffer
#define EGL_NV_post_sub_buffer 1
#define EGL_POST_SUB_BUFFER_SUPPORTED_NV 0x30BE
typedef EGLBoolean (EGLAPIENTRYP PFNEGLPOSTSUBBUFFERNVPROC) (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglPostSubBufferNV (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height);
#endif
#endif /* EGL_NV_post_sub_buffer */
#ifndef EGL_NV_stream_sync
#define EGL_NV_stream_sync 1
#define EGL_SYNC_NEW_FRAME_NV 0x321F
typedef EGLSyncKHR (EGLAPIENTRYP PFNEGLCREATESTREAMSYNCNVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum type, const EGLint *attrib_list);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateStreamSyncNV (EGLDisplay dpy, EGLStreamKHR stream, EGLenum type, const EGLint *attrib_list);
#endif
#endif /* EGL_NV_stream_sync */
#ifndef EGL_NV_sync
#define EGL_NV_sync 1
typedef void *EGLSyncNV;
typedef khronos_utime_nanoseconds_t EGLTimeNV;
#ifdef KHRONOS_SUPPORT_INT64
#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE_NV 0x30E6
#define EGL_SYNC_STATUS_NV 0x30E7
#define EGL_SIGNALED_NV 0x30E8
#define EGL_UNSIGNALED_NV 0x30E9
#define EGL_SYNC_FLUSH_COMMANDS_BIT_NV 0x0001
#define EGL_FOREVER_NV 0xFFFFFFFFFFFFFFFFull
#define EGL_ALREADY_SIGNALED_NV 0x30EA
#define EGL_TIMEOUT_EXPIRED_NV 0x30EB
#define EGL_CONDITION_SATISFIED_NV 0x30EC
#define EGL_SYNC_TYPE_NV 0x30ED
#define EGL_SYNC_CONDITION_NV 0x30EE
#define EGL_SYNC_FENCE_NV 0x30EF
#define EGL_NO_SYNC_NV ((EGLSyncNV)0)
typedef EGLSyncNV (EGLAPIENTRYP PFNEGLCREATEFENCESYNCNVPROC) (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSYNCNVPROC) (EGLSyncNV sync);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLFENCENVPROC) (EGLSyncNV sync);
typedef EGLint (EGLAPIENTRYP PFNEGLCLIENTWAITSYNCNVPROC) (EGLSyncNV sync, EGLint flags, EGLTimeNV timeout);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSIGNALSYNCNVPROC) (EGLSyncNV sync, EGLenum mode);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBNVPROC) (EGLSyncNV sync, EGLint attribute, EGLint *value);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLSyncNV EGLAPIENTRY eglCreateFenceSyncNV (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroySyncNV (EGLSyncNV sync);
EGLAPI EGLBoolean EGLAPIENTRY eglFenceNV (EGLSyncNV sync);
EGLAPI EGLint EGLAPIENTRY eglClientWaitSyncNV (EGLSyncNV sync, EGLint flags, EGLTimeNV timeout);
EGLAPI EGLBoolean EGLAPIENTRY eglSignalSyncNV (EGLSyncNV sync, EGLenum mode);
EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttribNV (EGLSyncNV sync, EGLint attribute, EGLint *value);
#endif
#endif /* KHRONOS_SUPPORT_INT64 */
#endif /* EGL_NV_sync */
#ifndef EGL_NV_system_time
#define EGL_NV_system_time 1
typedef khronos_utime_nanoseconds_t EGLuint64NV;
#ifdef KHRONOS_SUPPORT_INT64
typedef EGLuint64NV (EGLAPIENTRYP PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) (void);
typedef EGLuint64NV (EGLAPIENTRYP PFNEGLGETSYSTEMTIMENVPROC) (void);
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeFrequencyNV (void);
EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeNV (void);
#endif
#endif /* KHRONOS_SUPPORT_INT64 */
#endif /* EGL_NV_system_time */
#ifndef EGL_TIZEN_image_native_buffer
#define EGL_TIZEN_image_native_buffer 1
#define EGL_NATIVE_BUFFER_TIZEN 0x32A0
#endif /* EGL_TIZEN_image_native_buffer */
#ifndef EGL_TIZEN_image_native_surface
#define EGL_TIZEN_image_native_surface 1
#define EGL_NATIVE_SURFACE_TIZEN 0x32A1
#endif /* EGL_TIZEN_image_native_surface */
#ifdef __cplusplus
}
#endif
#endif /* __eglext_h_ */
#endif /* _MSC_VER */
| 73,586 | C | 42.958781 | 176 | 0.732368 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_image.h | /*
SDL_image: An example image loading library for use with SDL
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* A simple library to load images of various formats as SDL surfaces */
#ifndef SDL_IMAGE_H_
#define SDL_IMAGE_H_
#include "SDL.h"
#include "SDL_version.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL
*/
#define SDL_IMAGE_MAJOR_VERSION 2
#define SDL_IMAGE_MINOR_VERSION 0
#define SDL_IMAGE_PATCHLEVEL 3
/* This macro can be used to fill a version structure with the compile-time
* version of the SDL_image library.
*/
#define SDL_IMAGE_VERSION(X) \
{ \
(X)->major = SDL_IMAGE_MAJOR_VERSION; \
(X)->minor = SDL_IMAGE_MINOR_VERSION; \
(X)->patch = SDL_IMAGE_PATCHLEVEL; \
}
/**
* This is the version number macro for the current SDL_image version.
*/
#define SDL_IMAGE_COMPILEDVERSION \
SDL_VERSIONNUM(SDL_IMAGE_MAJOR_VERSION, SDL_IMAGE_MINOR_VERSION, SDL_IMAGE_PATCHLEVEL)
/**
* This macro will evaluate to true if compiled with SDL_image at least X.Y.Z.
*/
#define SDL_IMAGE_VERSION_ATLEAST(X, Y, Z) \
(SDL_IMAGE_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z))
/* This function gets the version of the dynamically linked SDL_image library.
it should NOT be used to fill a version structure, instead you should
use the SDL_IMAGE_VERSION() macro.
*/
extern DECLSPEC const SDL_version * SDLCALL IMG_Linked_Version(void);
typedef enum
{
IMG_INIT_JPG = 0x00000001,
IMG_INIT_PNG = 0x00000002,
IMG_INIT_TIF = 0x00000004,
IMG_INIT_WEBP = 0x00000008
} IMG_InitFlags;
/* Loads dynamic libraries and prepares them for use. Flags should be
one or more flags from IMG_InitFlags OR'd together.
It returns the flags successfully initialized, or 0 on failure.
*/
extern DECLSPEC int SDLCALL IMG_Init(int flags);
/* Unloads libraries loaded with IMG_Init */
extern DECLSPEC void SDLCALL IMG_Quit(void);
/* Load an image from an SDL data source.
The 'type' may be one of: "BMP", "GIF", "PNG", etc.
If the image format supports a transparent pixel, SDL will set the
colorkey for the surface. You can enable RLE acceleration on the
surface afterwards by calling:
SDL_SetColorKey(image, SDL_RLEACCEL, image->format->colorkey);
*/
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadTyped_RW(SDL_RWops *src, int freesrc, const char *type);
/* Convenience functions */
extern DECLSPEC SDL_Surface * SDLCALL IMG_Load(const char *file);
extern DECLSPEC SDL_Surface * SDLCALL IMG_Load_RW(SDL_RWops *src, int freesrc);
#if SDL_VERSION_ATLEAST(2,0,0)
/* Load an image directly into a render texture.
*/
extern DECLSPEC SDL_Texture * SDLCALL IMG_LoadTexture(SDL_Renderer *renderer, const char *file);
extern DECLSPEC SDL_Texture * SDLCALL IMG_LoadTexture_RW(SDL_Renderer *renderer, SDL_RWops *src, int freesrc);
extern DECLSPEC SDL_Texture * SDLCALL IMG_LoadTextureTyped_RW(SDL_Renderer *renderer, SDL_RWops *src, int freesrc, const char *type);
#endif /* SDL 2.0 */
/* Functions to detect a file type, given a seekable source */
extern DECLSPEC int SDLCALL IMG_isICO(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isCUR(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isBMP(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isGIF(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isJPG(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isLBM(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isPCX(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isPNG(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isPNM(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isSVG(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isTIF(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isXCF(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isXPM(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isXV(SDL_RWops *src);
extern DECLSPEC int SDLCALL IMG_isWEBP(SDL_RWops *src);
/* Individual loading functions */
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadICO_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadCUR_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadBMP_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadGIF_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadJPG_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadLBM_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadPCX_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadPNG_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadPNM_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadSVG_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadTGA_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadTIF_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadXCF_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadXPM_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadXV_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadWEBP_RW(SDL_RWops *src);
extern DECLSPEC SDL_Surface * SDLCALL IMG_ReadXPMFromArray(char **xpm);
/* Individual saving functions */
extern DECLSPEC int SDLCALL IMG_SavePNG(SDL_Surface *surface, const char *file);
extern DECLSPEC int SDLCALL IMG_SavePNG_RW(SDL_Surface *surface, SDL_RWops *dst, int freedst);
extern DECLSPEC int SDLCALL IMG_SaveJPG(SDL_Surface *surface, const char *file, int quality);
extern DECLSPEC int SDLCALL IMG_SaveJPG_RW(SDL_Surface *surface, SDL_RWops *dst, int freedst, int quality);
/* We'll use SDL for reporting errors */
#define IMG_SetError SDL_SetError
#define IMG_GetError SDL_GetError
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_IMAGE_H_ */
| 6,820 | C | 41.104938 | 133 | 0.734311 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_thread.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_thread_h_
#define SDL_thread_h_
/**
* \file SDL_thread.h
*
* Header for the SDL thread management routines.
*/
#include "SDL_stdinc.h"
#include "SDL_error.h"
/* Thread synchronization primitives */
#include "SDL_atomic.h"
#include "SDL_mutex.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* The SDL thread structure, defined in SDL_thread.c */
struct SDL_Thread;
typedef struct SDL_Thread SDL_Thread;
/* The SDL thread ID */
typedef unsigned long SDL_threadID;
/* Thread local storage ID, 0 is the invalid ID */
typedef unsigned int SDL_TLSID;
/**
* The SDL thread priority.
*
* \note On many systems you require special privileges to set high priority.
*/
typedef enum {
SDL_THREAD_PRIORITY_LOW,
SDL_THREAD_PRIORITY_NORMAL,
SDL_THREAD_PRIORITY_HIGH
} SDL_ThreadPriority;
/**
* The function passed to SDL_CreateThread().
* It is passed a void* user context parameter and returns an int.
*/
typedef int (SDLCALL * SDL_ThreadFunction) (void *data);
#if defined(__WIN32__) && !defined(HAVE_LIBC)
/**
* \file SDL_thread.h
*
* We compile SDL into a DLL. This means, that it's the DLL which
* creates a new thread for the calling process with the SDL_CreateThread()
* API. There is a problem with this, that only the RTL of the SDL2.DLL will
* be initialized for those threads, and not the RTL of the calling
* application!
*
* To solve this, we make a little hack here.
*
* We'll always use the caller's _beginthread() and _endthread() APIs to
* start a new thread. This way, if it's the SDL2.DLL which uses this API,
* then the RTL of SDL2.DLL will be used to create the new thread, and if it's
* the application, then the RTL of the application will be used.
*
* So, in short:
* Always use the _beginthread() and _endthread() of the calling runtime
* library!
*/
#define SDL_PASSED_BEGINTHREAD_ENDTHREAD
#include <process.h> /* _beginthreadex() and _endthreadex() */
typedef uintptr_t(__cdecl * pfnSDL_CurrentBeginThread)
(void *, unsigned, unsigned (__stdcall *func)(void *),
void * /*arg*/, unsigned, unsigned * /* threadID */);
typedef void (__cdecl * pfnSDL_CurrentEndThread) (unsigned code);
/**
* Create a thread.
*/
extern DECLSPEC SDL_Thread *SDLCALL
SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data,
pfnSDL_CurrentBeginThread pfnBeginThread,
pfnSDL_CurrentEndThread pfnEndThread);
/**
* Create a thread.
*/
#if defined(SDL_CreateThread) && SDL_DYNAMIC_API
#undef SDL_CreateThread
#define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthreadex, (pfnSDL_CurrentEndThread)_endthreadex)
#else
#define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthreadex, (pfnSDL_CurrentEndThread)_endthreadex)
#endif
#elif defined(__OS2__)
/*
* just like the windows case above: We compile SDL2
* into a dll with Watcom's runtime statically linked.
*/
#define SDL_PASSED_BEGINTHREAD_ENDTHREAD
#ifndef __EMX__
#include <process.h>
#else
#include <stdlib.h>
#endif
typedef int (*pfnSDL_CurrentBeginThread)(void (*func)(void *), void *, unsigned, void * /*arg*/);
typedef void (*pfnSDL_CurrentEndThread)(void);
extern DECLSPEC SDL_Thread *SDLCALL
SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data,
pfnSDL_CurrentBeginThread pfnBeginThread,
pfnSDL_CurrentEndThread pfnEndThread);
#if defined(SDL_CreateThread) && SDL_DYNAMIC_API
#undef SDL_CreateThread
#define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthread, (pfnSDL_CurrentEndThread)_endthread)
#else
#define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthread, (pfnSDL_CurrentEndThread)_endthread)
#endif
#else
/**
* Create a thread.
*
* Thread naming is a little complicated: Most systems have very small
* limits for the string length (Haiku has 32 bytes, Linux currently has 16,
* Visual C++ 6.0 has nine!), and possibly other arbitrary rules. You'll
* have to see what happens with your system's debugger. The name should be
* UTF-8 (but using the naming limits of C identifiers is a better bet).
* There are no requirements for thread naming conventions, so long as the
* string is null-terminated UTF-8, but these guidelines are helpful in
* choosing a name:
*
* http://stackoverflow.com/questions/149932/naming-conventions-for-threads
*
* If a system imposes requirements, SDL will try to munge the string for
* it (truncate, etc), but the original string contents will be available
* from SDL_GetThreadName().
*/
extern DECLSPEC SDL_Thread *SDLCALL
SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data);
#endif
/**
* Get the thread name, as it was specified in SDL_CreateThread().
* This function returns a pointer to a UTF-8 string that names the
* specified thread, or NULL if it doesn't have a name. This is internal
* memory, not to be free()'d by the caller, and remains valid until the
* specified thread is cleaned up by SDL_WaitThread().
*/
extern DECLSPEC const char *SDLCALL SDL_GetThreadName(SDL_Thread *thread);
/**
* Get the thread identifier for the current thread.
*/
extern DECLSPEC SDL_threadID SDLCALL SDL_ThreadID(void);
/**
* Get the thread identifier for the specified thread.
*
* Equivalent to SDL_ThreadID() if the specified thread is NULL.
*/
extern DECLSPEC SDL_threadID SDLCALL SDL_GetThreadID(SDL_Thread * thread);
/**
* Set the priority for the current thread
*/
extern DECLSPEC int SDLCALL SDL_SetThreadPriority(SDL_ThreadPriority priority);
/**
* Wait for a thread to finish. Threads that haven't been detached will
* remain (as a "zombie") until this function cleans them up. Not doing so
* is a resource leak.
*
* Once a thread has been cleaned up through this function, the SDL_Thread
* that references it becomes invalid and should not be referenced again.
* As such, only one thread may call SDL_WaitThread() on another.
*
* The return code for the thread function is placed in the area
* pointed to by \c status, if \c status is not NULL.
*
* You may not wait on a thread that has been used in a call to
* SDL_DetachThread(). Use either that function or this one, but not
* both, or behavior is undefined.
*
* It is safe to pass NULL to this function; it is a no-op.
*/
extern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread * thread, int *status);
/**
* A thread may be "detached" to signify that it should not remain until
* another thread has called SDL_WaitThread() on it. Detaching a thread
* is useful for long-running threads that nothing needs to synchronize
* with or further manage. When a detached thread is done, it simply
* goes away.
*
* There is no way to recover the return code of a detached thread. If you
* need this, don't detach the thread and instead use SDL_WaitThread().
*
* Once a thread is detached, you should usually assume the SDL_Thread isn't
* safe to reference again, as it will become invalid immediately upon
* the detached thread's exit, instead of remaining until someone has called
* SDL_WaitThread() to finally clean it up. As such, don't detach the same
* thread more than once.
*
* If a thread has already exited when passed to SDL_DetachThread(), it will
* stop waiting for a call to SDL_WaitThread() and clean up immediately.
* It is not safe to detach a thread that might be used with SDL_WaitThread().
*
* You may not call SDL_WaitThread() on a thread that has been detached.
* Use either that function or this one, but not both, or behavior is
* undefined.
*
* It is safe to pass NULL to this function; it is a no-op.
*/
extern DECLSPEC void SDLCALL SDL_DetachThread(SDL_Thread * thread);
/**
* \brief Create an identifier that is globally visible to all threads but refers to data that is thread-specific.
*
* \return The newly created thread local storage identifier, or 0 on error
*
* \code
* static SDL_SpinLock tls_lock;
* static SDL_TLSID thread_local_storage;
*
* void SetMyThreadData(void *value)
* {
* if (!thread_local_storage) {
* SDL_AtomicLock(&tls_lock);
* if (!thread_local_storage) {
* thread_local_storage = SDL_TLSCreate();
* }
* SDL_AtomicUnlock(&tls_lock);
* }
* SDL_TLSSet(thread_local_storage, value, 0);
* }
*
* void *GetMyThreadData(void)
* {
* return SDL_TLSGet(thread_local_storage);
* }
* \endcode
*
* \sa SDL_TLSGet()
* \sa SDL_TLSSet()
*/
extern DECLSPEC SDL_TLSID SDLCALL SDL_TLSCreate(void);
/**
* \brief Get the value associated with a thread local storage ID for the current thread.
*
* \param id The thread local storage ID
*
* \return The value associated with the ID for the current thread, or NULL if no value has been set.
*
* \sa SDL_TLSCreate()
* \sa SDL_TLSSet()
*/
extern DECLSPEC void * SDLCALL SDL_TLSGet(SDL_TLSID id);
/**
* \brief Set the value associated with a thread local storage ID for the current thread.
*
* \param id The thread local storage ID
* \param value The value to associate with the ID for the current thread
* \param destructor A function called when the thread exits, to free the value.
*
* \return 0 on success, -1 on error
*
* \sa SDL_TLSCreate()
* \sa SDL_TLSGet()
*/
extern DECLSPEC int SDLCALL SDL_TLSSet(SDL_TLSID id, const void *value, void (SDLCALL *destructor)(void*));
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_thread_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 10,851 | C | 34.119741 | 160 | 0.70869 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_loadso.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_loadso.h
*
* System dependent library loading routines
*
* Some things to keep in mind:
* \li These functions only work on C function names. Other languages may
* have name mangling and intrinsic language support that varies from
* compiler to compiler.
* \li Make sure you declare your function pointers with the same calling
* convention as the actual library function. Your code will crash
* mysteriously if you do not do this.
* \li Avoid namespace collisions. If you load a symbol from the library,
* it is not defined whether or not it goes into the global symbol
* namespace for the application. If it does and it conflicts with
* symbols in your code or other shared libraries, you will not get
* the results you expect. :)
*/
#ifndef SDL_loadso_h_
#define SDL_loadso_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* This function dynamically loads a shared object and returns a pointer
* to the object handle (or NULL if there was an error).
* The 'sofile' parameter is a system dependent name of the object file.
*/
extern DECLSPEC void *SDLCALL SDL_LoadObject(const char *sofile);
/**
* Given an object handle, this function looks up the address of the
* named function in the shared object and returns it. This address
* is no longer valid after calling SDL_UnloadObject().
*/
extern DECLSPEC void *SDLCALL SDL_LoadFunction(void *handle,
const char *name);
/**
* Unload a shared object from memory.
*/
extern DECLSPEC void SDLCALL SDL_UnloadObject(void *handle);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_loadso_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 2,866 | C | 33.963414 | 76 | 0.713538 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_test_harness.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_test_harness.h
*
* Include file for SDL test framework.
*
* This code is a part of the SDL2_test library, not the main SDL library.
*/
/*
Defines types for test case definitions and the test execution harness API.
Based on original GSOC code by Markus Kauppila <[email protected]>
*/
#ifndef SDL_test_h_arness_h
#define SDL_test_h_arness_h
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* ! Definitions for test case structures */
#define TEST_ENABLED 1
#define TEST_DISABLED 0
/* ! Definition of all the possible test return values of the test case method */
#define TEST_ABORTED -1
#define TEST_STARTED 0
#define TEST_COMPLETED 1
#define TEST_SKIPPED 2
/* ! Definition of all the possible test results for the harness */
#define TEST_RESULT_PASSED 0
#define TEST_RESULT_FAILED 1
#define TEST_RESULT_NO_ASSERT 2
#define TEST_RESULT_SKIPPED 3
#define TEST_RESULT_SETUP_FAILURE 4
/* !< Function pointer to a test case setup function (run before every test) */
typedef void (*SDLTest_TestCaseSetUpFp)(void *arg);
/* !< Function pointer to a test case function */
typedef int (*SDLTest_TestCaseFp)(void *arg);
/* !< Function pointer to a test case teardown function (run after every test) */
typedef void (*SDLTest_TestCaseTearDownFp)(void *arg);
/**
* Holds information about a single test case.
*/
typedef struct SDLTest_TestCaseReference {
/* !< Func2Stress */
SDLTest_TestCaseFp testCase;
/* !< Short name (or function name) "Func2Stress" */
char *name;
/* !< Long name or full description "This test pushes func2() to the limit." */
char *description;
/* !< Set to TEST_ENABLED or TEST_DISABLED (test won't be run) */
int enabled;
} SDLTest_TestCaseReference;
/**
* Holds information about a test suite (multiple test cases).
*/
typedef struct SDLTest_TestSuiteReference {
/* !< "PlatformSuite" */
char *name;
/* !< The function that is run before each test. NULL skips. */
SDLTest_TestCaseSetUpFp testSetUp;
/* !< The test cases that are run as part of the suite. Last item should be NULL. */
const SDLTest_TestCaseReference **testCases;
/* !< The function that is run after each test. NULL skips. */
SDLTest_TestCaseTearDownFp testTearDown;
} SDLTest_TestSuiteReference;
/**
* \brief Generates a random run seed string for the harness. The generated seed will contain alphanumeric characters (0-9A-Z).
*
* Note: The returned string needs to be deallocated by the caller.
*
* \param length The length of the seed string to generate
*
* \returns The generated seed string
*/
char *SDLTest_GenerateRunSeed(const int length);
/**
* \brief Execute a test suite using the given run seed and execution key.
*
* \param testSuites Suites containing the test case.
* \param userRunSeed Custom run seed provided by user, or NULL to autogenerate one.
* \param userExecKey Custom execution key provided by user, or 0 to autogenerate one.
* \param filter Filter specification. NULL disables. Case sensitive.
* \param testIterations Number of iterations to run each test case.
*
* \returns Test run result; 0 when all tests passed, 1 if any tests failed.
*/
int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *userRunSeed, Uint64 userExecKey, const char *filter, int testIterations);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_test_h_arness_h */
/* vi: set ts=4 sw=4 expandtab: */
| 4,612 | C | 33.17037 | 149 | 0.714224 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_test_log.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_test_log.h
*
* Include file for SDL test framework.
*
* This code is a part of the SDL2_test library, not the main SDL library.
*/
/*
*
* Wrapper to log in the TEST category
*
*/
#ifndef SDL_test_log_h_
#define SDL_test_log_h_
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Prints given message with a timestamp in the TEST category and INFO priority.
*
* \param fmt Message to be logged
*/
void SDLTest_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1);
/**
* \brief Prints given message with a timestamp in the TEST category and the ERROR priority.
*
* \param fmt Message to be logged
*/
void SDLTest_LogError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_test_log_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 1,954 | C | 27.75 | 95 | 0.718526 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_test_assert.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_test_assert.h
*
* Include file for SDL test framework.
*
* This code is a part of the SDL2_test library, not the main SDL library.
*/
/*
*
* Assert API for test code and test cases
*
*/
#ifndef SDL_test_assert_h_
#define SDL_test_assert_h_
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Fails the assert.
*/
#define ASSERT_FAIL 0
/**
* \brief Passes the assert.
*/
#define ASSERT_PASS 1
/**
* \brief Assert that logs and break execution flow on failures.
*
* \param assertCondition Evaluated condition or variable to assert; fail (==0) or pass (!=0).
* \param assertDescription Message to log with the assert describing it.
*/
void SDLTest_Assert(int assertCondition, SDL_PRINTF_FORMAT_STRING const char *assertDescription, ...) SDL_PRINTF_VARARG_FUNC(2);
/**
* \brief Assert for test cases that logs but does not break execution flow on failures. Updates assertion counters.
*
* \param assertCondition Evaluated condition or variable to assert; fail (==0) or pass (!=0).
* \param assertDescription Message to log with the assert describing it.
*
* \returns Returns the assertCondition so it can be used to externally to break execution flow if desired.
*/
int SDLTest_AssertCheck(int assertCondition, SDL_PRINTF_FORMAT_STRING const char *assertDescription, ...) SDL_PRINTF_VARARG_FUNC(2);
/**
* \brief Explicitly pass without checking an assertion condition. Updates assertion counter.
*
* \param assertDescription Message to log with the assert describing it.
*/
void SDLTest_AssertPass(SDL_PRINTF_FORMAT_STRING const char *assertDescription, ...) SDL_PRINTF_VARARG_FUNC(1);
/**
* \brief Resets the assert summary counters to zero.
*/
void SDLTest_ResetAssertSummary(void);
/**
* \brief Logs summary of all assertions (total, pass, fail) since last reset as INFO or ERROR.
*/
void SDLTest_LogAssertSummary(void);
/**
* \brief Converts the current assert summary state to a test result.
*
* \returns TEST_RESULT_PASSED, TEST_RESULT_FAILED, or TEST_RESULT_NO_ASSERT
*/
int SDLTest_AssertSummaryToTestResult(void);
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_test_assert_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 3,243 | C | 29.603773 | 132 | 0.730805 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_rect.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_rect.h
*
* Header file for SDL_rect definition and management functions.
*/
#ifndef SDL_rect_h_
#define SDL_rect_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_pixels.h"
#include "SDL_rwops.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief The structure that defines a point
*
* \sa SDL_EnclosePoints
* \sa SDL_PointInRect
*/
typedef struct SDL_Point
{
int x;
int y;
} SDL_Point;
/**
* \brief A rectangle, with the origin at the upper left.
*
* \sa SDL_RectEmpty
* \sa SDL_RectEquals
* \sa SDL_HasIntersection
* \sa SDL_IntersectRect
* \sa SDL_UnionRect
* \sa SDL_EnclosePoints
*/
typedef struct SDL_Rect
{
int x, y;
int w, h;
} SDL_Rect;
/**
* \brief Returns true if point resides inside a rectangle.
*/
SDL_FORCE_INLINE SDL_bool SDL_PointInRect(const SDL_Point *p, const SDL_Rect *r)
{
return ( (p->x >= r->x) && (p->x < (r->x + r->w)) &&
(p->y >= r->y) && (p->y < (r->y + r->h)) ) ? SDL_TRUE : SDL_FALSE;
}
/**
* \brief Returns true if the rectangle has no area.
*/
SDL_FORCE_INLINE SDL_bool SDL_RectEmpty(const SDL_Rect *r)
{
return ((!r) || (r->w <= 0) || (r->h <= 0)) ? SDL_TRUE : SDL_FALSE;
}
/**
* \brief Returns true if the two rectangles are equal.
*/
SDL_FORCE_INLINE SDL_bool SDL_RectEquals(const SDL_Rect *a, const SDL_Rect *b)
{
return (a && b && (a->x == b->x) && (a->y == b->y) &&
(a->w == b->w) && (a->h == b->h)) ? SDL_TRUE : SDL_FALSE;
}
/**
* \brief Determine whether two rectangles intersect.
*
* \return SDL_TRUE if there is an intersection, SDL_FALSE otherwise.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasIntersection(const SDL_Rect * A,
const SDL_Rect * B);
/**
* \brief Calculate the intersection of two rectangles.
*
* \return SDL_TRUE if there is an intersection, SDL_FALSE otherwise.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IntersectRect(const SDL_Rect * A,
const SDL_Rect * B,
SDL_Rect * result);
/**
* \brief Calculate the union of two rectangles.
*/
extern DECLSPEC void SDLCALL SDL_UnionRect(const SDL_Rect * A,
const SDL_Rect * B,
SDL_Rect * result);
/**
* \brief Calculate a minimal rectangle enclosing a set of points
*
* \return SDL_TRUE if any points were within the clipping rect
*/
extern DECLSPEC SDL_bool SDLCALL SDL_EnclosePoints(const SDL_Point * points,
int count,
const SDL_Rect * clip,
SDL_Rect * result);
/**
* \brief Calculate the intersection of a rectangle and line segment.
*
* \return SDL_TRUE if there is an intersection, SDL_FALSE otherwise.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IntersectRectAndLine(const SDL_Rect *
rect, int *X1,
int *Y1, int *X2,
int *Y2);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_rect_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 4,445 | C | 28.838926 | 80 | 0.586727 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_system.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_system.h
*
* Include file for platform specific SDL API functions
*/
#ifndef SDL_system_h_
#define SDL_system_h_
#include "SDL_stdinc.h"
#include "SDL_keyboard.h"
#include "SDL_render.h"
#include "SDL_video.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* Platform specific functions for Windows */
#ifdef __WIN32__
/**
\brief Set a function that is called for every windows message, before TranslateMessage()
*/
typedef void (SDLCALL * SDL_WindowsMessageHook)(void *userdata, void *hWnd, unsigned int message, Uint64 wParam, Sint64 lParam);
extern DECLSPEC void SDLCALL SDL_SetWindowsMessageHook(SDL_WindowsMessageHook callback, void *userdata);
/**
\brief Returns the D3D9 adapter index that matches the specified display index.
This adapter index can be passed to IDirect3D9::CreateDevice and controls
on which monitor a full screen application will appear.
*/
extern DECLSPEC int SDLCALL SDL_Direct3D9GetAdapterIndex( int displayIndex );
typedef struct IDirect3DDevice9 IDirect3DDevice9;
/**
\brief Returns the D3D device associated with a renderer, or NULL if it's not a D3D renderer.
Once you are done using the device, you should release it to avoid a resource leak.
*/
extern DECLSPEC IDirect3DDevice9* SDLCALL SDL_RenderGetD3D9Device(SDL_Renderer * renderer);
/**
\brief Returns the DXGI Adapter and Output indices for the specified display index.
These can be passed to EnumAdapters and EnumOutputs respectively to get the objects
required to create a DX10 or DX11 device and swap chain.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_DXGIGetOutputInfo( int displayIndex, int *adapterIndex, int *outputIndex );
#endif /* __WIN32__ */
/* Platform specific functions for iOS */
#if defined(__IPHONEOS__) && __IPHONEOS__
#define SDL_iOSSetAnimationCallback(window, interval, callback, callbackParam) SDL_iPhoneSetAnimationCallback(window, interval, callback, callbackParam)
extern DECLSPEC int SDLCALL SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam);
#define SDL_iOSSetEventPump(enabled) SDL_iPhoneSetEventPump(enabled)
extern DECLSPEC void SDLCALL SDL_iPhoneSetEventPump(SDL_bool enabled);
#endif /* __IPHONEOS__ */
/* Platform specific functions for Android */
#if defined(__ANDROID__) && __ANDROID__
/**
\brief Get the JNI environment for the current thread
This returns JNIEnv*, but the prototype is void* so we don't need jni.h
*/
extern DECLSPEC void * SDLCALL SDL_AndroidGetJNIEnv(void);
/**
\brief Get the SDL Activity object for the application
This returns jobject, but the prototype is void* so we don't need jni.h
The jobject returned by SDL_AndroidGetActivity is a local reference.
It is the caller's responsibility to properly release it
(using env->Push/PopLocalFrame or manually with env->DeleteLocalRef)
*/
extern DECLSPEC void * SDLCALL SDL_AndroidGetActivity(void);
/**
\brief Return true if the application is running on Android TV
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsAndroidTV(void);
/**
See the official Android developer guide for more information:
http://developer.android.com/guide/topics/data/data-storage.html
*/
#define SDL_ANDROID_EXTERNAL_STORAGE_READ 0x01
#define SDL_ANDROID_EXTERNAL_STORAGE_WRITE 0x02
/**
\brief Get the path used for internal storage for this application.
This path is unique to your application and cannot be written to
by other applications.
*/
extern DECLSPEC const char * SDLCALL SDL_AndroidGetInternalStoragePath(void);
/**
\brief Get the current state of external storage, a bitmask of these values:
SDL_ANDROID_EXTERNAL_STORAGE_READ
SDL_ANDROID_EXTERNAL_STORAGE_WRITE
If external storage is currently unavailable, this will return 0.
*/
extern DECLSPEC int SDLCALL SDL_AndroidGetExternalStorageState(void);
/**
\brief Get the path used for external storage for this application.
This path is unique to your application, but is public and can be
written to by other applications.
*/
extern DECLSPEC const char * SDLCALL SDL_AndroidGetExternalStoragePath(void);
#endif /* __ANDROID__ */
/* Platform specific functions for WinRT */
#if defined(__WINRT__) && __WINRT__
/**
* \brief WinRT / Windows Phone path types
*/
typedef enum
{
/** \brief The installed app's root directory.
Files here are likely to be read-only. */
SDL_WINRT_PATH_INSTALLED_LOCATION,
/** \brief The app's local data store. Files may be written here */
SDL_WINRT_PATH_LOCAL_FOLDER,
/** \brief The app's roaming data store. Unsupported on Windows Phone.
Files written here may be copied to other machines via a network
connection.
*/
SDL_WINRT_PATH_ROAMING_FOLDER,
/** \brief The app's temporary data store. Unsupported on Windows Phone.
Files written here may be deleted at any time. */
SDL_WINRT_PATH_TEMP_FOLDER
} SDL_WinRT_Path;
/**
* \brief WinRT Device Family
*/
typedef enum
{
/** \brief Unknown family */
SDL_WINRT_DEVICEFAMILY_UNKNOWN,
/** \brief Desktop family*/
SDL_WINRT_DEVICEFAMILY_DESKTOP,
/** \brief Mobile family (for example smartphone) */
SDL_WINRT_DEVICEFAMILY_MOBILE,
/** \brief XBox family */
SDL_WINRT_DEVICEFAMILY_XBOX,
} SDL_WinRT_DeviceFamily;
/**
* \brief Retrieves a WinRT defined path on the local file system
*
* \note Documentation on most app-specific path types on WinRT
* can be found on MSDN, at the URL:
* http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx
*
* \param pathType The type of path to retrieve.
* \return A UCS-2 string (16-bit, wide-char) containing the path, or NULL
* if the path is not available for any reason. Not all paths are
* available on all versions of Windows. This is especially true on
* Windows Phone. Check the documentation for the given
* SDL_WinRT_Path for more information on which path types are
* supported where.
*/
extern DECLSPEC const wchar_t * SDLCALL SDL_WinRTGetFSPathUNICODE(SDL_WinRT_Path pathType);
/**
* \brief Retrieves a WinRT defined path on the local file system
*
* \note Documentation on most app-specific path types on WinRT
* can be found on MSDN, at the URL:
* http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx
*
* \param pathType The type of path to retrieve.
* \return A UTF-8 string (8-bit, multi-byte) containing the path, or NULL
* if the path is not available for any reason. Not all paths are
* available on all versions of Windows. This is especially true on
* Windows Phone. Check the documentation for the given
* SDL_WinRT_Path for more information on which path types are
* supported where.
*/
extern DECLSPEC const char * SDLCALL SDL_WinRTGetFSPathUTF8(SDL_WinRT_Path pathType);
/**
* \brief Detects the device family of WinRT plattform on runtime
*
* \return Device family
*/
extern DECLSPEC SDL_WinRT_DeviceFamily SDLCALL SDL_WinRTGetDeviceFamily();
#endif /* __WINRT__ */
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_system_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 8,292 | C | 32.439516 | 152 | 0.729619 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_config.h | /* include/SDL_config.h. Generated from SDL_config.h.in by configure. */
/*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_config_h_
#define SDL_config_h_
/**
* \file SDL_config.h.in
*
* This is a set of defines to configure the SDL features
*/
/* General platform specific identifiers */
#include "SDL_platform.h"
/* Make sure that this isn't included by Visual C++ */
#ifdef _MSC_VER
#error You should run hg revert SDL_config.h
#endif
/* C language features */
/* #undef const */
/* #undef inline */
/* #undef volatile */
/* C datatypes */
#ifdef __LP64__
#define SIZEOF_VOIDP 8
#else
#define SIZEOF_VOIDP 4
#endif
#define HAVE_GCC_ATOMICS 1
/* #undef HAVE_GCC_SYNC_LOCK_TEST_AND_SET */
/* Comment this if you want to build without any C library requirements */
#define HAVE_LIBC 1
#if HAVE_LIBC
/* Useful headers */
#define STDC_HEADERS 1
#define HAVE_ALLOCA_H 1
#define HAVE_CTYPE_H 1
#define HAVE_FLOAT_H 1
#define HAVE_ICONV_H 1
#define HAVE_INTTYPES_H 1
#define HAVE_LIMITS_H 1
#define HAVE_MALLOC_H 1
#define HAVE_MATH_H 1
#define HAVE_MEMORY_H 1
#define HAVE_SIGNAL_H 1
#define HAVE_STDARG_H 1
#define HAVE_STDINT_H 1
#define HAVE_STDIO_H 1
#define HAVE_STDLIB_H 1
#define HAVE_STRINGS_H 1
#define HAVE_STRING_H 1
#define HAVE_SYS_TYPES_H 1
#define HAVE_WCHAR_H 1
/* #undef HAVE_PTHREAD_NP_H */
/* #undef HAVE_LIBUNWIND_H */
/* C library functions */
#define HAVE_MALLOC 1
#define HAVE_CALLOC 1
#define HAVE_REALLOC 1
#define HAVE_FREE 1
#define HAVE_ALLOCA 1
#ifndef __WIN32__ /* Don't use C runtime versions of these on Windows */
#define HAVE_GETENV 1
#define HAVE_SETENV 1
#define HAVE_PUTENV 1
#define HAVE_UNSETENV 1
#endif
#define HAVE_QSORT 1
#define HAVE_ABS 1
#define HAVE_BCOPY 1
#define HAVE_MEMSET 1
#define HAVE_MEMCPY 1
#define HAVE_MEMMOVE 1
#define HAVE_MEMCMP 1
#define HAVE_WCSLEN 1
/* #undef HAVE_WCSLCPY */
/* #undef HAVE_WCSLCAT */
#define HAVE_WCSCMP 1
#define HAVE_STRLEN 1
/* #undef HAVE_STRLCPY */
/* #undef HAVE_STRLCAT */
/* #undef HAVE__STRREV */
/* #undef HAVE__STRUPR */
/* #undef HAVE__STRLWR */
/* #undef HAVE_INDEX */
/* #undef HAVE_RINDEX */
#define HAVE_STRCHR 1
#define HAVE_STRRCHR 1
#define HAVE_STRSTR 1
/* #undef HAVE_ITOA */
/* #undef HAVE__LTOA */
/* #undef HAVE__UITOA */
/* #undef HAVE__ULTOA */
#define HAVE_STRTOL 1
#define HAVE_STRTOUL 1
/* #undef HAVE__I64TOA */
/* #undef HAVE__UI64TOA */
#define HAVE_STRTOLL 1
#define HAVE_STRTOULL 1
#define HAVE_STRTOD 1
#define HAVE_ATOI 1
#define HAVE_ATOF 1
#define HAVE_STRCMP 1
#define HAVE_STRNCMP 1
/* #undef HAVE__STRICMP */
#define HAVE_STRCASECMP 1
/* #undef HAVE__STRNICMP */
#define HAVE_STRNCASECMP 1
/* #undef HAVE_SSCANF */
#define HAVE_VSSCANF 1
/* #undef HAVE_SNPRINTF */
#define HAVE_VSNPRINTF 1
#define HAVE_M_PI /**/
#define HAVE_ACOS 1
#define HAVE_ACOSF 1
#define HAVE_ASIN 1
#define HAVE_ASINF 1
#define HAVE_ATAN 1
#define HAVE_ATANF 1
#define HAVE_ATAN2 1
#define HAVE_ATAN2F 1
#define HAVE_CEIL 1
#define HAVE_CEILF 1
#define HAVE_COPYSIGN 1
#define HAVE_COPYSIGNF 1
#define HAVE_COS 1
#define HAVE_COSF 1
#define HAVE_FABS 1
#define HAVE_FABSF 1
#define HAVE_FLOOR 1
#define HAVE_FLOORF 1
#define HAVE_FMOD 1
#define HAVE_FMODF 1
#define HAVE_LOG 1
#define HAVE_LOGF 1
#define HAVE_LOG10 1
#define HAVE_LOG10F 1
#define HAVE_POW 1
#define HAVE_POWF 1
#define HAVE_SCALBN 1
#define HAVE_SCALBNF 1
#define HAVE_SIN 1
#define HAVE_SINF 1
#define HAVE_SQRT 1
#define HAVE_SQRTF 1
#define HAVE_TAN 1
#define HAVE_TANF 1
#define HAVE_FOPEN64 1
#define HAVE_FSEEKO 1
#define HAVE_FSEEKO64 1
#define HAVE_SIGACTION 1
#define HAVE_SA_SIGACTION 1
#define HAVE_SETJMP 1
#define HAVE_NANOSLEEP 1
#define HAVE_SYSCONF 1
/* #undef HAVE_SYSCTLBYNAME */
#define HAVE_CLOCK_GETTIME 1
/* #undef HAVE_GETPAGESIZE */
#define HAVE_MPROTECT 1
#define HAVE_ICONV 1
#define HAVE_PTHREAD_SETNAME_NP 1
/* #undef HAVE_PTHREAD_SET_NAME_NP */
#define HAVE_SEM_TIMEDWAIT 1
#define HAVE_GETAUXVAL 1
#define HAVE_POLL 1
#else
#define HAVE_STDARG_H 1
#define HAVE_STDDEF_H 1
#define HAVE_STDINT_H 1
#endif /* HAVE_LIBC */
/* #undef HAVE_ALTIVEC_H */
#define HAVE_DBUS_DBUS_H 1
#define HAVE_FCITX_FRONTEND_H 1
#define HAVE_IBUS_IBUS_H 1
#define HAVE_IMMINTRIN_H 1
#define HAVE_LIBSAMPLERATE_H 1
#define HAVE_LIBUDEV_H 1
/* #undef HAVE_DDRAW_H */
/* #undef HAVE_DINPUT_H */
/* #undef HAVE_DSOUND_H */
/* #undef HAVE_DXGI_H */
/* #undef HAVE_XINPUT_H */
/* #undef HAVE_XINPUT_GAMEPAD_EX */
/* #undef HAVE_XINPUT_STATE_EX */
/* SDL internal assertion support */
/* #undef SDL_DEFAULT_ASSERT_LEVEL */
/* Allow disabling of core subsystems */
/* #undef SDL_ATOMIC_DISABLED */
/* #undef SDL_AUDIO_DISABLED */
/* #undef SDL_CPUINFO_DISABLED */
/* #undef SDL_EVENTS_DISABLED */
/* #undef SDL_FILE_DISABLED */
/* #undef SDL_JOYSTICK_DISABLED */
/* #undef SDL_HAPTIC_DISABLED */
/* #undef SDL_LOADSO_DISABLED */
/* #undef SDL_RENDER_DISABLED */
/* #undef SDL_THREADS_DISABLED */
/* #undef SDL_TIMERS_DISABLED */
/* #undef SDL_VIDEO_DISABLED */
/* #undef SDL_POWER_DISABLED */
/* #undef SDL_FILESYSTEM_DISABLED */
/* Enable various audio drivers */
#define SDL_AUDIO_DRIVER_ALSA 1
/* #undef SDL_AUDIO_DRIVER_ALSA_DYNAMIC */
/* #undef SDL_AUDIO_DRIVER_ANDROID */
/* #undef SDL_AUDIO_DRIVER_ARTS */
/* #undef SDL_AUDIO_DRIVER_ARTS_DYNAMIC */
/* #undef SDL_AUDIO_DRIVER_COREAUDIO */
#define SDL_AUDIO_DRIVER_DISK 1
/* #undef SDL_AUDIO_DRIVER_DSOUND */
#define SDL_AUDIO_DRIVER_DUMMY 1
/* #undef SDL_AUDIO_DRIVER_EMSCRIPTEN */
/* #undef SDL_AUDIO_DRIVER_ESD */
/* #undef SDL_AUDIO_DRIVER_ESD_DYNAMIC */
/* #undef SDL_AUDIO_DRIVER_FUSIONSOUND */
/* #undef SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC */
/* #undef SDL_AUDIO_DRIVER_HAIKU */
/* #undef SDL_AUDIO_DRIVER_JACK */
/* #undef SDL_AUDIO_DRIVER_JACK_DYNAMIC */
/* #undef SDL_AUDIO_DRIVER_NACL */
/* #undef SDL_AUDIO_DRIVER_NAS */
/* #undef SDL_AUDIO_DRIVER_NAS_DYNAMIC */
/* #undef SDL_AUDIO_DRIVER_NETBSD */
#define SDL_AUDIO_DRIVER_OSS 1
/* #undef SDL_AUDIO_DRIVER_OSS_SOUNDCARD_H */
/* #undef SDL_AUDIO_DRIVER_PAUDIO */
#define SDL_AUDIO_DRIVER_PULSEAUDIO 1
/* #undef SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC */
/* #undef SDL_AUDIO_DRIVER_QSA */
#define SDL_AUDIO_DRIVER_SNDIO 1
/* #undef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC */
/* #undef SDL_AUDIO_DRIVER_SUNAUDIO */
/* #undef SDL_AUDIO_DRIVER_WASAPI */
/* #undef SDL_AUDIO_DRIVER_WINMM */
/* Enable various input drivers */
#define SDL_INPUT_LINUXEV 1
#define SDL_INPUT_LINUXKD 1
/* #undef SDL_INPUT_TSLIB */
/* #undef SDL_JOYSTICK_HAIKU */
/* #undef SDL_JOYSTICK_DINPUT */
/* #undef SDL_JOYSTICK_XINPUT */
/* #undef SDL_JOYSTICK_DUMMY */
/* #undef SDL_JOYSTICK_IOKIT */
#define SDL_JOYSTICK_LINUX 1
/* #undef SDL_JOYSTICK_ANDROID */
/* #undef SDL_JOYSTICK_WINMM */
/* #undef SDL_JOYSTICK_USBHID */
/* #undef SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H */
/* #undef SDL_JOYSTICK_EMSCRIPTEN */
/* #undef SDL_HAPTIC_DUMMY */
/* #undef SDL_HAPTIC_ANDROID */
#define SDL_HAPTIC_LINUX 1
/* #undef SDL_HAPTIC_IOKIT */
/* #undef SDL_HAPTIC_DINPUT */
/* #undef SDL_HAPTIC_XINPUT */
/* Enable various shared object loading systems */
#define SDL_LOADSO_DLOPEN 1
/* #undef SDL_LOADSO_DUMMY */
/* #undef SDL_LOADSO_LDG */
/* #undef SDL_LOADSO_WINDOWS */
/* Enable various threading systems */
#define SDL_THREAD_PTHREAD 1
#define SDL_THREAD_PTHREAD_RECURSIVE_MUTEX 1
/* #undef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP */
/* #undef SDL_THREAD_WINDOWS */
/* Enable various timer systems */
/* #undef SDL_TIMER_HAIKU */
/* #undef SDL_TIMER_DUMMY */
#define SDL_TIMER_UNIX 1
/* #undef SDL_TIMER_WINDOWS */
/* Enable various video drivers */
/* #undef SDL_VIDEO_DRIVER_HAIKU */
/* #undef SDL_VIDEO_DRIVER_COCOA */
/* #undef SDL_VIDEO_DRIVER_DIRECTFB */
/* #undef SDL_VIDEO_DRIVER_DIRECTFB_DYNAMIC */
#define SDL_VIDEO_DRIVER_DUMMY 1
/* #undef SDL_VIDEO_DRIVER_WINDOWS */
#define SDL_VIDEO_DRIVER_WAYLAND 1
#define SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH 1
/* #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC */
/* #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL */
/* #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR */
/* #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON */
#define SDL_VIDEO_DRIVER_MIR 1
#define SDL_VIDEO_DRIVER_MIR_DYNAMIC "libmirclient.so.9"
#define SDL_VIDEO_DRIVER_MIR_DYNAMIC_XKBCOMMON "libxkbcommon.so.0"
#define SDL_VIDEO_DRIVER_X11 1
/* #undef SDL_VIDEO_DRIVER_RPI */
/* #undef SDL_VIDEO_DRIVER_KMSDRM */
/* #undef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC */
/* #undef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM */
/* #undef SDL_VIDEO_DRIVER_ANDROID */
/* #undef SDL_VIDEO_DRIVER_EMSCRIPTEN */
/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC */
/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT */
/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XCURSOR */
/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XINERAMA */
/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2 */
/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR */
/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS */
/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XVIDMODE */
#define SDL_VIDEO_DRIVER_X11_XCURSOR 1
#define SDL_VIDEO_DRIVER_X11_XDBE 1
#define SDL_VIDEO_DRIVER_X11_XINERAMA 1
#define SDL_VIDEO_DRIVER_X11_XINPUT2 1
#define SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH 1
#define SDL_VIDEO_DRIVER_X11_XRANDR 1
#define SDL_VIDEO_DRIVER_X11_XSCRNSAVER 1
#define SDL_VIDEO_DRIVER_X11_XSHAPE 1
#define SDL_VIDEO_DRIVER_X11_XVIDMODE 1
#define SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS 1
#define SDL_VIDEO_DRIVER_X11_CONST_PARAM_XEXTADDDISPLAY 1
#define SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM 1
/* #undef SDL_VIDEO_DRIVER_NACL */
/* #undef SDL_VIDEO_DRIVER_VIVANTE */
/* #undef SDL_VIDEO_DRIVER_VIVANTE_VDK */
/* #undef SDL_VIDEO_DRIVER_QNX */
/* #undef SDL_VIDEO_RENDER_D3D */
/* #undef SDL_VIDEO_RENDER_D3D11 */
#define SDL_VIDEO_RENDER_OGL 1
/* #undef SDL_VIDEO_RENDER_OGL_ES */
#define SDL_VIDEO_RENDER_OGL_ES2 1
/* #undef SDL_VIDEO_RENDER_DIRECTFB */
/* #undef SDL_VIDEO_RENDER_METAL */
/* Enable OpenGL support */
#define SDL_VIDEO_OPENGL 1
/* #undef SDL_VIDEO_OPENGL_ES */
#define SDL_VIDEO_OPENGL_ES2 1
/* #undef SDL_VIDEO_OPENGL_BGL */
/* #undef SDL_VIDEO_OPENGL_CGL */
#define SDL_VIDEO_OPENGL_EGL 1
#define SDL_VIDEO_OPENGL_GLX 1
/* #undef SDL_VIDEO_OPENGL_WGL */
/* #undef SDL_VIDEO_OPENGL_OSMESA */
/* #undef SDL_VIDEO_OPENGL_OSMESA_DYNAMIC */
/* Enable Vulkan support */
#define SDL_VIDEO_VULKAN 1
/* Enable system power support */
#define SDL_POWER_LINUX 1
/* #undef SDL_POWER_WINDOWS */
/* #undef SDL_POWER_MACOSX */
/* #undef SDL_POWER_HAIKU */
/* #undef SDL_POWER_ANDROID */
/* #undef SDL_POWER_EMSCRIPTEN */
/* #undef SDL_POWER_HARDWIRED */
/* Enable system filesystem support */
/* #undef SDL_FILESYSTEM_HAIKU */
/* #undef SDL_FILESYSTEM_COCOA */
/* #undef SDL_FILESYSTEM_DUMMY */
#define SDL_FILESYSTEM_UNIX 1
/* #undef SDL_FILESYSTEM_WINDOWS */
/* #undef SDL_FILESYSTEM_NACL */
/* #undef SDL_FILESYSTEM_ANDROID */
/* #undef SDL_FILESYSTEM_EMSCRIPTEN */
/* Enable assembly routines */
#define SDL_ASSEMBLY_ROUTINES 1
/* #undef SDL_ALTIVEC_BLITTERS */
/* Enable ime support */
#define SDL_USE_IME 1
/* Enable dynamic udev support */
#define SDL_UDEV_DYNAMIC "libudev.so.1"
/* Enable dynamic libsamplerate support */
#define SDL_LIBSAMPLERATE_DYNAMIC "libsamplerate.so.0"
#endif /* SDL_config_h_ */
| 12,015 | C | 28.23601 | 76 | 0.716271 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_test_random.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_test_random.h
*
* Include file for SDL test framework.
*
* This code is a part of the SDL2_test library, not the main SDL library.
*/
/*
A "32-bit Multiply with carry random number generator. Very fast.
Includes a list of recommended multipliers.
multiply-with-carry generator: x(n) = a*x(n-1) + carry mod 2^32.
period: (a*2^31)-1
*/
#ifndef SDL_test_random_h_
#define SDL_test_random_h_
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* --- Definitions */
/*
* Macros that return a random number in a specific format.
*/
#define SDLTest_RandomInt(c) ((int)SDLTest_Random(c))
/*
* Context structure for the random number generator state.
*/
typedef struct {
unsigned int a;
unsigned int x;
unsigned int c;
unsigned int ah;
unsigned int al;
} SDLTest_RandomContext;
/* --- Function prototypes */
/**
* \brief Initialize random number generator with two integers.
*
* Note: The random sequence of numbers returned by ...Random() is the
* same for the same two integers and has a period of 2^31.
*
* \param rndContext pointer to context structure
* \param xi integer that defines the random sequence
* \param ci integer that defines the random sequence
*
*/
void SDLTest_RandomInit(SDLTest_RandomContext * rndContext, unsigned int xi,
unsigned int ci);
/**
* \brief Initialize random number generator based on current system time.
*
* \param rndContext pointer to context structure
*
*/
void SDLTest_RandomInitTime(SDLTest_RandomContext *rndContext);
/**
* \brief Initialize random number generator based on current system time.
*
* Note: ...RandomInit() or ...RandomInitTime() must have been called
* before using this function.
*
* \param rndContext pointer to context structure
*
* \returns A random number (32bit unsigned integer)
*
*/
unsigned int SDLTest_Random(SDLTest_RandomContext *rndContext);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_test_random_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 3,156 | C | 26.215517 | 77 | 0.704373 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_test_md5.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_test_md5.h
*
* Include file for SDL test framework.
*
* This code is a part of the SDL2_test library, not the main SDL library.
*/
/*
***********************************************************************
** Header file for implementation of MD5 **
** RSA Data Security, Inc. MD5 Message-Digest Algorithm **
** Created: 2/17/90 RLR **
** Revised: 12/27/90 SRD,AJ,BSK,JT Reference C version **
** Revised (for MD5): RLR 4/27/91 **
** -- G modified to have y&~z instead of y&z **
** -- FF, GG, HH modified to add in last register done **
** -- Access pattern: round 2 works mod 5, round 3 works mod 3 **
** -- distinct additive constant for each step **
** -- round 4 added, working mod 7 **
***********************************************************************
*/
/*
***********************************************************************
** Message-digest routines: **
** To form the message digest for a message M **
** (1) Initialize a context buffer mdContext using MD5Init **
** (2) Call MD5Update on mdContext and M **
** (3) Call MD5Final on mdContext **
** The message digest is now in mdContext->digest[0...15] **
***********************************************************************
*/
#ifndef SDL_test_md5_h_
#define SDL_test_md5_h_
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* ------------ Definitions --------- */
/* typedef a 32-bit type */
typedef unsigned long int MD5UINT4;
/* Data structure for MD5 (Message-Digest) computation */
typedef struct {
MD5UINT4 i[2]; /* number of _bits_ handled mod 2^64 */
MD5UINT4 buf[4]; /* scratch buffer */
unsigned char in[64]; /* input buffer */
unsigned char digest[16]; /* actual digest after Md5Final call */
} SDLTest_Md5Context;
/* ---------- Function Prototypes ------------- */
/**
* \brief initialize the context
*
* \param mdContext pointer to context variable
*
* Note: The function initializes the message-digest context
* mdContext. Call before each new use of the context -
* all fields are set to zero.
*/
void SDLTest_Md5Init(SDLTest_Md5Context * mdContext);
/**
* \brief update digest from variable length data
*
* \param mdContext pointer to context variable
* \param inBuf pointer to data array/string
* \param inLen length of data array/string
*
* Note: The function updates the message-digest context to account
* for the presence of each of the characters inBuf[0..inLen-1]
* in the message whose digest is being computed.
*/
void SDLTest_Md5Update(SDLTest_Md5Context * mdContext, unsigned char *inBuf,
unsigned int inLen);
/**
* \brief complete digest computation
*
* \param mdContext pointer to context variable
*
* Note: The function terminates the message-digest computation and
* ends with the desired message digest in mdContext.digest[0..15].
* Always call before using the digest[] variable.
*/
void SDLTest_Md5Final(SDLTest_Md5Context * mdContext);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_test_md5_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 4,630 | C | 34.623077 | 77 | 0.578186 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_opengles.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_opengles.h
*
* This is a simple file to encapsulate the OpenGL ES 1.X API headers.
*/
#include "SDL_config.h"
#ifdef __IPHONEOS__
#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>
#else
#include <GLES/gl.h>
#include <GLES/glext.h>
#endif
#ifndef APIENTRY
#define APIENTRY
#endif
| 1,254 | C | 30.374999 | 76 | 0.746411 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_log.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_log.h
*
* Simple log messages with categories and priorities.
*
* By default logs are quiet, but if you're debugging SDL you might want:
*
* SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN);
*
* Here's where the messages go on different platforms:
* Windows: debug output stream
* Android: log output
* Others: standard error output (stderr)
*/
#ifndef SDL_log_h_
#define SDL_log_h_
#include "SDL_stdinc.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief The maximum size of a log message
*
* Messages longer than the maximum size will be truncated
*/
#define SDL_MAX_LOG_MESSAGE 4096
/**
* \brief The predefined log categories
*
* By default the application category is enabled at the INFO level,
* the assert category is enabled at the WARN level, test is enabled
* at the VERBOSE level and all other categories are enabled at the
* CRITICAL level.
*/
enum
{
SDL_LOG_CATEGORY_APPLICATION,
SDL_LOG_CATEGORY_ERROR,
SDL_LOG_CATEGORY_ASSERT,
SDL_LOG_CATEGORY_SYSTEM,
SDL_LOG_CATEGORY_AUDIO,
SDL_LOG_CATEGORY_VIDEO,
SDL_LOG_CATEGORY_RENDER,
SDL_LOG_CATEGORY_INPUT,
SDL_LOG_CATEGORY_TEST,
/* Reserved for future SDL library use */
SDL_LOG_CATEGORY_RESERVED1,
SDL_LOG_CATEGORY_RESERVED2,
SDL_LOG_CATEGORY_RESERVED3,
SDL_LOG_CATEGORY_RESERVED4,
SDL_LOG_CATEGORY_RESERVED5,
SDL_LOG_CATEGORY_RESERVED6,
SDL_LOG_CATEGORY_RESERVED7,
SDL_LOG_CATEGORY_RESERVED8,
SDL_LOG_CATEGORY_RESERVED9,
SDL_LOG_CATEGORY_RESERVED10,
/* Beyond this point is reserved for application use, e.g.
enum {
MYAPP_CATEGORY_AWESOME1 = SDL_LOG_CATEGORY_CUSTOM,
MYAPP_CATEGORY_AWESOME2,
MYAPP_CATEGORY_AWESOME3,
...
};
*/
SDL_LOG_CATEGORY_CUSTOM
};
/**
* \brief The predefined log priorities
*/
typedef enum
{
SDL_LOG_PRIORITY_VERBOSE = 1,
SDL_LOG_PRIORITY_DEBUG,
SDL_LOG_PRIORITY_INFO,
SDL_LOG_PRIORITY_WARN,
SDL_LOG_PRIORITY_ERROR,
SDL_LOG_PRIORITY_CRITICAL,
SDL_NUM_LOG_PRIORITIES
} SDL_LogPriority;
/**
* \brief Set the priority of all log categories
*/
extern DECLSPEC void SDLCALL SDL_LogSetAllPriority(SDL_LogPriority priority);
/**
* \brief Set the priority of a particular log category
*/
extern DECLSPEC void SDLCALL SDL_LogSetPriority(int category,
SDL_LogPriority priority);
/**
* \brief Get the priority of a particular log category
*/
extern DECLSPEC SDL_LogPriority SDLCALL SDL_LogGetPriority(int category);
/**
* \brief Reset all priorities to default.
*
* \note This is called in SDL_Quit().
*/
extern DECLSPEC void SDLCALL SDL_LogResetPriorities(void);
/**
* \brief Log a message with SDL_LOG_CATEGORY_APPLICATION and SDL_LOG_PRIORITY_INFO
*/
extern DECLSPEC void SDLCALL SDL_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1);
/**
* \brief Log a message with SDL_LOG_PRIORITY_VERBOSE
*/
extern DECLSPEC void SDLCALL SDL_LogVerbose(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2);
/**
* \brief Log a message with SDL_LOG_PRIORITY_DEBUG
*/
extern DECLSPEC void SDLCALL SDL_LogDebug(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2);
/**
* \brief Log a message with SDL_LOG_PRIORITY_INFO
*/
extern DECLSPEC void SDLCALL SDL_LogInfo(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2);
/**
* \brief Log a message with SDL_LOG_PRIORITY_WARN
*/
extern DECLSPEC void SDLCALL SDL_LogWarn(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2);
/**
* \brief Log a message with SDL_LOG_PRIORITY_ERROR
*/
extern DECLSPEC void SDLCALL SDL_LogError(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2);
/**
* \brief Log a message with SDL_LOG_PRIORITY_CRITICAL
*/
extern DECLSPEC void SDLCALL SDL_LogCritical(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2);
/**
* \brief Log a message with the specified category and priority.
*/
extern DECLSPEC void SDLCALL SDL_LogMessage(int category,
SDL_LogPriority priority,
SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(3);
/**
* \brief Log a message with the specified category and priority.
*/
extern DECLSPEC void SDLCALL SDL_LogMessageV(int category,
SDL_LogPriority priority,
const char *fmt, va_list ap);
/**
* \brief The prototype for the log output function
*/
typedef void (SDLCALL *SDL_LogOutputFunction)(void *userdata, int category, SDL_LogPriority priority, const char *message);
/**
* \brief Get the current log output function.
*/
extern DECLSPEC void SDLCALL SDL_LogGetOutputFunction(SDL_LogOutputFunction *callback, void **userdata);
/**
* \brief This function allows you to replace the default log output
* function with one of your own.
*/
extern DECLSPEC void SDLCALL SDL_LogSetOutputFunction(SDL_LogOutputFunction callback, void *userdata);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_log_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 6,491 | C | 29.622641 | 132 | 0.690032 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_audio.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_audio.h
*
* Access to the raw audio mixing buffer for the SDL library.
*/
#ifndef SDL_audio_h_
#define SDL_audio_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_endian.h"
#include "SDL_mutex.h"
#include "SDL_thread.h"
#include "SDL_rwops.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Audio format flags.
*
* These are what the 16 bits in SDL_AudioFormat currently mean...
* (Unspecified bits are always zero).
*
* \verbatim
++-----------------------sample is signed if set
||
|| ++-----------sample is bigendian if set
|| ||
|| || ++---sample is float if set
|| || ||
|| || || +---sample bit size---+
|| || || | |
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
\endverbatim
*
* There are macros in SDL 2.0 and later to query these bits.
*/
typedef Uint16 SDL_AudioFormat;
/**
* \name Audio flags
*/
/* @{ */
#define SDL_AUDIO_MASK_BITSIZE (0xFF)
#define SDL_AUDIO_MASK_DATATYPE (1<<8)
#define SDL_AUDIO_MASK_ENDIAN (1<<12)
#define SDL_AUDIO_MASK_SIGNED (1<<15)
#define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE)
#define SDL_AUDIO_ISFLOAT(x) (x & SDL_AUDIO_MASK_DATATYPE)
#define SDL_AUDIO_ISBIGENDIAN(x) (x & SDL_AUDIO_MASK_ENDIAN)
#define SDL_AUDIO_ISSIGNED(x) (x & SDL_AUDIO_MASK_SIGNED)
#define SDL_AUDIO_ISINT(x) (!SDL_AUDIO_ISFLOAT(x))
#define SDL_AUDIO_ISLITTLEENDIAN(x) (!SDL_AUDIO_ISBIGENDIAN(x))
#define SDL_AUDIO_ISUNSIGNED(x) (!SDL_AUDIO_ISSIGNED(x))
/**
* \name Audio format flags
*
* Defaults to LSB byte order.
*/
/* @{ */
#define AUDIO_U8 0x0008 /**< Unsigned 8-bit samples */
#define AUDIO_S8 0x8008 /**< Signed 8-bit samples */
#define AUDIO_U16LSB 0x0010 /**< Unsigned 16-bit samples */
#define AUDIO_S16LSB 0x8010 /**< Signed 16-bit samples */
#define AUDIO_U16MSB 0x1010 /**< As above, but big-endian byte order */
#define AUDIO_S16MSB 0x9010 /**< As above, but big-endian byte order */
#define AUDIO_U16 AUDIO_U16LSB
#define AUDIO_S16 AUDIO_S16LSB
/* @} */
/**
* \name int32 support
*/
/* @{ */
#define AUDIO_S32LSB 0x8020 /**< 32-bit integer samples */
#define AUDIO_S32MSB 0x9020 /**< As above, but big-endian byte order */
#define AUDIO_S32 AUDIO_S32LSB
/* @} */
/**
* \name float32 support
*/
/* @{ */
#define AUDIO_F32LSB 0x8120 /**< 32-bit floating point samples */
#define AUDIO_F32MSB 0x9120 /**< As above, but big-endian byte order */
#define AUDIO_F32 AUDIO_F32LSB
/* @} */
/**
* \name Native audio byte ordering
*/
/* @{ */
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define AUDIO_U16SYS AUDIO_U16LSB
#define AUDIO_S16SYS AUDIO_S16LSB
#define AUDIO_S32SYS AUDIO_S32LSB
#define AUDIO_F32SYS AUDIO_F32LSB
#else
#define AUDIO_U16SYS AUDIO_U16MSB
#define AUDIO_S16SYS AUDIO_S16MSB
#define AUDIO_S32SYS AUDIO_S32MSB
#define AUDIO_F32SYS AUDIO_F32MSB
#endif
/* @} */
/**
* \name Allow change flags
*
* Which audio format changes are allowed when opening a device.
*/
/* @{ */
#define SDL_AUDIO_ALLOW_FREQUENCY_CHANGE 0x00000001
#define SDL_AUDIO_ALLOW_FORMAT_CHANGE 0x00000002
#define SDL_AUDIO_ALLOW_CHANNELS_CHANGE 0x00000004
#define SDL_AUDIO_ALLOW_ANY_CHANGE (SDL_AUDIO_ALLOW_FREQUENCY_CHANGE|SDL_AUDIO_ALLOW_FORMAT_CHANGE|SDL_AUDIO_ALLOW_CHANNELS_CHANGE)
/* @} */
/* @} *//* Audio flags */
/**
* This function is called when the audio device needs more data.
*
* \param userdata An application-specific parameter saved in
* the SDL_AudioSpec structure
* \param stream A pointer to the audio data buffer.
* \param len The length of that buffer in bytes.
*
* Once the callback returns, the buffer will no longer be valid.
* Stereo samples are stored in a LRLRLR ordering.
*
* You can choose to avoid callbacks and use SDL_QueueAudio() instead, if
* you like. Just open your audio device with a NULL callback.
*/
typedef void (SDLCALL * SDL_AudioCallback) (void *userdata, Uint8 * stream,
int len);
/**
* The calculated values in this structure are calculated by SDL_OpenAudio().
*
* For multi-channel audio, the default SDL channel mapping is:
* 2: FL FR (stereo)
* 3: FL FR LFE (2.1 surround)
* 4: FL FR BL BR (quad)
* 5: FL FR FC BL BR (quad + center)
* 6: FL FR FC LFE SL SR (5.1 surround - last two can also be BL BR)
* 7: FL FR FC LFE BC SL SR (6.1 surround)
* 8: FL FR FC LFE BL BR SL SR (7.1 surround)
*/
typedef struct SDL_AudioSpec
{
int freq; /**< DSP frequency -- samples per second */
SDL_AudioFormat format; /**< Audio data format */
Uint8 channels; /**< Number of channels: 1 mono, 2 stereo */
Uint8 silence; /**< Audio buffer silence value (calculated) */
Uint16 samples; /**< Audio buffer size in sample FRAMES (total samples divided by channel count) */
Uint16 padding; /**< Necessary for some compile environments */
Uint32 size; /**< Audio buffer size in bytes (calculated) */
SDL_AudioCallback callback; /**< Callback that feeds the audio device (NULL to use SDL_QueueAudio()). */
void *userdata; /**< Userdata passed to callback (ignored for NULL callbacks). */
} SDL_AudioSpec;
struct SDL_AudioCVT;
typedef void (SDLCALL * SDL_AudioFilter) (struct SDL_AudioCVT * cvt,
SDL_AudioFormat format);
/**
* \brief Upper limit of filters in SDL_AudioCVT
*
* The maximum number of SDL_AudioFilter functions in SDL_AudioCVT is
* currently limited to 9. The SDL_AudioCVT.filters array has 10 pointers,
* one of which is the terminating NULL pointer.
*/
#define SDL_AUDIOCVT_MAX_FILTERS 9
/**
* \struct SDL_AudioCVT
* \brief A structure to hold a set of audio conversion filters and buffers.
*
* Note that various parts of the conversion pipeline can take advantage
* of SIMD operations (like SSE2, for example). SDL_AudioCVT doesn't require
* you to pass it aligned data, but can possibly run much faster if you
* set both its (buf) field to a pointer that is aligned to 16 bytes, and its
* (len) field to something that's a multiple of 16, if possible.
*/
#ifdef __GNUC__
/* This structure is 84 bytes on 32-bit architectures, make sure GCC doesn't
pad it out to 88 bytes to guarantee ABI compatibility between compilers.
vvv
The next time we rev the ABI, make sure to size the ints and add padding.
*/
#define SDL_AUDIOCVT_PACKED __attribute__((packed))
#else
#define SDL_AUDIOCVT_PACKED
#endif
/* */
typedef struct SDL_AudioCVT
{
int needed; /**< Set to 1 if conversion possible */
SDL_AudioFormat src_format; /**< Source audio format */
SDL_AudioFormat dst_format; /**< Target audio format */
double rate_incr; /**< Rate conversion increment */
Uint8 *buf; /**< Buffer to hold entire audio data */
int len; /**< Length of original audio buffer */
int len_cvt; /**< Length of converted audio buffer */
int len_mult; /**< buffer must be len*len_mult big */
double len_ratio; /**< Given len, final size is len*len_ratio */
SDL_AudioFilter filters[SDL_AUDIOCVT_MAX_FILTERS + 1]; /**< NULL-terminated list of filter functions */
int filter_index; /**< Current audio conversion function */
} SDL_AUDIOCVT_PACKED SDL_AudioCVT;
/* Function prototypes */
/**
* \name Driver discovery functions
*
* These functions return the list of built in audio drivers, in the
* order that they are normally initialized by default.
*/
/* @{ */
extern DECLSPEC int SDLCALL SDL_GetNumAudioDrivers(void);
extern DECLSPEC const char *SDLCALL SDL_GetAudioDriver(int index);
/* @} */
/**
* \name Initialization and cleanup
*
* \internal These functions are used internally, and should not be used unless
* you have a specific need to specify the audio driver you want to
* use. You should normally use SDL_Init() or SDL_InitSubSystem().
*/
/* @{ */
extern DECLSPEC int SDLCALL SDL_AudioInit(const char *driver_name);
extern DECLSPEC void SDLCALL SDL_AudioQuit(void);
/* @} */
/**
* This function returns the name of the current audio driver, or NULL
* if no driver has been initialized.
*/
extern DECLSPEC const char *SDLCALL SDL_GetCurrentAudioDriver(void);
/**
* This function opens the audio device with the desired parameters, and
* returns 0 if successful, placing the actual hardware parameters in the
* structure pointed to by \c obtained. If \c obtained is NULL, the audio
* data passed to the callback function will be guaranteed to be in the
* requested format, and will be automatically converted to the hardware
* audio format if necessary. This function returns -1 if it failed
* to open the audio device, or couldn't set up the audio thread.
*
* When filling in the desired audio spec structure,
* - \c desired->freq should be the desired audio frequency in samples-per-
* second.
* - \c desired->format should be the desired audio format.
* - \c desired->samples is the desired size of the audio buffer, in
* samples. This number should be a power of two, and may be adjusted by
* the audio driver to a value more suitable for the hardware. Good values
* seem to range between 512 and 8096 inclusive, depending on the
* application and CPU speed. Smaller values yield faster response time,
* but can lead to underflow if the application is doing heavy processing
* and cannot fill the audio buffer in time. A stereo sample consists of
* both right and left channels in LR ordering.
* Note that the number of samples is directly related to time by the
* following formula: \code ms = (samples*1000)/freq \endcode
* - \c desired->size is the size in bytes of the audio buffer, and is
* calculated by SDL_OpenAudio().
* - \c desired->silence is the value used to set the buffer to silence,
* and is calculated by SDL_OpenAudio().
* - \c desired->callback should be set to a function that will be called
* when the audio device is ready for more data. It is passed a pointer
* to the audio buffer, and the length in bytes of the audio buffer.
* This function usually runs in a separate thread, and so you should
* protect data structures that it accesses by calling SDL_LockAudio()
* and SDL_UnlockAudio() in your code. Alternately, you may pass a NULL
* pointer here, and call SDL_QueueAudio() with some frequency, to queue
* more audio samples to be played (or for capture devices, call
* SDL_DequeueAudio() with some frequency, to obtain audio samples).
* - \c desired->userdata is passed as the first parameter to your callback
* function. If you passed a NULL callback, this value is ignored.
*
* The audio device starts out playing silence when it's opened, and should
* be enabled for playing by calling \c SDL_PauseAudio(0) when you are ready
* for your audio callback function to be called. Since the audio driver
* may modify the requested size of the audio buffer, you should allocate
* any local mixing buffers after you open the audio device.
*/
extern DECLSPEC int SDLCALL SDL_OpenAudio(SDL_AudioSpec * desired,
SDL_AudioSpec * obtained);
/**
* SDL Audio Device IDs.
*
* A successful call to SDL_OpenAudio() is always device id 1, and legacy
* SDL audio APIs assume you want this device ID. SDL_OpenAudioDevice() calls
* always returns devices >= 2 on success. The legacy calls are good both
* for backwards compatibility and when you don't care about multiple,
* specific, or capture devices.
*/
typedef Uint32 SDL_AudioDeviceID;
/**
* Get the number of available devices exposed by the current driver.
* Only valid after a successfully initializing the audio subsystem.
* Returns -1 if an explicit list of devices can't be determined; this is
* not an error. For example, if SDL is set up to talk to a remote audio
* server, it can't list every one available on the Internet, but it will
* still allow a specific host to be specified to SDL_OpenAudioDevice().
*
* In many common cases, when this function returns a value <= 0, it can still
* successfully open the default device (NULL for first argument of
* SDL_OpenAudioDevice()).
*/
extern DECLSPEC int SDLCALL SDL_GetNumAudioDevices(int iscapture);
/**
* Get the human-readable name of a specific audio device.
* Must be a value between 0 and (number of audio devices-1).
* Only valid after a successfully initializing the audio subsystem.
* The values returned by this function reflect the latest call to
* SDL_GetNumAudioDevices(); recall that function to redetect available
* hardware.
*
* The string returned by this function is UTF-8 encoded, read-only, and
* managed internally. You are not to free it. If you need to keep the
* string for any length of time, you should make your own copy of it, as it
* will be invalid next time any of several other SDL functions is called.
*/
extern DECLSPEC const char *SDLCALL SDL_GetAudioDeviceName(int index,
int iscapture);
/**
* Open a specific audio device. Passing in a device name of NULL requests
* the most reasonable default (and is equivalent to calling SDL_OpenAudio()).
*
* The device name is a UTF-8 string reported by SDL_GetAudioDeviceName(), but
* some drivers allow arbitrary and driver-specific strings, such as a
* hostname/IP address for a remote audio server, or a filename in the
* diskaudio driver.
*
* \return 0 on error, a valid device ID that is >= 2 on success.
*
* SDL_OpenAudio(), unlike this function, always acts on device ID 1.
*/
extern DECLSPEC SDL_AudioDeviceID SDLCALL SDL_OpenAudioDevice(const char
*device,
int iscapture,
const
SDL_AudioSpec *
desired,
SDL_AudioSpec *
obtained,
int
allowed_changes);
/**
* \name Audio state
*
* Get the current audio state.
*/
/* @{ */
typedef enum
{
SDL_AUDIO_STOPPED = 0,
SDL_AUDIO_PLAYING,
SDL_AUDIO_PAUSED
} SDL_AudioStatus;
extern DECLSPEC SDL_AudioStatus SDLCALL SDL_GetAudioStatus(void);
extern DECLSPEC SDL_AudioStatus SDLCALL
SDL_GetAudioDeviceStatus(SDL_AudioDeviceID dev);
/* @} *//* Audio State */
/**
* \name Pause audio functions
*
* These functions pause and unpause the audio callback processing.
* They should be called with a parameter of 0 after opening the audio
* device to start playing sound. This is so you can safely initialize
* data for your callback function after opening the audio device.
* Silence will be written to the audio device during the pause.
*/
/* @{ */
extern DECLSPEC void SDLCALL SDL_PauseAudio(int pause_on);
extern DECLSPEC void SDLCALL SDL_PauseAudioDevice(SDL_AudioDeviceID dev,
int pause_on);
/* @} *//* Pause audio functions */
/**
* This function loads a WAVE from the data source, automatically freeing
* that source if \c freesrc is non-zero. For example, to load a WAVE file,
* you could do:
* \code
* SDL_LoadWAV_RW(SDL_RWFromFile("sample.wav", "rb"), 1, ...);
* \endcode
*
* If this function succeeds, it returns the given SDL_AudioSpec,
* filled with the audio data format of the wave data, and sets
* \c *audio_buf to a malloc()'d buffer containing the audio data,
* and sets \c *audio_len to the length of that audio buffer, in bytes.
* You need to free the audio buffer with SDL_FreeWAV() when you are
* done with it.
*
* This function returns NULL and sets the SDL error message if the
* wave file cannot be opened, uses an unknown data format, or is
* corrupt. Currently raw and MS-ADPCM WAVE files are supported.
*/
extern DECLSPEC SDL_AudioSpec *SDLCALL SDL_LoadWAV_RW(SDL_RWops * src,
int freesrc,
SDL_AudioSpec * spec,
Uint8 ** audio_buf,
Uint32 * audio_len);
/**
* Loads a WAV from a file.
* Compatibility convenience function.
*/
#define SDL_LoadWAV(file, spec, audio_buf, audio_len) \
SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"),1, spec,audio_buf,audio_len)
/**
* This function frees data previously allocated with SDL_LoadWAV_RW()
*/
extern DECLSPEC void SDLCALL SDL_FreeWAV(Uint8 * audio_buf);
/**
* This function takes a source format and rate and a destination format
* and rate, and initializes the \c cvt structure with information needed
* by SDL_ConvertAudio() to convert a buffer of audio data from one format
* to the other. An unsupported format causes an error and -1 will be returned.
*
* \return 0 if no conversion is needed, 1 if the audio filter is set up,
* or -1 on error.
*/
extern DECLSPEC int SDLCALL SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
SDL_AudioFormat src_format,
Uint8 src_channels,
int src_rate,
SDL_AudioFormat dst_format,
Uint8 dst_channels,
int dst_rate);
/**
* Once you have initialized the \c cvt structure using SDL_BuildAudioCVT(),
* created an audio buffer \c cvt->buf, and filled it with \c cvt->len bytes of
* audio data in the source format, this function will convert it in-place
* to the desired format.
*
* The data conversion may expand the size of the audio data, so the buffer
* \c cvt->buf should be allocated after the \c cvt structure is initialized by
* SDL_BuildAudioCVT(), and should be \c cvt->len*cvt->len_mult bytes long.
*
* \return 0 on success or -1 if \c cvt->buf is NULL.
*/
extern DECLSPEC int SDLCALL SDL_ConvertAudio(SDL_AudioCVT * cvt);
/* SDL_AudioStream is a new audio conversion interface.
The benefits vs SDL_AudioCVT:
- it can handle resampling data in chunks without generating
artifacts, when it doesn't have the complete buffer available.
- it can handle incoming data in any variable size.
- You push data as you have it, and pull it when you need it
*/
/* this is opaque to the outside world. */
struct _SDL_AudioStream;
typedef struct _SDL_AudioStream SDL_AudioStream;
/**
* Create a new audio stream
*
* \param src_format The format of the source audio
* \param src_channels The number of channels of the source audio
* \param src_rate The sampling rate of the source audio
* \param dst_format The format of the desired audio output
* \param dst_channels The number of channels of the desired audio output
* \param dst_rate The sampling rate of the desired audio output
* \return 0 on success, or -1 on error.
*
* \sa SDL_AudioStreamPut
* \sa SDL_AudioStreamGet
* \sa SDL_AudioStreamAvailable
* \sa SDL_AudioStreamFlush
* \sa SDL_AudioStreamClear
* \sa SDL_FreeAudioStream
*/
extern DECLSPEC SDL_AudioStream * SDLCALL SDL_NewAudioStream(const SDL_AudioFormat src_format,
const Uint8 src_channels,
const int src_rate,
const SDL_AudioFormat dst_format,
const Uint8 dst_channels,
const int dst_rate);
/**
* Add data to be converted/resampled to the stream
*
* \param stream The stream the audio data is being added to
* \param buf A pointer to the audio data to add
* \param len The number of bytes to write to the stream
* \return 0 on success, or -1 on error.
*
* \sa SDL_NewAudioStream
* \sa SDL_AudioStreamGet
* \sa SDL_AudioStreamAvailable
* \sa SDL_AudioStreamFlush
* \sa SDL_AudioStreamClear
* \sa SDL_FreeAudioStream
*/
extern DECLSPEC int SDLCALL SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, int len);
/**
* Get converted/resampled data from the stream
*
* \param stream The stream the audio is being requested from
* \param buf A buffer to fill with audio data
* \param len The maximum number of bytes to fill
* \return The number of bytes read from the stream, or -1 on error
*
* \sa SDL_NewAudioStream
* \sa SDL_AudioStreamPut
* \sa SDL_AudioStreamAvailable
* \sa SDL_AudioStreamFlush
* \sa SDL_AudioStreamClear
* \sa SDL_FreeAudioStream
*/
extern DECLSPEC int SDLCALL SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, int len);
/**
* Get the number of converted/resampled bytes available. The stream may be
* buffering data behind the scenes until it has enough to resample
* correctly, so this number might be lower than what you expect, or even
* be zero. Add more data or flush the stream if you need the data now.
*
* \sa SDL_NewAudioStream
* \sa SDL_AudioStreamPut
* \sa SDL_AudioStreamGet
* \sa SDL_AudioStreamFlush
* \sa SDL_AudioStreamClear
* \sa SDL_FreeAudioStream
*/
extern DECLSPEC int SDLCALL SDL_AudioStreamAvailable(SDL_AudioStream *stream);
/**
* Tell the stream that you're done sending data, and anything being buffered
* should be converted/resampled and made available immediately.
*
* It is legal to add more data to a stream after flushing, but there will
* be audio gaps in the output. Generally this is intended to signal the
* end of input, so the complete output becomes available.
*
* \sa SDL_NewAudioStream
* \sa SDL_AudioStreamPut
* \sa SDL_AudioStreamGet
* \sa SDL_AudioStreamAvailable
* \sa SDL_AudioStreamClear
* \sa SDL_FreeAudioStream
*/
extern DECLSPEC int SDLCALL SDL_AudioStreamFlush(SDL_AudioStream *stream);
/**
* Clear any pending data in the stream without converting it
*
* \sa SDL_NewAudioStream
* \sa SDL_AudioStreamPut
* \sa SDL_AudioStreamGet
* \sa SDL_AudioStreamAvailable
* \sa SDL_AudioStreamFlush
* \sa SDL_FreeAudioStream
*/
extern DECLSPEC void SDLCALL SDL_AudioStreamClear(SDL_AudioStream *stream);
/**
* Free an audio stream
*
* \sa SDL_NewAudioStream
* \sa SDL_AudioStreamPut
* \sa SDL_AudioStreamGet
* \sa SDL_AudioStreamAvailable
* \sa SDL_AudioStreamFlush
* \sa SDL_AudioStreamClear
*/
extern DECLSPEC void SDLCALL SDL_FreeAudioStream(SDL_AudioStream *stream);
#define SDL_MIX_MAXVOLUME 128
/**
* This takes two audio buffers of the playing audio format and mixes
* them, performing addition, volume adjustment, and overflow clipping.
* The volume ranges from 0 - 128, and should be set to ::SDL_MIX_MAXVOLUME
* for full audio volume. Note this does not change hardware volume.
* This is provided for convenience -- you can mix your own audio data.
*/
extern DECLSPEC void SDLCALL SDL_MixAudio(Uint8 * dst, const Uint8 * src,
Uint32 len, int volume);
/**
* This works like SDL_MixAudio(), but you specify the audio format instead of
* using the format of audio device 1. Thus it can be used when no audio
* device is open at all.
*/
extern DECLSPEC void SDLCALL SDL_MixAudioFormat(Uint8 * dst,
const Uint8 * src,
SDL_AudioFormat format,
Uint32 len, int volume);
/**
* Queue more audio on non-callback devices.
*
* (If you are looking to retrieve queued audio from a non-callback capture
* device, you want SDL_DequeueAudio() instead. This will return -1 to
* signify an error if you use it with capture devices.)
*
* SDL offers two ways to feed audio to the device: you can either supply a
* callback that SDL triggers with some frequency to obtain more audio
* (pull method), or you can supply no callback, and then SDL will expect
* you to supply data at regular intervals (push method) with this function.
*
* There are no limits on the amount of data you can queue, short of
* exhaustion of address space. Queued data will drain to the device as
* necessary without further intervention from you. If the device needs
* audio but there is not enough queued, it will play silence to make up
* the difference. This means you will have skips in your audio playback
* if you aren't routinely queueing sufficient data.
*
* This function copies the supplied data, so you are safe to free it when
* the function returns. This function is thread-safe, but queueing to the
* same device from two threads at once does not promise which buffer will
* be queued first.
*
* You may not queue audio on a device that is using an application-supplied
* callback; doing so returns an error. You have to use the audio callback
* or queue audio with this function, but not both.
*
* You should not call SDL_LockAudio() on the device before queueing; SDL
* handles locking internally for this function.
*
* \param dev The device ID to which we will queue audio.
* \param data The data to queue to the device for later playback.
* \param len The number of bytes (not samples!) to which (data) points.
* \return 0 on success, or -1 on error.
*
* \sa SDL_GetQueuedAudioSize
* \sa SDL_ClearQueuedAudio
*/
extern DECLSPEC int SDLCALL SDL_QueueAudio(SDL_AudioDeviceID dev, const void *data, Uint32 len);
/**
* Dequeue more audio on non-callback devices.
*
* (If you are looking to queue audio for output on a non-callback playback
* device, you want SDL_QueueAudio() instead. This will always return 0
* if you use it with playback devices.)
*
* SDL offers two ways to retrieve audio from a capture device: you can
* either supply a callback that SDL triggers with some frequency as the
* device records more audio data, (push method), or you can supply no
* callback, and then SDL will expect you to retrieve data at regular
* intervals (pull method) with this function.
*
* There are no limits on the amount of data you can queue, short of
* exhaustion of address space. Data from the device will keep queuing as
* necessary without further intervention from you. This means you will
* eventually run out of memory if you aren't routinely dequeueing data.
*
* Capture devices will not queue data when paused; if you are expecting
* to not need captured audio for some length of time, use
* SDL_PauseAudioDevice() to stop the capture device from queueing more
* data. This can be useful during, say, level loading times. When
* unpaused, capture devices will start queueing data from that point,
* having flushed any capturable data available while paused.
*
* This function is thread-safe, but dequeueing from the same device from
* two threads at once does not promise which thread will dequeued data
* first.
*
* You may not dequeue audio from a device that is using an
* application-supplied callback; doing so returns an error. You have to use
* the audio callback, or dequeue audio with this function, but not both.
*
* You should not call SDL_LockAudio() on the device before queueing; SDL
* handles locking internally for this function.
*
* \param dev The device ID from which we will dequeue audio.
* \param data A pointer into where audio data should be copied.
* \param len The number of bytes (not samples!) to which (data) points.
* \return number of bytes dequeued, which could be less than requested.
*
* \sa SDL_GetQueuedAudioSize
* \sa SDL_ClearQueuedAudio
*/
extern DECLSPEC Uint32 SDLCALL SDL_DequeueAudio(SDL_AudioDeviceID dev, void *data, Uint32 len);
/**
* Get the number of bytes of still-queued audio.
*
* For playback device:
*
* This is the number of bytes that have been queued for playback with
* SDL_QueueAudio(), but have not yet been sent to the hardware. This
* number may shrink at any time, so this only informs of pending data.
*
* Once we've sent it to the hardware, this function can not decide the
* exact byte boundary of what has been played. It's possible that we just
* gave the hardware several kilobytes right before you called this
* function, but it hasn't played any of it yet, or maybe half of it, etc.
*
* For capture devices:
*
* This is the number of bytes that have been captured by the device and
* are waiting for you to dequeue. This number may grow at any time, so
* this only informs of the lower-bound of available data.
*
* You may not queue audio on a device that is using an application-supplied
* callback; calling this function on such a device always returns 0.
* You have to queue audio with SDL_QueueAudio()/SDL_DequeueAudio(), or use
* the audio callback, but not both.
*
* You should not call SDL_LockAudio() on the device before querying; SDL
* handles locking internally for this function.
*
* \param dev The device ID of which we will query queued audio size.
* \return Number of bytes (not samples!) of queued audio.
*
* \sa SDL_QueueAudio
* \sa SDL_ClearQueuedAudio
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetQueuedAudioSize(SDL_AudioDeviceID dev);
/**
* Drop any queued audio data. For playback devices, this is any queued data
* still waiting to be submitted to the hardware. For capture devices, this
* is any data that was queued by the device that hasn't yet been dequeued by
* the application.
*
* Immediately after this call, SDL_GetQueuedAudioSize() will return 0. For
* playback devices, the hardware will start playing silence if more audio
* isn't queued. Unpaused capture devices will start filling the queue again
* as soon as they have more data available (which, depending on the state
* of the hardware and the thread, could be before this function call
* returns!).
*
* This will not prevent playback of queued audio that's already been sent
* to the hardware, as we can not undo that, so expect there to be some
* fraction of a second of audio that might still be heard. This can be
* useful if you want to, say, drop any pending music during a level change
* in your game.
*
* You may not queue audio on a device that is using an application-supplied
* callback; calling this function on such a device is always a no-op.
* You have to queue audio with SDL_QueueAudio()/SDL_DequeueAudio(), or use
* the audio callback, but not both.
*
* You should not call SDL_LockAudio() on the device before clearing the
* queue; SDL handles locking internally for this function.
*
* This function always succeeds and thus returns void.
*
* \param dev The device ID of which to clear the audio queue.
*
* \sa SDL_QueueAudio
* \sa SDL_GetQueuedAudioSize
*/
extern DECLSPEC void SDLCALL SDL_ClearQueuedAudio(SDL_AudioDeviceID dev);
/**
* \name Audio lock functions
*
* The lock manipulated by these functions protects the callback function.
* During a SDL_LockAudio()/SDL_UnlockAudio() pair, you can be guaranteed that
* the callback function is not running. Do not call these from the callback
* function or you will cause deadlock.
*/
/* @{ */
extern DECLSPEC void SDLCALL SDL_LockAudio(void);
extern DECLSPEC void SDLCALL SDL_LockAudioDevice(SDL_AudioDeviceID dev);
extern DECLSPEC void SDLCALL SDL_UnlockAudio(void);
extern DECLSPEC void SDLCALL SDL_UnlockAudioDevice(SDL_AudioDeviceID dev);
/* @} *//* Audio lock functions */
/**
* This function shuts down audio processing and closes the audio device.
*/
extern DECLSPEC void SDLCALL SDL_CloseAudio(void);
extern DECLSPEC void SDLCALL SDL_CloseAudioDevice(SDL_AudioDeviceID dev);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_audio_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 33,865 | C | 40 | 140 | 0.669423 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_messagebox.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_messagebox_h_
#define SDL_messagebox_h_
#include "SDL_stdinc.h"
#include "SDL_video.h" /* For SDL_Window */
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief SDL_MessageBox flags. If supported will display warning icon, etc.
*/
typedef enum
{
SDL_MESSAGEBOX_ERROR = 0x00000010, /**< error dialog */
SDL_MESSAGEBOX_WARNING = 0x00000020, /**< warning dialog */
SDL_MESSAGEBOX_INFORMATION = 0x00000040 /**< informational dialog */
} SDL_MessageBoxFlags;
/**
* \brief Flags for SDL_MessageBoxButtonData.
*/
typedef enum
{
SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT = 0x00000001, /**< Marks the default button when return is hit */
SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT = 0x00000002 /**< Marks the default button when escape is hit */
} SDL_MessageBoxButtonFlags;
/**
* \brief Individual button data.
*/
typedef struct
{
Uint32 flags; /**< ::SDL_MessageBoxButtonFlags */
int buttonid; /**< User defined button id (value returned via SDL_ShowMessageBox) */
const char * text; /**< The UTF-8 button text */
} SDL_MessageBoxButtonData;
/**
* \brief RGB value used in a message box color scheme
*/
typedef struct
{
Uint8 r, g, b;
} SDL_MessageBoxColor;
typedef enum
{
SDL_MESSAGEBOX_COLOR_BACKGROUND,
SDL_MESSAGEBOX_COLOR_TEXT,
SDL_MESSAGEBOX_COLOR_BUTTON_BORDER,
SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND,
SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED,
SDL_MESSAGEBOX_COLOR_MAX
} SDL_MessageBoxColorType;
/**
* \brief A set of colors to use for message box dialogs
*/
typedef struct
{
SDL_MessageBoxColor colors[SDL_MESSAGEBOX_COLOR_MAX];
} SDL_MessageBoxColorScheme;
/**
* \brief MessageBox structure containing title, text, window, etc.
*/
typedef struct
{
Uint32 flags; /**< ::SDL_MessageBoxFlags */
SDL_Window *window; /**< Parent window, can be NULL */
const char *title; /**< UTF-8 title */
const char *message; /**< UTF-8 message text */
int numbuttons;
const SDL_MessageBoxButtonData *buttons;
const SDL_MessageBoxColorScheme *colorScheme; /**< ::SDL_MessageBoxColorScheme, can be NULL to use system settings */
} SDL_MessageBoxData;
/**
* \brief Create a modal message box.
*
* \param messageboxdata The SDL_MessageBoxData structure with title, text, etc.
* \param buttonid The pointer to which user id of hit button should be copied.
*
* \return -1 on error, otherwise 0 and buttonid contains user id of button
* hit or -1 if dialog was closed.
*
* \note This function should be called on the thread that created the parent
* window, or on the main thread if the messagebox has no parent. It will
* block execution of that thread until the user clicks a button or
* closes the messagebox.
*/
extern DECLSPEC int SDLCALL SDL_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid);
/**
* \brief Create a simple modal message box
*
* \param flags ::SDL_MessageBoxFlags
* \param title UTF-8 title text
* \param message UTF-8 message text
* \param window The parent window, or NULL for no parent
*
* \return 0 on success, -1 on error
*
* \sa SDL_ShowMessageBox
*/
extern DECLSPEC int SDLCALL SDL_ShowSimpleMessageBox(Uint32 flags, const char *title, const char *message, SDL_Window *window);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_messagebox_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 4,611 | C | 30.806896 | 127 | 0.693125 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_hints.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_hints.h
*
* Official documentation for SDL configuration variables
*
* This file contains functions to set and get configuration hints,
* as well as listing each of them alphabetically.
*
* The convention for naming hints is SDL_HINT_X, where "SDL_X" is
* the environment variable that can be used to override the default.
*
* In general these hints are just that - they may or may not be
* supported or applicable on any given platform, but they provide
* a way for an application or user to give the library a hint as
* to how they would like the library to work.
*/
#ifndef SDL_hints_h_
#define SDL_hints_h_
#include "SDL_stdinc.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief A variable controlling how 3D acceleration is used to accelerate the SDL screen surface.
*
* SDL can try to accelerate the SDL screen surface by using streaming
* textures with a 3D rendering engine. This variable controls whether and
* how this is done.
*
* This variable can be set to the following values:
* "0" - Disable 3D acceleration
* "1" - Enable 3D acceleration, using the default renderer.
* "X" - Enable 3D acceleration, using X where X is one of the valid rendering drivers. (e.g. "direct3d", "opengl", etc.)
*
* By default SDL tries to make a best guess for each platform whether
* to use acceleration or not.
*/
#define SDL_HINT_FRAMEBUFFER_ACCELERATION "SDL_FRAMEBUFFER_ACCELERATION"
/**
* \brief A variable specifying which render driver to use.
*
* If the application doesn't pick a specific renderer to use, this variable
* specifies the name of the preferred renderer. If the preferred renderer
* can't be initialized, the normal default renderer is used.
*
* This variable is case insensitive and can be set to the following values:
* "direct3d"
* "opengl"
* "opengles2"
* "opengles"
* "metal"
* "software"
*
* The default varies by platform, but it's the first one in the list that
* is available on the current platform.
*/
#define SDL_HINT_RENDER_DRIVER "SDL_RENDER_DRIVER"
/**
* \brief A variable controlling whether the OpenGL render driver uses shaders if they are available.
*
* This variable can be set to the following values:
* "0" - Disable shaders
* "1" - Enable shaders
*
* By default shaders are used if OpenGL supports them.
*/
#define SDL_HINT_RENDER_OPENGL_SHADERS "SDL_RENDER_OPENGL_SHADERS"
/**
* \brief A variable controlling whether the Direct3D device is initialized for thread-safe operations.
*
* This variable can be set to the following values:
* "0" - Thread-safety is not enabled (faster)
* "1" - Thread-safety is enabled
*
* By default the Direct3D device is created with thread-safety disabled.
*/
#define SDL_HINT_RENDER_DIRECT3D_THREADSAFE "SDL_RENDER_DIRECT3D_THREADSAFE"
/**
* \brief A variable controlling whether to enable Direct3D 11+'s Debug Layer.
*
* This variable does not have any effect on the Direct3D 9 based renderer.
*
* This variable can be set to the following values:
* "0" - Disable Debug Layer use
* "1" - Enable Debug Layer use
*
* By default, SDL does not use Direct3D Debug Layer.
*/
#define SDL_HINT_RENDER_DIRECT3D11_DEBUG "SDL_RENDER_DIRECT3D11_DEBUG"
/**
* \brief A variable controlling the scaling policy for SDL_RenderSetLogicalSize.
*
* This variable can be set to the following values:
* "0" or "letterbox" - Uses letterbox/sidebars to fit the entire rendering on screen
* "1" or "overscan" - Will zoom the rendering so it fills the entire screen, allowing edges to be drawn offscreen
*
* By default letterbox is used
*/
#define SDL_HINT_RENDER_LOGICAL_SIZE_MODE "SDL_RENDER_LOGICAL_SIZE_MODE"
/**
* \brief A variable controlling the scaling quality
*
* This variable can be set to the following values:
* "0" or "nearest" - Nearest pixel sampling
* "1" or "linear" - Linear filtering (supported by OpenGL and Direct3D)
* "2" or "best" - Currently this is the same as "linear"
*
* By default nearest pixel sampling is used
*/
#define SDL_HINT_RENDER_SCALE_QUALITY "SDL_RENDER_SCALE_QUALITY"
/**
* \brief A variable controlling whether updates to the SDL screen surface should be synchronized with the vertical refresh, to avoid tearing.
*
* This variable can be set to the following values:
* "0" - Disable vsync
* "1" - Enable vsync
*
* By default SDL does not sync screen surface updates with vertical refresh.
*/
#define SDL_HINT_RENDER_VSYNC "SDL_RENDER_VSYNC"
/**
* \brief A variable controlling whether the screensaver is enabled.
*
* This variable can be set to the following values:
* "0" - Disable screensaver
* "1" - Enable screensaver
*
* By default SDL will disable the screensaver.
*/
#define SDL_HINT_VIDEO_ALLOW_SCREENSAVER "SDL_VIDEO_ALLOW_SCREENSAVER"
/**
* \brief A variable controlling whether the X11 VidMode extension should be used.
*
* This variable can be set to the following values:
* "0" - Disable XVidMode
* "1" - Enable XVidMode
*
* By default SDL will use XVidMode if it is available.
*/
#define SDL_HINT_VIDEO_X11_XVIDMODE "SDL_VIDEO_X11_XVIDMODE"
/**
* \brief A variable controlling whether the X11 Xinerama extension should be used.
*
* This variable can be set to the following values:
* "0" - Disable Xinerama
* "1" - Enable Xinerama
*
* By default SDL will use Xinerama if it is available.
*/
#define SDL_HINT_VIDEO_X11_XINERAMA "SDL_VIDEO_X11_XINERAMA"
/**
* \brief A variable controlling whether the X11 XRandR extension should be used.
*
* This variable can be set to the following values:
* "0" - Disable XRandR
* "1" - Enable XRandR
*
* By default SDL will not use XRandR because of window manager issues.
*/
#define SDL_HINT_VIDEO_X11_XRANDR "SDL_VIDEO_X11_XRANDR"
/**
* \brief A variable controlling whether the X11 _NET_WM_PING protocol should be supported.
*
* This variable can be set to the following values:
* "0" - Disable _NET_WM_PING
* "1" - Enable _NET_WM_PING
*
* By default SDL will use _NET_WM_PING, but for applications that know they
* will not always be able to respond to ping requests in a timely manner they can
* turn it off to avoid the window manager thinking the app is hung.
* The hint is checked in CreateWindow.
*/
#define SDL_HINT_VIDEO_X11_NET_WM_PING "SDL_VIDEO_X11_NET_WM_PING"
/**
* \brief A variable controlling whether the X11 _NET_WM_BYPASS_COMPOSITOR hint should be used.
*
* This variable can be set to the following values:
* "0" - Disable _NET_WM_BYPASS_COMPOSITOR
* "1" - Enable _NET_WM_BYPASS_COMPOSITOR
*
* By default SDL will use _NET_WM_BYPASS_COMPOSITOR
*
*/
#define SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR "SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR"
/**
* \brief A variable controlling whether the window frame and title bar are interactive when the cursor is hidden
*
* This variable can be set to the following values:
* "0" - The window frame is not interactive when the cursor is hidden (no move, resize, etc)
* "1" - The window frame is interactive when the cursor is hidden
*
* By default SDL will allow interaction with the window frame when the cursor is hidden
*/
#define SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN "SDL_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN"
/**
* \brief A variable to specify custom icon resource id from RC file on Windows platform
*/
#define SDL_HINT_WINDOWS_INTRESOURCE_ICON "SDL_WINDOWS_INTRESOURCE_ICON"
#define SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL "SDL_WINDOWS_INTRESOURCE_ICON_SMALL"
/**
* \brief A variable controlling whether the windows message loop is processed by SDL
*
* This variable can be set to the following values:
* "0" - The window message loop is not run
* "1" - The window message loop is processed in SDL_PumpEvents()
*
* By default SDL will process the windows message loop
*/
#define SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP "SDL_WINDOWS_ENABLE_MESSAGELOOP"
/**
* \brief A variable controlling whether grabbing input grabs the keyboard
*
* This variable can be set to the following values:
* "0" - Grab will affect only the mouse
* "1" - Grab will affect mouse and keyboard
*
* By default SDL will not grab the keyboard so system shortcuts still work.
*/
#define SDL_HINT_GRAB_KEYBOARD "SDL_GRAB_KEYBOARD"
/**
* \brief A variable setting the speed scale for mouse motion, in floating point, when the mouse is not in relative mode
*/
#define SDL_HINT_MOUSE_NORMAL_SPEED_SCALE "SDL_MOUSE_NORMAL_SPEED_SCALE"
/**
* \brief A variable setting the scale for mouse motion, in floating point, when the mouse is in relative mode
*/
#define SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE "SDL_MOUSE_RELATIVE_SPEED_SCALE"
/**
* \brief A variable controlling whether relative mouse mode is implemented using mouse warping
*
* This variable can be set to the following values:
* "0" - Relative mouse mode uses raw input
* "1" - Relative mouse mode uses mouse warping
*
* By default SDL will use raw input for relative mouse mode
*/
#define SDL_HINT_MOUSE_RELATIVE_MODE_WARP "SDL_MOUSE_RELATIVE_MODE_WARP"
/**
* \brief Allow mouse click events when clicking to focus an SDL window
*
* This variable can be set to the following values:
* "0" - Ignore mouse clicks that activate a window
* "1" - Generate events for mouse clicks that activate a window
*
* By default SDL will ignore mouse clicks that activate a window
*/
#define SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH "SDL_MOUSE_FOCUS_CLICKTHROUGH"
/**
* \brief A variable controlling whether touch events should generate synthetic mouse events
*
* This variable can be set to the following values:
* "0" - Touch events will not generate mouse events
* "1" - Touch events will generate mouse events
*
* By default SDL will generate mouse events for touch events
*/
#define SDL_HINT_TOUCH_MOUSE_EVENTS "SDL_TOUCH_MOUSE_EVENTS"
/**
* \brief Minimize your SDL_Window if it loses key focus when in fullscreen mode. Defaults to true.
*
*/
#define SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS "SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS"
/**
* \brief A variable controlling whether the idle timer is disabled on iOS.
*
* When an iOS app does not receive touches for some time, the screen is
* dimmed automatically. For games where the accelerometer is the only input
* this is problematic. This functionality can be disabled by setting this
* hint.
*
* As of SDL 2.0.4, SDL_EnableScreenSaver() and SDL_DisableScreenSaver()
* accomplish the same thing on iOS. They should be preferred over this hint.
*
* This variable can be set to the following values:
* "0" - Enable idle timer
* "1" - Disable idle timer
*/
#define SDL_HINT_IDLE_TIMER_DISABLED "SDL_IOS_IDLE_TIMER_DISABLED"
/**
* \brief A variable controlling which orientations are allowed on iOS.
*
* In some circumstances it is necessary to be able to explicitly control
* which UI orientations are allowed.
*
* This variable is a space delimited list of the following values:
* "LandscapeLeft", "LandscapeRight", "Portrait" "PortraitUpsideDown"
*/
#define SDL_HINT_ORIENTATIONS "SDL_IOS_ORIENTATIONS"
/**
* \brief A variable controlling whether controllers used with the Apple TV
* generate UI events.
*
* When UI events are generated by controller input, the app will be
* backgrounded when the Apple TV remote's menu button is pressed, and when the
* pause or B buttons on gamepads are pressed.
*
* More information about properly making use of controllers for the Apple TV
* can be found here:
* https://developer.apple.com/tvos/human-interface-guidelines/remote-and-controllers/
*
* This variable can be set to the following values:
* "0" - Controller input does not generate UI events (the default).
* "1" - Controller input generates UI events.
*/
#define SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS "SDL_APPLE_TV_CONTROLLER_UI_EVENTS"
/**
* \brief A variable controlling whether the Apple TV remote's joystick axes
* will automatically match the rotation of the remote.
*
* This variable can be set to the following values:
* "0" - Remote orientation does not affect joystick axes (the default).
* "1" - Joystick axes are based on the orientation of the remote.
*/
#define SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION "SDL_APPLE_TV_REMOTE_ALLOW_ROTATION"
/**
* \brief A variable controlling whether the home indicator bar on iPhone X
* should be hidden.
*
* This variable can be set to the following values:
* "0" - The indicator bar is not hidden (default for windowed applications)
* "1" - The indicator bar is hidden and is shown when the screen is touched (useful for movie playback applications)
* "2" - The indicator bar is dim and the first swipe makes it visible and the second swipe performs the "home" action (default for fullscreen applications)
*/
#define SDL_HINT_IOS_HIDE_HOME_INDICATOR "SDL_IOS_HIDE_HOME_INDICATOR"
/**
* \brief A variable controlling whether the Android / iOS built-in
* accelerometer should be listed as a joystick device.
*
* This variable can be set to the following values:
* "0" - The accelerometer is not listed as a joystick
* "1" - The accelerometer is available as a 3 axis joystick (the default).
*/
#define SDL_HINT_ACCELEROMETER_AS_JOYSTICK "SDL_ACCELEROMETER_AS_JOYSTICK"
/**
* \brief A variable controlling whether the Android / tvOS remotes
* should be listed as joystick devices, instead of sending keyboard events.
*
* This variable can be set to the following values:
* "0" - Remotes send enter/escape/arrow key events
* "1" - Remotes are available as 2 axis, 2 button joysticks (the default).
*/
#define SDL_HINT_TV_REMOTE_AS_JOYSTICK "SDL_TV_REMOTE_AS_JOYSTICK"
/**
* \brief A variable that lets you disable the detection and use of Xinput gamepad devices
*
* The variable can be set to the following values:
* "0" - Disable XInput detection (only uses direct input)
* "1" - Enable XInput detection (the default)
*/
#define SDL_HINT_XINPUT_ENABLED "SDL_XINPUT_ENABLED"
/**
* \brief A variable that causes SDL to use the old axis and button mapping for XInput devices.
*
* This hint is for backwards compatibility only and will be removed in SDL 2.1
*
* The default value is "0". This hint must be set before SDL_Init()
*/
#define SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING "SDL_XINPUT_USE_OLD_JOYSTICK_MAPPING"
/**
* \brief A variable that lets you manually hint extra gamecontroller db entries.
*
* The variable should be newline delimited rows of gamecontroller config data, see SDL_gamecontroller.h
*
* This hint must be set before calling SDL_Init(SDL_INIT_GAMECONTROLLER)
* You can update mappings after the system is initialized with SDL_GameControllerMappingForGUID() and SDL_GameControllerAddMapping()
*/
#define SDL_HINT_GAMECONTROLLERCONFIG "SDL_GAMECONTROLLERCONFIG"
/**
* \brief A variable containing a list of devices to skip when scanning for game controllers.
*
* The format of the string is a comma separated list of USB VID/PID pairs
* in hexadecimal form, e.g.
*
* 0xAAAA/0xBBBB,0xCCCC/0xDDDD
*
* The variable can also take the form of @file, in which case the named
* file will be loaded and interpreted as the value of the variable.
*/
#define SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES "SDL_GAMECONTROLLER_IGNORE_DEVICES"
/**
* \brief If set, all devices will be skipped when scanning for game controllers except for the ones listed in this variable.
*
* The format of the string is a comma separated list of USB VID/PID pairs
* in hexadecimal form, e.g.
*
* 0xAAAA/0xBBBB,0xCCCC/0xDDDD
*
* The variable can also take the form of @file, in which case the named
* file will be loaded and interpreted as the value of the variable.
*/
#define SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT "SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT"
/**
* \brief A variable that lets you enable joystick (and gamecontroller) events even when your app is in the background.
*
* The variable can be set to the following values:
* "0" - Disable joystick & gamecontroller input events when the
* application is in the background.
* "1" - Enable joystick & gamecontroller input events when the
* application is in the background.
*
* The default value is "0". This hint may be set at any time.
*/
#define SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS "SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS"
/**
* \brief If set to "0" then never set the top most bit on a SDL Window, even if the video mode expects it.
* This is a debugging aid for developers and not expected to be used by end users. The default is "1"
*
* This variable can be set to the following values:
* "0" - don't allow topmost
* "1" - allow topmost
*/
#define SDL_HINT_ALLOW_TOPMOST "SDL_ALLOW_TOPMOST"
/**
* \brief A variable that controls the timer resolution, in milliseconds.
*
* The higher resolution the timer, the more frequently the CPU services
* timer interrupts, and the more precise delays are, but this takes up
* power and CPU time. This hint is only used on Windows 7 and earlier.
*
* See this blog post for more information:
* http://randomascii.wordpress.com/2013/07/08/windows-timer-resolution-megawatts-wasted/
*
* If this variable is set to "0", the system timer resolution is not set.
*
* The default value is "1". This hint may be set at any time.
*/
#define SDL_HINT_TIMER_RESOLUTION "SDL_TIMER_RESOLUTION"
/**
* \brief A variable describing the content orientation on QtWayland-based platforms.
*
* On QtWayland platforms, windows are rotated client-side to allow for custom
* transitions. In order to correctly position overlays (e.g. volume bar) and
* gestures (e.g. events view, close/minimize gestures), the system needs to
* know in which orientation the application is currently drawing its contents.
*
* This does not cause the window to be rotated or resized, the application
* needs to take care of drawing the content in the right orientation (the
* framebuffer is always in portrait mode).
*
* This variable can be one of the following values:
* "primary" (default), "portrait", "landscape", "inverted-portrait", "inverted-landscape"
*/
#define SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION "SDL_QTWAYLAND_CONTENT_ORIENTATION"
/**
* \brief Flags to set on QtWayland windows to integrate with the native window manager.
*
* On QtWayland platforms, this hint controls the flags to set on the windows.
* For example, on Sailfish OS "OverridesSystemGestures" disables swipe gestures.
*
* This variable is a space-separated list of the following values (empty = no flags):
* "OverridesSystemGestures", "StaysOnTop", "BypassWindowManager"
*/
#define SDL_HINT_QTWAYLAND_WINDOW_FLAGS "SDL_QTWAYLAND_WINDOW_FLAGS"
/**
* \brief A string specifying SDL's threads stack size in bytes or "0" for the backend's default size
*
* Use this hint in case you need to set SDL's threads stack size to other than the default.
* This is specially useful if you build SDL against a non glibc libc library (such as musl) which
* provides a relatively small default thread stack size (a few kilobytes versus the default 8MB glibc uses).
* Support for this hint is currently available only in the pthread, Windows, and PSP backend.
*/
#define SDL_HINT_THREAD_STACK_SIZE "SDL_THREAD_STACK_SIZE"
/**
* \brief If set to 1, then do not allow high-DPI windows. ("Retina" on Mac and iOS)
*/
#define SDL_HINT_VIDEO_HIGHDPI_DISABLED "SDL_VIDEO_HIGHDPI_DISABLED"
/**
* \brief A variable that determines whether ctrl+click should generate a right-click event on Mac
*
* If present, holding ctrl while left clicking will generate a right click
* event when on Mac.
*/
#define SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK "SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK"
/**
* \brief A variable specifying which shader compiler to preload when using the Chrome ANGLE binaries
*
* SDL has EGL and OpenGL ES2 support on Windows via the ANGLE project. It
* can use two different sets of binaries, those compiled by the user from source
* or those provided by the Chrome browser. In the later case, these binaries require
* that SDL loads a DLL providing the shader compiler.
*
* This variable can be set to the following values:
* "d3dcompiler_46.dll" - default, best for Vista or later.
* "d3dcompiler_43.dll" - for XP support.
* "none" - do not load any library, useful if you compiled ANGLE from source and included the compiler in your binaries.
*
*/
#define SDL_HINT_VIDEO_WIN_D3DCOMPILER "SDL_VIDEO_WIN_D3DCOMPILER"
/**
* \brief A variable that is the address of another SDL_Window* (as a hex string formatted with "%p").
*
* If this hint is set before SDL_CreateWindowFrom() and the SDL_Window* it is set to has
* SDL_WINDOW_OPENGL set (and running on WGL only, currently), then two things will occur on the newly
* created SDL_Window:
*
* 1. Its pixel format will be set to the same pixel format as this SDL_Window. This is
* needed for example when sharing an OpenGL context across multiple windows.
*
* 2. The flag SDL_WINDOW_OPENGL will be set on the new window so it can be used for
* OpenGL rendering.
*
* This variable can be set to the following values:
* The address (as a string "%p") of the SDL_Window* that new windows created with SDL_CreateWindowFrom() should
* share a pixel format with.
*/
#define SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT "SDL_VIDEO_WINDOW_SHARE_PIXEL_FORMAT"
/**
* \brief A URL to a WinRT app's privacy policy
*
* All network-enabled WinRT apps must make a privacy policy available to its
* users. On Windows 8, 8.1, and RT, Microsoft mandates that this policy be
* be available in the Windows Settings charm, as accessed from within the app.
* SDL provides code to add a URL-based link there, which can point to the app's
* privacy policy.
*
* To setup a URL to an app's privacy policy, set SDL_HINT_WINRT_PRIVACY_POLICY_URL
* before calling any SDL_Init() functions. The contents of the hint should
* be a valid URL. For example, "http://www.example.com".
*
* The default value is "", which will prevent SDL from adding a privacy policy
* link to the Settings charm. This hint should only be set during app init.
*
* The label text of an app's "Privacy Policy" link may be customized via another
* hint, SDL_HINT_WINRT_PRIVACY_POLICY_LABEL.
*
* Please note that on Windows Phone, Microsoft does not provide standard UI
* for displaying a privacy policy link, and as such, SDL_HINT_WINRT_PRIVACY_POLICY_URL
* will not get used on that platform. Network-enabled phone apps should display
* their privacy policy through some other, in-app means.
*/
#define SDL_HINT_WINRT_PRIVACY_POLICY_URL "SDL_WINRT_PRIVACY_POLICY_URL"
/** \brief Label text for a WinRT app's privacy policy link
*
* Network-enabled WinRT apps must include a privacy policy. On Windows 8, 8.1, and RT,
* Microsoft mandates that this policy be available via the Windows Settings charm.
* SDL provides code to add a link there, with its label text being set via the
* optional hint, SDL_HINT_WINRT_PRIVACY_POLICY_LABEL.
*
* Please note that a privacy policy's contents are not set via this hint. A separate
* hint, SDL_HINT_WINRT_PRIVACY_POLICY_URL, is used to link to the actual text of the
* policy.
*
* The contents of this hint should be encoded as a UTF8 string.
*
* The default value is "Privacy Policy". This hint should only be set during app
* initialization, preferably before any calls to SDL_Init().
*
* For additional information on linking to a privacy policy, see the documentation for
* SDL_HINT_WINRT_PRIVACY_POLICY_URL.
*/
#define SDL_HINT_WINRT_PRIVACY_POLICY_LABEL "SDL_WINRT_PRIVACY_POLICY_LABEL"
/** \brief Allows back-button-press events on Windows Phone to be marked as handled
*
* Windows Phone devices typically feature a Back button. When pressed,
* the OS will emit back-button-press events, which apps are expected to
* handle in an appropriate manner. If apps do not explicitly mark these
* events as 'Handled', then the OS will invoke its default behavior for
* unhandled back-button-press events, which on Windows Phone 8 and 8.1 is to
* terminate the app (and attempt to switch to the previous app, or to the
* device's home screen).
*
* Setting the SDL_HINT_WINRT_HANDLE_BACK_BUTTON hint to "1" will cause SDL
* to mark back-button-press events as Handled, if and when one is sent to
* the app.
*
* Internally, Windows Phone sends back button events as parameters to
* special back-button-press callback functions. Apps that need to respond
* to back-button-press events are expected to register one or more
* callback functions for such, shortly after being launched (during the
* app's initialization phase). After the back button is pressed, the OS
* will invoke these callbacks. If the app's callback(s) do not explicitly
* mark the event as handled by the time they return, or if the app never
* registers one of these callback, the OS will consider the event
* un-handled, and it will apply its default back button behavior (terminate
* the app).
*
* SDL registers its own back-button-press callback with the Windows Phone
* OS. This callback will emit a pair of SDL key-press events (SDL_KEYDOWN
* and SDL_KEYUP), each with a scancode of SDL_SCANCODE_AC_BACK, after which
* it will check the contents of the hint, SDL_HINT_WINRT_HANDLE_BACK_BUTTON.
* If the hint's value is set to "1", the back button event's Handled
* property will get set to 'true'. If the hint's value is set to something
* else, or if it is unset, SDL will leave the event's Handled property
* alone. (By default, the OS sets this property to 'false', to note.)
*
* SDL apps can either set SDL_HINT_WINRT_HANDLE_BACK_BUTTON well before a
* back button is pressed, or can set it in direct-response to a back button
* being pressed.
*
* In order to get notified when a back button is pressed, SDL apps should
* register a callback function with SDL_AddEventWatch(), and have it listen
* for SDL_KEYDOWN events that have a scancode of SDL_SCANCODE_AC_BACK.
* (Alternatively, SDL_KEYUP events can be listened-for. Listening for
* either event type is suitable.) Any value of SDL_HINT_WINRT_HANDLE_BACK_BUTTON
* set by such a callback, will be applied to the OS' current
* back-button-press event.
*
* More details on back button behavior in Windows Phone apps can be found
* at the following page, on Microsoft's developer site:
* http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj247550(v=vs.105).aspx
*/
#define SDL_HINT_WINRT_HANDLE_BACK_BUTTON "SDL_WINRT_HANDLE_BACK_BUTTON"
/**
* \brief A variable that dictates policy for fullscreen Spaces on Mac OS X.
*
* This hint only applies to Mac OS X.
*
* The variable can be set to the following values:
* "0" - Disable Spaces support (FULLSCREEN_DESKTOP won't use them and
* SDL_WINDOW_RESIZABLE windows won't offer the "fullscreen"
* button on their titlebars).
* "1" - Enable Spaces support (FULLSCREEN_DESKTOP will use them and
* SDL_WINDOW_RESIZABLE windows will offer the "fullscreen"
* button on their titlebars).
*
* The default value is "1". Spaces are disabled regardless of this hint if
* the OS isn't at least Mac OS X Lion (10.7). This hint must be set before
* any windows are created.
*/
#define SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES "SDL_VIDEO_MAC_FULLSCREEN_SPACES"
/**
* \brief When set don't force the SDL app to become a foreground process
*
* This hint only applies to Mac OS X.
*
*/
#define SDL_HINT_MAC_BACKGROUND_APP "SDL_MAC_BACKGROUND_APP"
/**
* \brief Android APK expansion main file version. Should be a string number like "1", "2" etc.
*
* Must be set together with SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION.
*
* If both hints were set then SDL_RWFromFile() will look into expansion files
* after a given relative path was not found in the internal storage and assets.
*
* By default this hint is not set and the APK expansion files are not searched.
*/
#define SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION "SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION"
/**
* \brief Android APK expansion patch file version. Should be a string number like "1", "2" etc.
*
* Must be set together with SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION.
*
* If both hints were set then SDL_RWFromFile() will look into expansion files
* after a given relative path was not found in the internal storage and assets.
*
* By default this hint is not set and the APK expansion files are not searched.
*/
#define SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION "SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION"
/**
* \brief A variable to control whether certain IMEs should handle text editing internally instead of sending SDL_TEXTEDITING events.
*
* The variable can be set to the following values:
* "0" - SDL_TEXTEDITING events are sent, and it is the application's
* responsibility to render the text from these events and
* differentiate it somehow from committed text. (default)
* "1" - If supported by the IME then SDL_TEXTEDITING events are not sent,
* and text that is being composed will be rendered in its own UI.
*/
#define SDL_HINT_IME_INTERNAL_EDITING "SDL_IME_INTERNAL_EDITING"
/**
* \brief A variable to control whether mouse and touch events are to be treated together or separately
*
* The variable can be set to the following values:
* "0" - Mouse events will be handled as touch events, and touch will raise fake mouse
* events. This is the behaviour of SDL <= 2.0.3. (default)
* "1" - Mouse events will be handled separately from pure touch events.
*
* The value of this hint is used at runtime, so it can be changed at any time.
*/
#define SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH "SDL_ANDROID_SEPARATE_MOUSE_AND_TOUCH"
/**
* \brief A variable to control whether the return key on the soft keyboard
* should hide the soft keyboard on Android and iOS.
*
* The variable can be set to the following values:
* "0" - The return key will be handled as a key event. This is the behaviour of SDL <= 2.0.3. (default)
* "1" - The return key will hide the keyboard.
*
* The value of this hint is used at runtime, so it can be changed at any time.
*/
#define SDL_HINT_RETURN_KEY_HIDES_IME "SDL_RETURN_KEY_HIDES_IME"
/**
* \brief override the binding element for keyboard inputs for Emscripten builds
*
* This hint only applies to the emscripten platform
*
* The variable can be one of
* "#window" - The javascript window object (this is the default)
* "#document" - The javascript document object
* "#screen" - the javascript window.screen object
* "#canvas" - the WebGL canvas element
* any other string without a leading # sign applies to the element on the page with that ID.
*/
#define SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT "SDL_EMSCRIPTEN_KEYBOARD_ELEMENT"
/**
* \brief Tell SDL not to catch the SIGINT or SIGTERM signals.
*
* This hint only applies to Unix-like platforms.
*
* The variable can be set to the following values:
* "0" - SDL will install a SIGINT and SIGTERM handler, and when it
* catches a signal, convert it into an SDL_QUIT event.
* "1" - SDL will not install a signal handler at all.
*/
#define SDL_HINT_NO_SIGNAL_HANDLERS "SDL_NO_SIGNAL_HANDLERS"
/**
* \brief Tell SDL not to generate window-close events for Alt+F4 on Windows.
*
* The variable can be set to the following values:
* "0" - SDL will generate a window-close event when it sees Alt+F4.
* "1" - SDL will only do normal key handling for Alt+F4.
*/
#define SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 "SDL_WINDOWS_NO_CLOSE_ON_ALT_F4"
/**
* \brief Prevent SDL from using version 4 of the bitmap header when saving BMPs.
*
* The bitmap header version 4 is required for proper alpha channel support and
* SDL will use it when required. Should this not be desired, this hint can
* force the use of the 40 byte header version which is supported everywhere.
*
* The variable can be set to the following values:
* "0" - Surfaces with a colorkey or an alpha channel are saved to a
* 32-bit BMP file with an alpha mask. SDL will use the bitmap
* header version 4 and set the alpha mask accordingly.
* "1" - Surfaces with a colorkey or an alpha channel are saved to a
* 32-bit BMP file without an alpha mask. The alpha channel data
* will be in the file, but applications are going to ignore it.
*
* The default value is "0".
*/
#define SDL_HINT_BMP_SAVE_LEGACY_FORMAT "SDL_BMP_SAVE_LEGACY_FORMAT"
/**
* \brief Tell SDL not to name threads on Windows with the 0x406D1388 Exception.
* The 0x406D1388 Exception is a trick used to inform Visual Studio of a
* thread's name, but it tends to cause problems with other debuggers,
* and the .NET runtime. Note that SDL 2.0.6 and later will still use
* the (safer) SetThreadDescription API, introduced in the Windows 10
* Creators Update, if available.
*
* The variable can be set to the following values:
* "0" - SDL will raise the 0x406D1388 Exception to name threads.
* This is the default behavior of SDL <= 2.0.4.
* "1" - SDL will not raise this exception, and threads will be unnamed. (default)
* This is necessary with .NET languages or debuggers that aren't Visual Studio.
*/
#define SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING "SDL_WINDOWS_DISABLE_THREAD_NAMING"
/**
* \brief Tell SDL which Dispmanx layer to use on a Raspberry PI
*
* Also known as Z-order. The variable can take a negative or positive value.
* The default is 10000.
*/
#define SDL_HINT_RPI_VIDEO_LAYER "SDL_RPI_VIDEO_LAYER"
/**
* \brief Tell the video driver that we only want a double buffer.
*
* By default, most lowlevel 2D APIs will use a triple buffer scheme that
* wastes no CPU time on waiting for vsync after issuing a flip, but
* introduces a frame of latency. On the other hand, using a double buffer
* scheme instead is recommended for cases where low latency is an important
* factor because we save a whole frame of latency.
* We do so by waiting for vsync immediately after issuing a flip, usually just
* after eglSwapBuffers call in the backend's *_SwapWindow function.
*
* Since it's driver-specific, it's only supported where possible and
* implemented. Currently supported the following drivers:
* - KMSDRM (kmsdrm)
* - Raspberry Pi (raspberrypi)
*/
#define SDL_HINT_VIDEO_DOUBLE_BUFFER "SDL_VIDEO_DOUBLE_BUFFER"
/**
* \brief A variable controlling what driver to use for OpenGL ES contexts.
*
* On some platforms, currently Windows and X11, OpenGL drivers may support
* creating contexts with an OpenGL ES profile. By default SDL uses these
* profiles, when available, otherwise it attempts to load an OpenGL ES
* library, e.g. that provided by the ANGLE project. This variable controls
* whether SDL follows this default behaviour or will always load an
* OpenGL ES library.
*
* Circumstances where this is useful include
* - Testing an app with a particular OpenGL ES implementation, e.g ANGLE,
* or emulator, e.g. those from ARM, Imagination or Qualcomm.
* - Resolving OpenGL ES function addresses at link time by linking with
* the OpenGL ES library instead of querying them at run time with
* SDL_GL_GetProcAddress().
*
* Caution: for an application to work with the default behaviour across
* different OpenGL drivers it must query the OpenGL ES function
* addresses at run time using SDL_GL_GetProcAddress().
*
* This variable is ignored on most platforms because OpenGL ES is native
* or not supported.
*
* This variable can be set to the following values:
* "0" - Use ES profile of OpenGL, if available. (Default when not set.)
* "1" - Load OpenGL ES library using the default library names.
*
*/
#define SDL_HINT_OPENGL_ES_DRIVER "SDL_OPENGL_ES_DRIVER"
/**
* \brief A variable controlling speed/quality tradeoff of audio resampling.
*
* If available, SDL can use libsamplerate ( http://www.mega-nerd.com/SRC/ )
* to handle audio resampling. There are different resampling modes available
* that produce different levels of quality, using more CPU.
*
* If this hint isn't specified to a valid setting, or libsamplerate isn't
* available, SDL will use the default, internal resampling algorithm.
*
* Note that this is currently only applicable to resampling audio that is
* being written to a device for playback or audio being read from a device
* for capture. SDL_AudioCVT always uses the default resampler (although this
* might change for SDL 2.1).
*
* This hint is currently only checked at audio subsystem initialization.
*
* This variable can be set to the following values:
*
* "0" or "default" - Use SDL's internal resampling (Default when not set - low quality, fast)
* "1" or "fast" - Use fast, slightly higher quality resampling, if available
* "2" or "medium" - Use medium quality resampling, if available
* "3" or "best" - Use high quality resampling, if available
*/
#define SDL_HINT_AUDIO_RESAMPLING_MODE "SDL_AUDIO_RESAMPLING_MODE"
/**
* \brief A variable controlling the audio category on iOS and Mac OS X
*
* This variable can be set to the following values:
*
* "ambient" - Use the AVAudioSessionCategoryAmbient audio category, will be muted by the phone mute switch (default)
* "playback" - Use the AVAudioSessionCategoryPlayback category
*
* For more information, see Apple's documentation:
* https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionCategoriesandModes/AudioSessionCategoriesandModes.html
*/
#define SDL_HINT_AUDIO_CATEGORY "SDL_AUDIO_CATEGORY"
/**
* \brief An enumeration of hint priorities
*/
typedef enum
{
SDL_HINT_DEFAULT,
SDL_HINT_NORMAL,
SDL_HINT_OVERRIDE
} SDL_HintPriority;
/**
* \brief Set a hint with a specific priority
*
* The priority controls the behavior when setting a hint that already
* has a value. Hints will replace existing hints of their priority and
* lower. Environment variables are considered to have override priority.
*
* \return SDL_TRUE if the hint was set, SDL_FALSE otherwise
*/
extern DECLSPEC SDL_bool SDLCALL SDL_SetHintWithPriority(const char *name,
const char *value,
SDL_HintPriority priority);
/**
* \brief Set a hint with normal priority
*
* \return SDL_TRUE if the hint was set, SDL_FALSE otherwise
*/
extern DECLSPEC SDL_bool SDLCALL SDL_SetHint(const char *name,
const char *value);
/**
* \brief Get a hint
*
* \return The string value of a hint variable.
*/
extern DECLSPEC const char * SDLCALL SDL_GetHint(const char *name);
/**
* \brief Get a hint
*
* \return The boolean value of a hint variable.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GetHintBoolean(const char *name, SDL_bool default_value);
/**
* \brief type definition of the hint callback function.
*/
typedef void (SDLCALL *SDL_HintCallback)(void *userdata, const char *name, const char *oldValue, const char *newValue);
/**
* \brief Add a function to watch a particular hint
*
* \param name The hint to watch
* \param callback The function to call when the hint value changes
* \param userdata A pointer to pass to the callback function
*/
extern DECLSPEC void SDLCALL SDL_AddHintCallback(const char *name,
SDL_HintCallback callback,
void *userdata);
/**
* \brief Remove a function watching a particular hint
*
* \param name The hint being watched
* \param callback The function being called when the hint value changes
* \param userdata A pointer being passed to the callback function
*/
extern DECLSPEC void SDLCALL SDL_DelHintCallback(const char *name,
SDL_HintCallback callback,
void *userdata);
/**
* \brief Clear all hints
*
* This function is called during SDL_Quit() to free stored hints.
*/
extern DECLSPEC void SDLCALL SDL_ClearHints(void);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_hints_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 42,803 | C | 40.841642 | 174 | 0.705558 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_bits.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_bits.h
*
* Functions for fiddling with bits and bitmasks.
*/
#ifndef SDL_bits_h_
#define SDL_bits_h_
#include "SDL_stdinc.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \file SDL_bits.h
*/
/**
* Get the index of the most significant bit. Result is undefined when called
* with 0. This operation can also be stated as "count leading zeroes" and
* "log base 2".
*
* \return Index of the most significant bit, or -1 if the value is 0.
*/
#if defined(__WATCOMC__) && defined(__386__)
extern _inline int _SDL_clz_watcom (Uint32);
#pragma aux _SDL_clz_watcom = \
"bsr eax, eax" \
"xor eax, 31" \
parm [eax] nomemory \
value [eax] \
modify exact [eax] nomemory;
#endif
SDL_FORCE_INLINE int
SDL_MostSignificantBitIndex32(Uint32 x)
{
#if defined(__GNUC__) && (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
/* Count Leading Zeroes builtin in GCC.
* http://gcc.gnu.org/onlinedocs/gcc-4.3.4/gcc/Other-Builtins.html
*/
if (x == 0) {
return -1;
}
return 31 - __builtin_clz(x);
#elif defined(__WATCOMC__) && defined(__386__)
if (x == 0) {
return -1;
}
return 31 - _SDL_clz_watcom(x);
#else
/* Based off of Bit Twiddling Hacks by Sean Eron Anderson
* <[email protected]>, released in the public domain.
* http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog
*/
const Uint32 b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000};
const int S[] = {1, 2, 4, 8, 16};
int msbIndex = 0;
int i;
if (x == 0) {
return -1;
}
for (i = 4; i >= 0; i--)
{
if (x & b[i])
{
x >>= S[i];
msbIndex |= S[i];
}
}
return msbIndex;
#endif
}
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_bits_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 2,945 | C | 25.070796 | 82 | 0.632258 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_stdinc.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_stdinc.h
*
* This is a general header that includes C language support.
*/
#ifndef SDL_stdinc_h_
#define SDL_stdinc_h_
#include "SDL_config.h"
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#if defined(STDC_HEADERS)
# include <stdlib.h>
# include <stddef.h>
# include <stdarg.h>
#else
# if defined(HAVE_STDLIB_H)
# include <stdlib.h>
# elif defined(HAVE_MALLOC_H)
# include <malloc.h>
# endif
# if defined(HAVE_STDDEF_H)
# include <stddef.h>
# endif
# if defined(HAVE_STDARG_H)
# include <stdarg.h>
# endif
#endif
#ifdef HAVE_STRING_H
# if !defined(STDC_HEADERS) && defined(HAVE_MEMORY_H)
# include <memory.h>
# endif
# include <string.h>
#endif
#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif
#ifdef HAVE_WCHAR_H
# include <wchar.h>
#endif
#if defined(HAVE_INTTYPES_H)
# include <inttypes.h>
#elif defined(HAVE_STDINT_H)
# include <stdint.h>
#endif
#ifdef HAVE_CTYPE_H
# include <ctype.h>
#endif
#ifdef HAVE_MATH_H
# if defined(__WINRT__)
/* Defining _USE_MATH_DEFINES is required to get M_PI to be defined on
WinRT. See http://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
for more information.
*/
# define _USE_MATH_DEFINES
# endif
# include <math.h>
#endif
#ifdef HAVE_FLOAT_H
# include <float.h>
#endif
/**
* The number of elements in an array.
*/
#define SDL_arraysize(array) (sizeof(array)/sizeof(array[0]))
#define SDL_TABLESIZE(table) SDL_arraysize(table)
/**
* Macro useful for building other macros with strings in them
*
* e.g. #define LOG_ERROR(X) OutputDebugString(SDL_STRINGIFY_ARG(__FUNCTION__) ": " X "\n")
*/
#define SDL_STRINGIFY_ARG(arg) #arg
/**
* \name Cast operators
*
* Use proper C++ casts when compiled as C++ to be compatible with the option
* -Wold-style-cast of GCC (and -Werror=old-style-cast in GCC 4.2 and above).
*/
/* @{ */
#ifdef __cplusplus
#define SDL_reinterpret_cast(type, expression) reinterpret_cast<type>(expression)
#define SDL_static_cast(type, expression) static_cast<type>(expression)
#define SDL_const_cast(type, expression) const_cast<type>(expression)
#else
#define SDL_reinterpret_cast(type, expression) ((type)(expression))
#define SDL_static_cast(type, expression) ((type)(expression))
#define SDL_const_cast(type, expression) ((type)(expression))
#endif
/* @} *//* Cast operators */
/* Define a four character code as a Uint32 */
#define SDL_FOURCC(A, B, C, D) \
((SDL_static_cast(Uint32, SDL_static_cast(Uint8, (A))) << 0) | \
(SDL_static_cast(Uint32, SDL_static_cast(Uint8, (B))) << 8) | \
(SDL_static_cast(Uint32, SDL_static_cast(Uint8, (C))) << 16) | \
(SDL_static_cast(Uint32, SDL_static_cast(Uint8, (D))) << 24))
/**
* \name Basic data types
*/
/* @{ */
#ifdef __CC_ARM
/* ARM's compiler throws warnings if we use an enum: like "SDL_bool x = a < b;" */
#define SDL_FALSE 0
#define SDL_TRUE 1
typedef int SDL_bool;
#else
typedef enum
{
SDL_FALSE = 0,
SDL_TRUE = 1
} SDL_bool;
#endif
/**
* \brief A signed 8-bit integer type.
*/
#define SDL_MAX_SINT8 ((Sint8)0x7F) /* 127 */
#define SDL_MIN_SINT8 ((Sint8)(~0x7F)) /* -128 */
typedef int8_t Sint8;
/**
* \brief An unsigned 8-bit integer type.
*/
#define SDL_MAX_UINT8 ((Uint8)0xFF) /* 255 */
#define SDL_MIN_UINT8 ((Uint8)0x00) /* 0 */
typedef uint8_t Uint8;
/**
* \brief A signed 16-bit integer type.
*/
#define SDL_MAX_SINT16 ((Sint16)0x7FFF) /* 32767 */
#define SDL_MIN_SINT16 ((Sint16)(~0x7FFF)) /* -32768 */
typedef int16_t Sint16;
/**
* \brief An unsigned 16-bit integer type.
*/
#define SDL_MAX_UINT16 ((Uint16)0xFFFF) /* 65535 */
#define SDL_MIN_UINT16 ((Uint16)0x0000) /* 0 */
typedef uint16_t Uint16;
/**
* \brief A signed 32-bit integer type.
*/
#define SDL_MAX_SINT32 ((Sint32)0x7FFFFFFF) /* 2147483647 */
#define SDL_MIN_SINT32 ((Sint32)(~0x7FFFFFFF)) /* -2147483648 */
typedef int32_t Sint32;
/**
* \brief An unsigned 32-bit integer type.
*/
#define SDL_MAX_UINT32 ((Uint32)0xFFFFFFFFu) /* 4294967295 */
#define SDL_MIN_UINT32 ((Uint32)0x00000000) /* 0 */
typedef uint32_t Uint32;
/**
* \brief A signed 64-bit integer type.
*/
#define SDL_MAX_SINT64 ((Sint64)0x7FFFFFFFFFFFFFFFll) /* 9223372036854775807 */
#define SDL_MIN_SINT64 ((Sint64)(~0x7FFFFFFFFFFFFFFFll)) /* -9223372036854775808 */
typedef int64_t Sint64;
/**
* \brief An unsigned 64-bit integer type.
*/
#define SDL_MAX_UINT64 ((Uint64)0xFFFFFFFFFFFFFFFFull) /* 18446744073709551615 */
#define SDL_MIN_UINT64 ((Uint64)(0x0000000000000000ull)) /* 0 */
typedef uint64_t Uint64;
/* @} *//* Basic data types */
/* Make sure we have macros for printing 64 bit values.
* <stdint.h> should define these but this is not true all platforms.
* (for example win32) */
#ifndef SDL_PRIs64
#ifdef PRIs64
#define SDL_PRIs64 PRIs64
#elif defined(__WIN32__)
#define SDL_PRIs64 "I64d"
#elif defined(__LINUX__) && defined(__LP64__)
#define SDL_PRIs64 "ld"
#else
#define SDL_PRIs64 "lld"
#endif
#endif
#ifndef SDL_PRIu64
#ifdef PRIu64
#define SDL_PRIu64 PRIu64
#elif defined(__WIN32__)
#define SDL_PRIu64 "I64u"
#elif defined(__LINUX__) && defined(__LP64__)
#define SDL_PRIu64 "lu"
#else
#define SDL_PRIu64 "llu"
#endif
#endif
#ifndef SDL_PRIx64
#ifdef PRIx64
#define SDL_PRIx64 PRIx64
#elif defined(__WIN32__)
#define SDL_PRIx64 "I64x"
#elif defined(__LINUX__) && defined(__LP64__)
#define SDL_PRIx64 "lx"
#else
#define SDL_PRIx64 "llx"
#endif
#endif
#ifndef SDL_PRIX64
#ifdef PRIX64
#define SDL_PRIX64 PRIX64
#elif defined(__WIN32__)
#define SDL_PRIX64 "I64X"
#elif defined(__LINUX__) && defined(__LP64__)
#define SDL_PRIX64 "lX"
#else
#define SDL_PRIX64 "llX"
#endif
#endif
/* Annotations to help code analysis tools */
#ifdef SDL_DISABLE_ANALYZE_MACROS
#define SDL_IN_BYTECAP(x)
#define SDL_INOUT_Z_CAP(x)
#define SDL_OUT_Z_CAP(x)
#define SDL_OUT_CAP(x)
#define SDL_OUT_BYTECAP(x)
#define SDL_OUT_Z_BYTECAP(x)
#define SDL_PRINTF_FORMAT_STRING
#define SDL_SCANF_FORMAT_STRING
#define SDL_PRINTF_VARARG_FUNC( fmtargnumber )
#define SDL_SCANF_VARARG_FUNC( fmtargnumber )
#else
#if defined(_MSC_VER) && (_MSC_VER >= 1600) /* VS 2010 and above */
#include <sal.h>
#define SDL_IN_BYTECAP(x) _In_bytecount_(x)
#define SDL_INOUT_Z_CAP(x) _Inout_z_cap_(x)
#define SDL_OUT_Z_CAP(x) _Out_z_cap_(x)
#define SDL_OUT_CAP(x) _Out_cap_(x)
#define SDL_OUT_BYTECAP(x) _Out_bytecap_(x)
#define SDL_OUT_Z_BYTECAP(x) _Out_z_bytecap_(x)
#define SDL_PRINTF_FORMAT_STRING _Printf_format_string_
#define SDL_SCANF_FORMAT_STRING _Scanf_format_string_impl_
#else
#define SDL_IN_BYTECAP(x)
#define SDL_INOUT_Z_CAP(x)
#define SDL_OUT_Z_CAP(x)
#define SDL_OUT_CAP(x)
#define SDL_OUT_BYTECAP(x)
#define SDL_OUT_Z_BYTECAP(x)
#define SDL_PRINTF_FORMAT_STRING
#define SDL_SCANF_FORMAT_STRING
#endif
#if defined(__GNUC__)
#define SDL_PRINTF_VARARG_FUNC( fmtargnumber ) __attribute__ (( format( __printf__, fmtargnumber, fmtargnumber+1 )))
#define SDL_SCANF_VARARG_FUNC( fmtargnumber ) __attribute__ (( format( __scanf__, fmtargnumber, fmtargnumber+1 )))
#else
#define SDL_PRINTF_VARARG_FUNC( fmtargnumber )
#define SDL_SCANF_VARARG_FUNC( fmtargnumber )
#endif
#endif /* SDL_DISABLE_ANALYZE_MACROS */
#define SDL_COMPILE_TIME_ASSERT(name, x) \
typedef int SDL_compile_time_assert_ ## name[(x) * 2 - 1]
/** \cond */
#ifndef DOXYGEN_SHOULD_IGNORE_THIS
SDL_COMPILE_TIME_ASSERT(uint8, sizeof(Uint8) == 1);
SDL_COMPILE_TIME_ASSERT(sint8, sizeof(Sint8) == 1);
SDL_COMPILE_TIME_ASSERT(uint16, sizeof(Uint16) == 2);
SDL_COMPILE_TIME_ASSERT(sint16, sizeof(Sint16) == 2);
SDL_COMPILE_TIME_ASSERT(uint32, sizeof(Uint32) == 4);
SDL_COMPILE_TIME_ASSERT(sint32, sizeof(Sint32) == 4);
SDL_COMPILE_TIME_ASSERT(uint64, sizeof(Uint64) == 8);
SDL_COMPILE_TIME_ASSERT(sint64, sizeof(Sint64) == 8);
#endif /* DOXYGEN_SHOULD_IGNORE_THIS */
/** \endcond */
/* Check to make sure enums are the size of ints, for structure packing.
For both Watcom C/C++ and Borland C/C++ the compiler option that makes
enums having the size of an int must be enabled.
This is "-b" for Borland C/C++ and "-ei" for Watcom C/C++ (v11).
*/
/** \cond */
#ifndef DOXYGEN_SHOULD_IGNORE_THIS
#if !defined(__ANDROID__)
/* TODO: include/SDL_stdinc.h:174: error: size of array 'SDL_dummy_enum' is negative */
typedef enum
{
DUMMY_ENUM_VALUE
} SDL_DUMMY_ENUM;
SDL_COMPILE_TIME_ASSERT(enum, sizeof(SDL_DUMMY_ENUM) == sizeof(int));
#endif
#endif /* DOXYGEN_SHOULD_IGNORE_THIS */
/** \endcond */
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
#if defined(HAVE_ALLOCA) && !defined(alloca)
# if defined(HAVE_ALLOCA_H)
# include <alloca.h>
# elif defined(__GNUC__)
# define alloca __builtin_alloca
# elif defined(_MSC_VER)
# include <malloc.h>
# define alloca _alloca
# elif defined(__WATCOMC__)
# include <malloc.h>
# elif defined(__BORLANDC__)
# include <malloc.h>
# elif defined(__DMC__)
# include <stdlib.h>
# elif defined(__AIX__)
#pragma alloca
# elif defined(__MRC__)
void *alloca(unsigned);
# else
char *alloca();
# endif
#endif
#ifdef HAVE_ALLOCA
#define SDL_stack_alloc(type, count) (type*)alloca(sizeof(type)*(count))
#define SDL_stack_free(data)
#else
#define SDL_stack_alloc(type, count) (type*)SDL_malloc(sizeof(type)*(count))
#define SDL_stack_free(data) SDL_free(data)
#endif
extern DECLSPEC void *SDLCALL SDL_malloc(size_t size);
extern DECLSPEC void *SDLCALL SDL_calloc(size_t nmemb, size_t size);
extern DECLSPEC void *SDLCALL SDL_realloc(void *mem, size_t size);
extern DECLSPEC void SDLCALL SDL_free(void *mem);
typedef void *(SDLCALL *SDL_malloc_func)(size_t size);
typedef void *(SDLCALL *SDL_calloc_func)(size_t nmemb, size_t size);
typedef void *(SDLCALL *SDL_realloc_func)(void *mem, size_t size);
typedef void (SDLCALL *SDL_free_func)(void *mem);
/**
* \brief Get the current set of SDL memory functions
*/
extern DECLSPEC void SDLCALL SDL_GetMemoryFunctions(SDL_malloc_func *malloc_func,
SDL_calloc_func *calloc_func,
SDL_realloc_func *realloc_func,
SDL_free_func *free_func);
/**
* \brief Replace SDL's memory allocation functions with a custom set
*
* \note If you are replacing SDL's memory functions, you should call
* SDL_GetNumAllocations() and be very careful if it returns non-zero.
* That means that your free function will be called with memory
* allocated by the previous memory allocation functions.
*/
extern DECLSPEC int SDLCALL SDL_SetMemoryFunctions(SDL_malloc_func malloc_func,
SDL_calloc_func calloc_func,
SDL_realloc_func realloc_func,
SDL_free_func free_func);
/**
* \brief Get the number of outstanding (unfreed) allocations
*/
extern DECLSPEC int SDLCALL SDL_GetNumAllocations(void);
extern DECLSPEC char *SDLCALL SDL_getenv(const char *name);
extern DECLSPEC int SDLCALL SDL_setenv(const char *name, const char *value, int overwrite);
extern DECLSPEC void SDLCALL SDL_qsort(void *base, size_t nmemb, size_t size, int (*compare) (const void *, const void *));
extern DECLSPEC int SDLCALL SDL_abs(int x);
/* !!! FIXME: these have side effects. You probably shouldn't use them. */
/* !!! FIXME: Maybe we do forceinline functions of SDL_mini, SDL_minf, etc? */
#define SDL_min(x, y) (((x) < (y)) ? (x) : (y))
#define SDL_max(x, y) (((x) > (y)) ? (x) : (y))
extern DECLSPEC int SDLCALL SDL_isdigit(int x);
extern DECLSPEC int SDLCALL SDL_isspace(int x);
extern DECLSPEC int SDLCALL SDL_toupper(int x);
extern DECLSPEC int SDLCALL SDL_tolower(int x);
extern DECLSPEC void *SDLCALL SDL_memset(SDL_OUT_BYTECAP(len) void *dst, int c, size_t len);
#define SDL_zero(x) SDL_memset(&(x), 0, sizeof((x)))
#define SDL_zerop(x) SDL_memset((x), 0, sizeof(*(x)))
/* Note that memset() is a byte assignment and this is a 32-bit assignment, so they're not directly equivalent. */
SDL_FORCE_INLINE void SDL_memset4(void *dst, Uint32 val, size_t dwords)
{
#if defined(__GNUC__) && defined(i386)
int u0, u1, u2;
__asm__ __volatile__ (
"cld \n\t"
"rep ; stosl \n\t"
: "=&D" (u0), "=&a" (u1), "=&c" (u2)
: "0" (dst), "1" (val), "2" (SDL_static_cast(Uint32, dwords))
: "memory"
);
#else
size_t _n = (dwords + 3) / 4;
Uint32 *_p = SDL_static_cast(Uint32 *, dst);
Uint32 _val = (val);
if (dwords == 0)
return;
switch (dwords % 4)
{
case 0: do { *_p++ = _val; /* fallthrough */
case 3: *_p++ = _val; /* fallthrough */
case 2: *_p++ = _val; /* fallthrough */
case 1: *_p++ = _val; /* fallthrough */
} while ( --_n );
}
#endif
}
extern DECLSPEC void *SDLCALL SDL_memcpy(SDL_OUT_BYTECAP(len) void *dst, SDL_IN_BYTECAP(len) const void *src, size_t len);
extern DECLSPEC void *SDLCALL SDL_memmove(SDL_OUT_BYTECAP(len) void *dst, SDL_IN_BYTECAP(len) const void *src, size_t len);
extern DECLSPEC int SDLCALL SDL_memcmp(const void *s1, const void *s2, size_t len);
extern DECLSPEC size_t SDLCALL SDL_wcslen(const wchar_t *wstr);
extern DECLSPEC size_t SDLCALL SDL_wcslcpy(SDL_OUT_Z_CAP(maxlen) wchar_t *dst, const wchar_t *src, size_t maxlen);
extern DECLSPEC size_t SDLCALL SDL_wcslcat(SDL_INOUT_Z_CAP(maxlen) wchar_t *dst, const wchar_t *src, size_t maxlen);
extern DECLSPEC int SDLCALL SDL_wcscmp(const wchar_t *str1, const wchar_t *str2);
extern DECLSPEC size_t SDLCALL SDL_strlen(const char *str);
extern DECLSPEC size_t SDLCALL SDL_strlcpy(SDL_OUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen);
extern DECLSPEC size_t SDLCALL SDL_utf8strlcpy(SDL_OUT_Z_CAP(dst_bytes) char *dst, const char *src, size_t dst_bytes);
extern DECLSPEC size_t SDLCALL SDL_strlcat(SDL_INOUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen);
extern DECLSPEC char *SDLCALL SDL_strdup(const char *str);
extern DECLSPEC char *SDLCALL SDL_strrev(char *str);
extern DECLSPEC char *SDLCALL SDL_strupr(char *str);
extern DECLSPEC char *SDLCALL SDL_strlwr(char *str);
extern DECLSPEC char *SDLCALL SDL_strchr(const char *str, int c);
extern DECLSPEC char *SDLCALL SDL_strrchr(const char *str, int c);
extern DECLSPEC char *SDLCALL SDL_strstr(const char *haystack, const char *needle);
extern DECLSPEC size_t SDLCALL SDL_utf8strlen(const char *str);
extern DECLSPEC char *SDLCALL SDL_itoa(int value, char *str, int radix);
extern DECLSPEC char *SDLCALL SDL_uitoa(unsigned int value, char *str, int radix);
extern DECLSPEC char *SDLCALL SDL_ltoa(long value, char *str, int radix);
extern DECLSPEC char *SDLCALL SDL_ultoa(unsigned long value, char *str, int radix);
extern DECLSPEC char *SDLCALL SDL_lltoa(Sint64 value, char *str, int radix);
extern DECLSPEC char *SDLCALL SDL_ulltoa(Uint64 value, char *str, int radix);
extern DECLSPEC int SDLCALL SDL_atoi(const char *str);
extern DECLSPEC double SDLCALL SDL_atof(const char *str);
extern DECLSPEC long SDLCALL SDL_strtol(const char *str, char **endp, int base);
extern DECLSPEC unsigned long SDLCALL SDL_strtoul(const char *str, char **endp, int base);
extern DECLSPEC Sint64 SDLCALL SDL_strtoll(const char *str, char **endp, int base);
extern DECLSPEC Uint64 SDLCALL SDL_strtoull(const char *str, char **endp, int base);
extern DECLSPEC double SDLCALL SDL_strtod(const char *str, char **endp);
extern DECLSPEC int SDLCALL SDL_strcmp(const char *str1, const char *str2);
extern DECLSPEC int SDLCALL SDL_strncmp(const char *str1, const char *str2, size_t maxlen);
extern DECLSPEC int SDLCALL SDL_strcasecmp(const char *str1, const char *str2);
extern DECLSPEC int SDLCALL SDL_strncasecmp(const char *str1, const char *str2, size_t len);
extern DECLSPEC int SDLCALL SDL_sscanf(const char *text, SDL_SCANF_FORMAT_STRING const char *fmt, ...) SDL_SCANF_VARARG_FUNC(2);
extern DECLSPEC int SDLCALL SDL_vsscanf(const char *text, const char *fmt, va_list ap);
extern DECLSPEC int SDLCALL SDL_snprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, ... ) SDL_PRINTF_VARARG_FUNC(3);
extern DECLSPEC int SDLCALL SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt, va_list ap);
#ifndef HAVE_M_PI
#ifndef M_PI
#define M_PI 3.14159265358979323846264338327950288 /**< pi */
#endif
#endif
extern DECLSPEC double SDLCALL SDL_acos(double x);
extern DECLSPEC float SDLCALL SDL_acosf(float x);
extern DECLSPEC double SDLCALL SDL_asin(double x);
extern DECLSPEC float SDLCALL SDL_asinf(float x);
extern DECLSPEC double SDLCALL SDL_atan(double x);
extern DECLSPEC float SDLCALL SDL_atanf(float x);
extern DECLSPEC double SDLCALL SDL_atan2(double x, double y);
extern DECLSPEC float SDLCALL SDL_atan2f(float x, float y);
extern DECLSPEC double SDLCALL SDL_ceil(double x);
extern DECLSPEC float SDLCALL SDL_ceilf(float x);
extern DECLSPEC double SDLCALL SDL_copysign(double x, double y);
extern DECLSPEC float SDLCALL SDL_copysignf(float x, float y);
extern DECLSPEC double SDLCALL SDL_cos(double x);
extern DECLSPEC float SDLCALL SDL_cosf(float x);
extern DECLSPEC double SDLCALL SDL_fabs(double x);
extern DECLSPEC float SDLCALL SDL_fabsf(float x);
extern DECLSPEC double SDLCALL SDL_floor(double x);
extern DECLSPEC float SDLCALL SDL_floorf(float x);
extern DECLSPEC double SDLCALL SDL_fmod(double x, double y);
extern DECLSPEC float SDLCALL SDL_fmodf(float x, float y);
extern DECLSPEC double SDLCALL SDL_log(double x);
extern DECLSPEC float SDLCALL SDL_logf(float x);
extern DECLSPEC double SDLCALL SDL_log10(double x);
extern DECLSPEC float SDLCALL SDL_log10f(float x);
extern DECLSPEC double SDLCALL SDL_pow(double x, double y);
extern DECLSPEC float SDLCALL SDL_powf(float x, float y);
extern DECLSPEC double SDLCALL SDL_scalbn(double x, int n);
extern DECLSPEC float SDLCALL SDL_scalbnf(float x, int n);
extern DECLSPEC double SDLCALL SDL_sin(double x);
extern DECLSPEC float SDLCALL SDL_sinf(float x);
extern DECLSPEC double SDLCALL SDL_sqrt(double x);
extern DECLSPEC float SDLCALL SDL_sqrtf(float x);
extern DECLSPEC double SDLCALL SDL_tan(double x);
extern DECLSPEC float SDLCALL SDL_tanf(float x);
/* The SDL implementation of iconv() returns these error codes */
#define SDL_ICONV_ERROR (size_t)-1
#define SDL_ICONV_E2BIG (size_t)-2
#define SDL_ICONV_EILSEQ (size_t)-3
#define SDL_ICONV_EINVAL (size_t)-4
/* SDL_iconv_* are now always real symbols/types, not macros or inlined. */
typedef struct _SDL_iconv_t *SDL_iconv_t;
extern DECLSPEC SDL_iconv_t SDLCALL SDL_iconv_open(const char *tocode,
const char *fromcode);
extern DECLSPEC int SDLCALL SDL_iconv_close(SDL_iconv_t cd);
extern DECLSPEC size_t SDLCALL SDL_iconv(SDL_iconv_t cd, const char **inbuf,
size_t * inbytesleft, char **outbuf,
size_t * outbytesleft);
/**
* This function converts a string between encodings in one pass, returning a
* string that must be freed with SDL_free() or NULL on error.
*/
extern DECLSPEC char *SDLCALL SDL_iconv_string(const char *tocode,
const char *fromcode,
const char *inbuf,
size_t inbytesleft);
#define SDL_iconv_utf8_locale(S) SDL_iconv_string("", "UTF-8", S, SDL_strlen(S)+1)
#define SDL_iconv_utf8_ucs2(S) (Uint16 *)SDL_iconv_string("UCS-2-INTERNAL", "UTF-8", S, SDL_strlen(S)+1)
#define SDL_iconv_utf8_ucs4(S) (Uint32 *)SDL_iconv_string("UCS-4-INTERNAL", "UTF-8", S, SDL_strlen(S)+1)
/* force builds using Clang's static analysis tools to use literal C runtime
here, since there are possibly tests that are ineffective otherwise. */
#if defined(__clang_analyzer__) && !defined(SDL_DISABLE_ANALYZE_MACROS)
#define SDL_malloc malloc
#define SDL_calloc calloc
#define SDL_realloc realloc
#define SDL_free free
#define SDL_memset memset
#define SDL_memcpy memcpy
#define SDL_memmove memmove
#define SDL_memcmp memcmp
#define SDL_strlen strlen
#define SDL_strlcpy strlcpy
#define SDL_strlcat strlcat
#define SDL_strdup strdup
#define SDL_strchr strchr
#define SDL_strrchr strrchr
#define SDL_strstr strstr
#define SDL_strcmp strcmp
#define SDL_strncmp strncmp
#define SDL_strcasecmp strcasecmp
#define SDL_strncasecmp strncasecmp
#define SDL_sscanf sscanf
#define SDL_vsscanf vsscanf
#define SDL_snprintf snprintf
#define SDL_vsnprintf vsnprintf
#endif
SDL_FORCE_INLINE void *SDL_memcpy4(SDL_OUT_BYTECAP(dwords*4) void *dst, SDL_IN_BYTECAP(dwords*4) const void *src, size_t dwords)
{
return SDL_memcpy(dst, src, dwords * 4);
}
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_stdinc_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 21,999 | C | 35.30363 | 164 | 0.689077 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_endian.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_endian.h
*
* Functions for reading and writing endian-specific values
*/
#ifndef SDL_endian_h_
#define SDL_endian_h_
#include "SDL_stdinc.h"
/**
* \name The two types of endianness
*/
/* @{ */
#define SDL_LIL_ENDIAN 1234
#define SDL_BIG_ENDIAN 4321
/* @} */
#ifndef SDL_BYTEORDER /* Not defined in SDL_config.h? */
#ifdef __linux__
#include <endian.h>
#define SDL_BYTEORDER __BYTE_ORDER
#else /* __linux__ */
#if defined(__hppa__) || \
defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \
(defined(__MIPS__) && defined(__MISPEB__)) || \
defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \
defined(__sparc__)
#define SDL_BYTEORDER SDL_BIG_ENDIAN
#else
#define SDL_BYTEORDER SDL_LIL_ENDIAN
#endif
#endif /* __linux__ */
#endif /* !SDL_BYTEORDER */
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \file SDL_endian.h
*/
#if defined(__GNUC__) && defined(__i386__) && \
!(__GNUC__ == 2 && __GNUC_MINOR__ == 95 /* broken gcc version */)
SDL_FORCE_INLINE Uint16
SDL_Swap16(Uint16 x)
{
__asm__("xchgb %b0,%h0": "=q"(x):"0"(x));
return x;
}
#elif defined(__GNUC__) && defined(__x86_64__)
SDL_FORCE_INLINE Uint16
SDL_Swap16(Uint16 x)
{
__asm__("xchgb %b0,%h0": "=Q"(x):"0"(x));
return x;
}
#elif defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__))
SDL_FORCE_INLINE Uint16
SDL_Swap16(Uint16 x)
{
int result;
__asm__("rlwimi %0,%2,8,16,23": "=&r"(result):"0"(x >> 8), "r"(x));
return (Uint16)result;
}
#elif defined(__GNUC__) && (defined(__M68000__) || defined(__M68020__)) && !defined(__mcoldfire__)
SDL_FORCE_INLINE Uint16
SDL_Swap16(Uint16 x)
{
__asm__("rorw #8,%0": "=d"(x): "0"(x):"cc");
return x;
}
#elif defined(__WATCOMC__) && defined(__386__)
extern _inline Uint16 SDL_Swap16(Uint16);
#pragma aux SDL_Swap16 = \
"xchg al, ah" \
parm [ax] \
modify [ax];
#else
SDL_FORCE_INLINE Uint16
SDL_Swap16(Uint16 x)
{
return SDL_static_cast(Uint16, ((x << 8) | (x >> 8)));
}
#endif
#if defined(__GNUC__) && defined(__i386__)
SDL_FORCE_INLINE Uint32
SDL_Swap32(Uint32 x)
{
__asm__("bswap %0": "=r"(x):"0"(x));
return x;
}
#elif defined(__GNUC__) && defined(__x86_64__)
SDL_FORCE_INLINE Uint32
SDL_Swap32(Uint32 x)
{
__asm__("bswapl %0": "=r"(x):"0"(x));
return x;
}
#elif defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__))
SDL_FORCE_INLINE Uint32
SDL_Swap32(Uint32 x)
{
Uint32 result;
__asm__("rlwimi %0,%2,24,16,23": "=&r"(result):"0"(x >> 24), "r"(x));
__asm__("rlwimi %0,%2,8,8,15": "=&r"(result):"0"(result), "r"(x));
__asm__("rlwimi %0,%2,24,0,7": "=&r"(result):"0"(result), "r"(x));
return result;
}
#elif defined(__GNUC__) && (defined(__M68000__) || defined(__M68020__)) && !defined(__mcoldfire__)
SDL_FORCE_INLINE Uint32
SDL_Swap32(Uint32 x)
{
__asm__("rorw #8,%0\n\tswap %0\n\trorw #8,%0": "=d"(x): "0"(x):"cc");
return x;
}
#elif defined(__WATCOMC__) && defined(__386__)
extern _inline Uint32 SDL_Swap32(Uint32);
#ifndef __SW_3 /* 486+ */
#pragma aux SDL_Swap32 = \
"bswap eax" \
parm [eax] \
modify [eax];
#else /* 386-only */
#pragma aux SDL_Swap32 = \
"xchg al, ah" \
"ror eax, 16" \
"xchg al, ah" \
parm [eax] \
modify [eax];
#endif
#else
SDL_FORCE_INLINE Uint32
SDL_Swap32(Uint32 x)
{
return SDL_static_cast(Uint32, ((x << 24) | ((x << 8) & 0x00FF0000) |
((x >> 8) & 0x0000FF00) | (x >> 24)));
}
#endif
#if defined(__GNUC__) && defined(__i386__)
SDL_FORCE_INLINE Uint64
SDL_Swap64(Uint64 x)
{
union
{
struct
{
Uint32 a, b;
} s;
Uint64 u;
} v;
v.u = x;
__asm__("bswapl %0 ; bswapl %1 ; xchgl %0,%1": "=r"(v.s.a), "=r"(v.s.b):"0"(v.s.a),
"1"(v.s.
b));
return v.u;
}
#elif defined(__GNUC__) && defined(__x86_64__)
SDL_FORCE_INLINE Uint64
SDL_Swap64(Uint64 x)
{
__asm__("bswapq %0": "=r"(x):"0"(x));
return x;
}
#else
SDL_FORCE_INLINE Uint64
SDL_Swap64(Uint64 x)
{
Uint32 hi, lo;
/* Separate into high and low 32-bit values and swap them */
lo = SDL_static_cast(Uint32, x & 0xFFFFFFFF);
x >>= 32;
hi = SDL_static_cast(Uint32, x & 0xFFFFFFFF);
x = SDL_Swap32(lo);
x <<= 32;
x |= SDL_Swap32(hi);
return (x);
}
#endif
SDL_FORCE_INLINE float
SDL_SwapFloat(float x)
{
union
{
float f;
Uint32 ui32;
} swapper;
swapper.f = x;
swapper.ui32 = SDL_Swap32(swapper.ui32);
return swapper.f;
}
/**
* \name Swap to native
* Byteswap item from the specified endianness to the native endianness.
*/
/* @{ */
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define SDL_SwapLE16(X) (X)
#define SDL_SwapLE32(X) (X)
#define SDL_SwapLE64(X) (X)
#define SDL_SwapFloatLE(X) (X)
#define SDL_SwapBE16(X) SDL_Swap16(X)
#define SDL_SwapBE32(X) SDL_Swap32(X)
#define SDL_SwapBE64(X) SDL_Swap64(X)
#define SDL_SwapFloatBE(X) SDL_SwapFloat(X)
#else
#define SDL_SwapLE16(X) SDL_Swap16(X)
#define SDL_SwapLE32(X) SDL_Swap32(X)
#define SDL_SwapLE64(X) SDL_Swap64(X)
#define SDL_SwapFloatLE(X) SDL_SwapFloat(X)
#define SDL_SwapBE16(X) (X)
#define SDL_SwapBE32(X) (X)
#define SDL_SwapBE64(X) (X)
#define SDL_SwapFloatBE(X) (X)
#endif
/* @} *//* Swap to native */
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_endian_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 6,451 | C | 23.720306 | 98 | 0.600837 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_keycode.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_keycode.h
*
* Defines constants which identify keyboard keys and modifiers.
*/
#ifndef SDL_keycode_h_
#define SDL_keycode_h_
#include "SDL_stdinc.h"
#include "SDL_scancode.h"
/**
* \brief The SDL virtual key representation.
*
* Values of this type are used to represent keyboard keys using the current
* layout of the keyboard. These values include Unicode values representing
* the unmodified character that would be generated by pressing the key, or
* an SDLK_* constant for those keys that do not generate characters.
*
* A special exception is the number keys at the top of the keyboard which
* always map to SDLK_0...SDLK_9, regardless of layout.
*/
typedef Sint32 SDL_Keycode;
#define SDLK_SCANCODE_MASK (1<<30)
#define SDL_SCANCODE_TO_KEYCODE(X) (X | SDLK_SCANCODE_MASK)
enum
{
SDLK_UNKNOWN = 0,
SDLK_RETURN = '\r',
SDLK_ESCAPE = '\033',
SDLK_BACKSPACE = '\b',
SDLK_TAB = '\t',
SDLK_SPACE = ' ',
SDLK_EXCLAIM = '!',
SDLK_QUOTEDBL = '"',
SDLK_HASH = '#',
SDLK_PERCENT = '%',
SDLK_DOLLAR = '$',
SDLK_AMPERSAND = '&',
SDLK_QUOTE = '\'',
SDLK_LEFTPAREN = '(',
SDLK_RIGHTPAREN = ')',
SDLK_ASTERISK = '*',
SDLK_PLUS = '+',
SDLK_COMMA = ',',
SDLK_MINUS = '-',
SDLK_PERIOD = '.',
SDLK_SLASH = '/',
SDLK_0 = '0',
SDLK_1 = '1',
SDLK_2 = '2',
SDLK_3 = '3',
SDLK_4 = '4',
SDLK_5 = '5',
SDLK_6 = '6',
SDLK_7 = '7',
SDLK_8 = '8',
SDLK_9 = '9',
SDLK_COLON = ':',
SDLK_SEMICOLON = ';',
SDLK_LESS = '<',
SDLK_EQUALS = '=',
SDLK_GREATER = '>',
SDLK_QUESTION = '?',
SDLK_AT = '@',
/*
Skip uppercase letters
*/
SDLK_LEFTBRACKET = '[',
SDLK_BACKSLASH = '\\',
SDLK_RIGHTBRACKET = ']',
SDLK_CARET = '^',
SDLK_UNDERSCORE = '_',
SDLK_BACKQUOTE = '`',
SDLK_a = 'a',
SDLK_b = 'b',
SDLK_c = 'c',
SDLK_d = 'd',
SDLK_e = 'e',
SDLK_f = 'f',
SDLK_g = 'g',
SDLK_h = 'h',
SDLK_i = 'i',
SDLK_j = 'j',
SDLK_k = 'k',
SDLK_l = 'l',
SDLK_m = 'm',
SDLK_n = 'n',
SDLK_o = 'o',
SDLK_p = 'p',
SDLK_q = 'q',
SDLK_r = 'r',
SDLK_s = 's',
SDLK_t = 't',
SDLK_u = 'u',
SDLK_v = 'v',
SDLK_w = 'w',
SDLK_x = 'x',
SDLK_y = 'y',
SDLK_z = 'z',
SDLK_CAPSLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CAPSLOCK),
SDLK_F1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F1),
SDLK_F2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F2),
SDLK_F3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F3),
SDLK_F4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F4),
SDLK_F5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F5),
SDLK_F6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F6),
SDLK_F7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F7),
SDLK_F8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F8),
SDLK_F9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F9),
SDLK_F10 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F10),
SDLK_F11 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F11),
SDLK_F12 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F12),
SDLK_PRINTSCREEN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRINTSCREEN),
SDLK_SCROLLLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SCROLLLOCK),
SDLK_PAUSE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAUSE),
SDLK_INSERT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INSERT),
SDLK_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HOME),
SDLK_PAGEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEUP),
SDLK_DELETE = '\177',
SDLK_END = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_END),
SDLK_PAGEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEDOWN),
SDLK_RIGHT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RIGHT),
SDLK_LEFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LEFT),
SDLK_DOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DOWN),
SDLK_UP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UP),
SDLK_NUMLOCKCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_NUMLOCKCLEAR),
SDLK_KP_DIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DIVIDE),
SDLK_KP_MULTIPLY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MULTIPLY),
SDLK_KP_MINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MINUS),
SDLK_KP_PLUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUS),
SDLK_KP_ENTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_ENTER),
SDLK_KP_1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_1),
SDLK_KP_2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_2),
SDLK_KP_3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_3),
SDLK_KP_4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_4),
SDLK_KP_5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_5),
SDLK_KP_6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_6),
SDLK_KP_7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_7),
SDLK_KP_8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_8),
SDLK_KP_9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_9),
SDLK_KP_0 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_0),
SDLK_KP_PERIOD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERIOD),
SDLK_APPLICATION = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APPLICATION),
SDLK_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_POWER),
SDLK_KP_EQUALS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALS),
SDLK_F13 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F13),
SDLK_F14 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F14),
SDLK_F15 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F15),
SDLK_F16 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F16),
SDLK_F17 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F17),
SDLK_F18 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F18),
SDLK_F19 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F19),
SDLK_F20 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F20),
SDLK_F21 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F21),
SDLK_F22 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F22),
SDLK_F23 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F23),
SDLK_F24 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F24),
SDLK_EXECUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXECUTE),
SDLK_HELP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HELP),
SDLK_MENU = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MENU),
SDLK_SELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SELECT),
SDLK_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_STOP),
SDLK_AGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AGAIN),
SDLK_UNDO = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UNDO),
SDLK_CUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CUT),
SDLK_COPY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COPY),
SDLK_PASTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PASTE),
SDLK_FIND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_FIND),
SDLK_MUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MUTE),
SDLK_VOLUMEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEUP),
SDLK_VOLUMEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEDOWN),
SDLK_KP_COMMA = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COMMA),
SDLK_KP_EQUALSAS400 =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALSAS400),
SDLK_ALTERASE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_ALTERASE),
SDLK_SYSREQ = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SYSREQ),
SDLK_CANCEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CANCEL),
SDLK_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEAR),
SDLK_PRIOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRIOR),
SDLK_RETURN2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RETURN2),
SDLK_SEPARATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SEPARATOR),
SDLK_OUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OUT),
SDLK_OPER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OPER),
SDLK_CLEARAGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEARAGAIN),
SDLK_CRSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CRSEL),
SDLK_EXSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXSEL),
SDLK_KP_00 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_00),
SDLK_KP_000 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_000),
SDLK_THOUSANDSSEPARATOR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_THOUSANDSSEPARATOR),
SDLK_DECIMALSEPARATOR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DECIMALSEPARATOR),
SDLK_CURRENCYUNIT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYUNIT),
SDLK_CURRENCYSUBUNIT =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYSUBUNIT),
SDLK_KP_LEFTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTPAREN),
SDLK_KP_RIGHTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTPAREN),
SDLK_KP_LEFTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTBRACE),
SDLK_KP_RIGHTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTBRACE),
SDLK_KP_TAB = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_TAB),
SDLK_KP_BACKSPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BACKSPACE),
SDLK_KP_A = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_A),
SDLK_KP_B = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_B),
SDLK_KP_C = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_C),
SDLK_KP_D = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_D),
SDLK_KP_E = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_E),
SDLK_KP_F = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_F),
SDLK_KP_XOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_XOR),
SDLK_KP_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_POWER),
SDLK_KP_PERCENT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERCENT),
SDLK_KP_LESS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LESS),
SDLK_KP_GREATER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_GREATER),
SDLK_KP_AMPERSAND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AMPERSAND),
SDLK_KP_DBLAMPERSAND =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLAMPERSAND),
SDLK_KP_VERTICALBAR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_VERTICALBAR),
SDLK_KP_DBLVERTICALBAR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLVERTICALBAR),
SDLK_KP_COLON = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COLON),
SDLK_KP_HASH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HASH),
SDLK_KP_SPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_SPACE),
SDLK_KP_AT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AT),
SDLK_KP_EXCLAM = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EXCLAM),
SDLK_KP_MEMSTORE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSTORE),
SDLK_KP_MEMRECALL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMRECALL),
SDLK_KP_MEMCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMCLEAR),
SDLK_KP_MEMADD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMADD),
SDLK_KP_MEMSUBTRACT =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSUBTRACT),
SDLK_KP_MEMMULTIPLY =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMMULTIPLY),
SDLK_KP_MEMDIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMDIVIDE),
SDLK_KP_PLUSMINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUSMINUS),
SDLK_KP_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEAR),
SDLK_KP_CLEARENTRY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEARENTRY),
SDLK_KP_BINARY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BINARY),
SDLK_KP_OCTAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_OCTAL),
SDLK_KP_DECIMAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DECIMAL),
SDLK_KP_HEXADECIMAL =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HEXADECIMAL),
SDLK_LCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LCTRL),
SDLK_LSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LSHIFT),
SDLK_LALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LALT),
SDLK_LGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LGUI),
SDLK_RCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RCTRL),
SDLK_RSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RSHIFT),
SDLK_RALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RALT),
SDLK_RGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RGUI),
SDLK_MODE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MODE),
SDLK_AUDIONEXT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIONEXT),
SDLK_AUDIOPREV = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPREV),
SDLK_AUDIOSTOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOSTOP),
SDLK_AUDIOPLAY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPLAY),
SDLK_AUDIOMUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOMUTE),
SDLK_MEDIASELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIASELECT),
SDLK_WWW = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_WWW),
SDLK_MAIL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MAIL),
SDLK_CALCULATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CALCULATOR),
SDLK_COMPUTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COMPUTER),
SDLK_AC_SEARCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_SEARCH),
SDLK_AC_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_HOME),
SDLK_AC_BACK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BACK),
SDLK_AC_FORWARD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_FORWARD),
SDLK_AC_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_STOP),
SDLK_AC_REFRESH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_REFRESH),
SDLK_AC_BOOKMARKS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BOOKMARKS),
SDLK_BRIGHTNESSDOWN =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSDOWN),
SDLK_BRIGHTNESSUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSUP),
SDLK_DISPLAYSWITCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DISPLAYSWITCH),
SDLK_KBDILLUMTOGGLE =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMTOGGLE),
SDLK_KBDILLUMDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMDOWN),
SDLK_KBDILLUMUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMUP),
SDLK_EJECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EJECT),
SDLK_SLEEP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SLEEP),
SDLK_APP1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APP1),
SDLK_APP2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APP2),
SDLK_AUDIOREWIND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOREWIND),
SDLK_AUDIOFASTFORWARD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOFASTFORWARD)
};
/**
* \brief Enumeration of valid key mods (possibly OR'd together).
*/
typedef enum
{
KMOD_NONE = 0x0000,
KMOD_LSHIFT = 0x0001,
KMOD_RSHIFT = 0x0002,
KMOD_LCTRL = 0x0040,
KMOD_RCTRL = 0x0080,
KMOD_LALT = 0x0100,
KMOD_RALT = 0x0200,
KMOD_LGUI = 0x0400,
KMOD_RGUI = 0x0800,
KMOD_NUM = 0x1000,
KMOD_CAPS = 0x2000,
KMOD_MODE = 0x4000,
KMOD_RESERVED = 0x8000
} SDL_Keymod;
#define KMOD_CTRL (KMOD_LCTRL|KMOD_RCTRL)
#define KMOD_SHIFT (KMOD_LSHIFT|KMOD_RSHIFT)
#define KMOD_ALT (KMOD_LALT|KMOD_RALT)
#define KMOD_GUI (KMOD_LGUI|KMOD_RGUI)
#endif /* SDL_keycode_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 15,262 | C | 42.608571 | 82 | 0.690473 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_atomic.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_atomic.h
*
* Atomic operations.
*
* IMPORTANT:
* If you are not an expert in concurrent lockless programming, you should
* only be using the atomic lock and reference counting functions in this
* file. In all other cases you should be protecting your data structures
* with full mutexes.
*
* The list of "safe" functions to use are:
* SDL_AtomicLock()
* SDL_AtomicUnlock()
* SDL_AtomicIncRef()
* SDL_AtomicDecRef()
*
* Seriously, here be dragons!
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^
*
* You can find out a little more about lockless programming and the
* subtle issues that can arise here:
* http://msdn.microsoft.com/en-us/library/ee418650%28v=vs.85%29.aspx
*
* There's also lots of good information here:
* http://www.1024cores.net/home/lock-free-algorithms
* http://preshing.com/
*
* These operations may or may not actually be implemented using
* processor specific atomic operations. When possible they are
* implemented as true processor specific atomic operations. When that
* is not possible the are implemented using locks that *do* use the
* available atomic operations.
*
* All of the atomic operations that modify memory are full memory barriers.
*/
#ifndef SDL_atomic_h_
#define SDL_atomic_h_
#include "SDL_stdinc.h"
#include "SDL_platform.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \name SDL AtomicLock
*
* The atomic locks are efficient spinlocks using CPU instructions,
* but are vulnerable to starvation and can spin forever if a thread
* holding a lock has been terminated. For this reason you should
* minimize the code executed inside an atomic lock and never do
* expensive things like API or system calls while holding them.
*
* The atomic locks are not safe to lock recursively.
*
* Porting Note:
* The spin lock functions and type are required and can not be
* emulated because they are used in the atomic emulation code.
*/
/* @{ */
typedef int SDL_SpinLock;
/**
* \brief Try to lock a spin lock by setting it to a non-zero value.
*
* \param lock Points to the lock.
*
* \return SDL_TRUE if the lock succeeded, SDL_FALSE if the lock is already held.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_AtomicTryLock(SDL_SpinLock *lock);
/**
* \brief Lock a spin lock by setting it to a non-zero value.
*
* \param lock Points to the lock.
*/
extern DECLSPEC void SDLCALL SDL_AtomicLock(SDL_SpinLock *lock);
/**
* \brief Unlock a spin lock by setting it to 0. Always returns immediately
*
* \param lock Points to the lock.
*/
extern DECLSPEC void SDLCALL SDL_AtomicUnlock(SDL_SpinLock *lock);
/* @} *//* SDL AtomicLock */
/**
* The compiler barrier prevents the compiler from reordering
* reads and writes to globally visible variables across the call.
*/
#if defined(_MSC_VER) && (_MSC_VER > 1200) && !defined(__clang__)
void _ReadWriteBarrier(void);
#pragma intrinsic(_ReadWriteBarrier)
#define SDL_CompilerBarrier() _ReadWriteBarrier()
#elif (defined(__GNUC__) && !defined(__EMSCRIPTEN__)) || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x5120))
/* This is correct for all CPUs when using GCC or Solaris Studio 12.1+. */
#define SDL_CompilerBarrier() __asm__ __volatile__ ("" : : : "memory")
#elif defined(__WATCOMC__)
extern _inline void SDL_CompilerBarrier (void);
#pragma aux SDL_CompilerBarrier = "" parm [] modify exact [];
#else
#define SDL_CompilerBarrier() \
{ SDL_SpinLock _tmp = 0; SDL_AtomicLock(&_tmp); SDL_AtomicUnlock(&_tmp); }
#endif
/**
* Memory barriers are designed to prevent reads and writes from being
* reordered by the compiler and being seen out of order on multi-core CPUs.
*
* A typical pattern would be for thread A to write some data and a flag,
* and for thread B to read the flag and get the data. In this case you
* would insert a release barrier between writing the data and the flag,
* guaranteeing that the data write completes no later than the flag is
* written, and you would insert an acquire barrier between reading the
* flag and reading the data, to ensure that all the reads associated
* with the flag have completed.
*
* In this pattern you should always see a release barrier paired with
* an acquire barrier and you should gate the data reads/writes with a
* single flag variable.
*
* For more information on these semantics, take a look at the blog post:
* http://preshing.com/20120913/acquire-and-release-semantics
*/
extern DECLSPEC void SDLCALL SDL_MemoryBarrierReleaseFunction(void);
extern DECLSPEC void SDLCALL SDL_MemoryBarrierAcquireFunction(void);
#if defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__))
#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("lwsync" : : : "memory")
#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("lwsync" : : : "memory")
#elif defined(__GNUC__) && defined(__aarch64__)
#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("dmb ish" : : : "memory")
#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("dmb ish" : : : "memory")
#elif defined(__GNUC__) && defined(__arm__)
#if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__)
#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("dmb ish" : : : "memory")
#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("dmb ish" : : : "memory")
#elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_5TE__)
#ifdef __thumb__
/* The mcr instruction isn't available in thumb mode, use real functions */
#define SDL_MemoryBarrierRelease() SDL_MemoryBarrierReleaseFunction()
#define SDL_MemoryBarrierAcquire() SDL_MemoryBarrierAcquireFunction()
#else
#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory")
#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory")
#endif /* __thumb__ */
#else
#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("" : : : "memory")
#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("" : : : "memory")
#endif /* __GNUC__ && __arm__ */
#else
#if (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x5120))
/* This is correct for all CPUs on Solaris when using Solaris Studio 12.1+. */
#include <mbarrier.h>
#define SDL_MemoryBarrierRelease() __machine_rel_barrier()
#define SDL_MemoryBarrierAcquire() __machine_acq_barrier()
#else
/* This is correct for the x86 and x64 CPUs, and we'll expand this over time. */
#define SDL_MemoryBarrierRelease() SDL_CompilerBarrier()
#define SDL_MemoryBarrierAcquire() SDL_CompilerBarrier()
#endif
#endif
/**
* \brief A type representing an atomic integer value. It is a struct
* so people don't accidentally use numeric operations on it.
*/
typedef struct { int value; } SDL_atomic_t;
/**
* \brief Set an atomic variable to a new value if it is currently an old value.
*
* \return SDL_TRUE if the atomic variable was set, SDL_FALSE otherwise.
*
* \note If you don't know what this function is for, you shouldn't use it!
*/
extern DECLSPEC SDL_bool SDLCALL SDL_AtomicCAS(SDL_atomic_t *a, int oldval, int newval);
/**
* \brief Set an atomic variable to a value.
*
* \return The previous value of the atomic variable.
*/
extern DECLSPEC int SDLCALL SDL_AtomicSet(SDL_atomic_t *a, int v);
/**
* \brief Get the value of an atomic variable
*/
extern DECLSPEC int SDLCALL SDL_AtomicGet(SDL_atomic_t *a);
/**
* \brief Add to an atomic variable.
*
* \return The previous value of the atomic variable.
*
* \note This same style can be used for any number operation
*/
extern DECLSPEC int SDLCALL SDL_AtomicAdd(SDL_atomic_t *a, int v);
/**
* \brief Increment an atomic variable used as a reference count.
*/
#ifndef SDL_AtomicIncRef
#define SDL_AtomicIncRef(a) SDL_AtomicAdd(a, 1)
#endif
/**
* \brief Decrement an atomic variable used as a reference count.
*
* \return SDL_TRUE if the variable reached zero after decrementing,
* SDL_FALSE otherwise
*/
#ifndef SDL_AtomicDecRef
#define SDL_AtomicDecRef(a) (SDL_AtomicAdd(a, -1) == 1)
#endif
/**
* \brief Set a pointer to a new value if it is currently an old value.
*
* \return SDL_TRUE if the pointer was set, SDL_FALSE otherwise.
*
* \note If you don't know what this function is for, you shouldn't use it!
*/
extern DECLSPEC SDL_bool SDLCALL SDL_AtomicCASPtr(void **a, void *oldval, void *newval);
/**
* \brief Set a pointer to a value atomically.
*
* \return The previous value of the pointer.
*/
extern DECLSPEC void* SDLCALL SDL_AtomicSetPtr(void **a, void* v);
/**
* \brief Get the value of a pointer atomically.
*/
extern DECLSPEC void* SDLCALL SDL_AtomicGetPtr(void **a);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_atomic_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 10,031 | C | 35.086331 | 200 | 0.700429 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_timer.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_timer_h_
#define SDL_timer_h_
/**
* \file SDL_timer.h
*
* Header for the SDL time management routines.
*/
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Get the number of milliseconds since the SDL library initialization.
*
* \note This value wraps if the program runs for more than ~49 days.
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetTicks(void);
/**
* \brief Compare SDL ticks values, and return true if A has passed B
*
* e.g. if you want to wait 100 ms, you could do this:
* Uint32 timeout = SDL_GetTicks() + 100;
* while (!SDL_TICKS_PASSED(SDL_GetTicks(), timeout)) {
* ... do work until timeout has elapsed
* }
*/
#define SDL_TICKS_PASSED(A, B) ((Sint32)((B) - (A)) <= 0)
/**
* \brief Get the current value of the high resolution counter
*/
extern DECLSPEC Uint64 SDLCALL SDL_GetPerformanceCounter(void);
/**
* \brief Get the count per second of the high resolution counter
*/
extern DECLSPEC Uint64 SDLCALL SDL_GetPerformanceFrequency(void);
/**
* \brief Wait a specified number of milliseconds before returning.
*/
extern DECLSPEC void SDLCALL SDL_Delay(Uint32 ms);
/**
* Function prototype for the timer callback function.
*
* The callback function is passed the current timer interval and returns
* the next timer interval. If the returned value is the same as the one
* passed in, the periodic alarm continues, otherwise a new alarm is
* scheduled. If the callback returns 0, the periodic alarm is cancelled.
*/
typedef Uint32 (SDLCALL * SDL_TimerCallback) (Uint32 interval, void *param);
/**
* Definition of the timer ID type.
*/
typedef int SDL_TimerID;
/**
* \brief Add a new timer to the pool of timers already running.
*
* \return A timer ID, or 0 when an error occurs.
*/
extern DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval,
SDL_TimerCallback callback,
void *param);
/**
* \brief Remove a timer knowing its ID.
*
* \return A boolean value indicating success or failure.
*
* \warning It is not safe to remove a timer multiple times.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_RemoveTimer(SDL_TimerID id);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_timer_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 3,454 | C | 28.784483 | 78 | 0.69861 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_opengles2_gl2.h | #ifndef __gl2_h_
#define __gl2_h_
/* $Revision: 20555 $ on $Date:: 2013-02-12 14:32:47 -0800 #$ */
/*#include <GLES2/gl2platform.h>*/
#ifdef __cplusplus
extern "C" {
#endif
/*
* This document is licensed under the SGI Free Software B License Version
* 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
*/
/*-------------------------------------------------------------------------
* Data type definitions
*-----------------------------------------------------------------------*/
typedef void GLvoid;
typedef char GLchar;
typedef unsigned int GLenum;
typedef unsigned char GLboolean;
typedef unsigned int GLbitfield;
typedef khronos_int8_t GLbyte;
typedef short GLshort;
typedef int GLint;
typedef int GLsizei;
typedef khronos_uint8_t GLubyte;
typedef unsigned short GLushort;
typedef unsigned int GLuint;
typedef khronos_float_t GLfloat;
typedef khronos_float_t GLclampf;
typedef khronos_int32_t GLfixed;
/* GL types for handling large vertex buffer objects */
typedef khronos_intptr_t GLintptr;
typedef khronos_ssize_t GLsizeiptr;
/* OpenGL ES core versions */
#define GL_ES_VERSION_2_0 1
/* ClearBufferMask */
#define GL_DEPTH_BUFFER_BIT 0x00000100
#define GL_STENCIL_BUFFER_BIT 0x00000400
#define GL_COLOR_BUFFER_BIT 0x00004000
/* Boolean */
#define GL_FALSE 0
#define GL_TRUE 1
/* BeginMode */
#define GL_POINTS 0x0000
#define GL_LINES 0x0001
#define GL_LINE_LOOP 0x0002
#define GL_LINE_STRIP 0x0003
#define GL_TRIANGLES 0x0004
#define GL_TRIANGLE_STRIP 0x0005
#define GL_TRIANGLE_FAN 0x0006
/* AlphaFunction (not supported in ES20) */
/* GL_NEVER */
/* GL_LESS */
/* GL_EQUAL */
/* GL_LEQUAL */
/* GL_GREATER */
/* GL_NOTEQUAL */
/* GL_GEQUAL */
/* GL_ALWAYS */
/* BlendingFactorDest */
#define GL_ZERO 0
#define GL_ONE 1
#define GL_SRC_COLOR 0x0300
#define GL_ONE_MINUS_SRC_COLOR 0x0301
#define GL_SRC_ALPHA 0x0302
#define GL_ONE_MINUS_SRC_ALPHA 0x0303
#define GL_DST_ALPHA 0x0304
#define GL_ONE_MINUS_DST_ALPHA 0x0305
/* BlendingFactorSrc */
/* GL_ZERO */
/* GL_ONE */
#define GL_DST_COLOR 0x0306
#define GL_ONE_MINUS_DST_COLOR 0x0307
#define GL_SRC_ALPHA_SATURATE 0x0308
/* GL_SRC_ALPHA */
/* GL_ONE_MINUS_SRC_ALPHA */
/* GL_DST_ALPHA */
/* GL_ONE_MINUS_DST_ALPHA */
/* BlendEquationSeparate */
#define GL_FUNC_ADD 0x8006
#define GL_BLEND_EQUATION 0x8009
#define GL_BLEND_EQUATION_RGB 0x8009 /* same as BLEND_EQUATION */
#define GL_BLEND_EQUATION_ALPHA 0x883D
/* BlendSubtract */
#define GL_FUNC_SUBTRACT 0x800A
#define GL_FUNC_REVERSE_SUBTRACT 0x800B
/* Separate Blend Functions */
#define GL_BLEND_DST_RGB 0x80C8
#define GL_BLEND_SRC_RGB 0x80C9
#define GL_BLEND_DST_ALPHA 0x80CA
#define GL_BLEND_SRC_ALPHA 0x80CB
#define GL_CONSTANT_COLOR 0x8001
#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002
#define GL_CONSTANT_ALPHA 0x8003
#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004
#define GL_BLEND_COLOR 0x8005
/* Buffer Objects */
#define GL_ARRAY_BUFFER 0x8892
#define GL_ELEMENT_ARRAY_BUFFER 0x8893
#define GL_ARRAY_BUFFER_BINDING 0x8894
#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
#define GL_STREAM_DRAW 0x88E0
#define GL_STATIC_DRAW 0x88E4
#define GL_DYNAMIC_DRAW 0x88E8
#define GL_BUFFER_SIZE 0x8764
#define GL_BUFFER_USAGE 0x8765
#define GL_CURRENT_VERTEX_ATTRIB 0x8626
/* CullFaceMode */
#define GL_FRONT 0x0404
#define GL_BACK 0x0405
#define GL_FRONT_AND_BACK 0x0408
/* DepthFunction */
/* GL_NEVER */
/* GL_LESS */
/* GL_EQUAL */
/* GL_LEQUAL */
/* GL_GREATER */
/* GL_NOTEQUAL */
/* GL_GEQUAL */
/* GL_ALWAYS */
/* EnableCap */
#define GL_TEXTURE_2D 0x0DE1
#define GL_CULL_FACE 0x0B44
#define GL_BLEND 0x0BE2
#define GL_DITHER 0x0BD0
#define GL_STENCIL_TEST 0x0B90
#define GL_DEPTH_TEST 0x0B71
#define GL_SCISSOR_TEST 0x0C11
#define GL_POLYGON_OFFSET_FILL 0x8037
#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E
#define GL_SAMPLE_COVERAGE 0x80A0
/* ErrorCode */
#define GL_NO_ERROR 0
#define GL_INVALID_ENUM 0x0500
#define GL_INVALID_VALUE 0x0501
#define GL_INVALID_OPERATION 0x0502
#define GL_OUT_OF_MEMORY 0x0505
/* FrontFaceDirection */
#define GL_CW 0x0900
#define GL_CCW 0x0901
/* GetPName */
#define GL_LINE_WIDTH 0x0B21
#define GL_ALIASED_POINT_SIZE_RANGE 0x846D
#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E
#define GL_CULL_FACE_MODE 0x0B45
#define GL_FRONT_FACE 0x0B46
#define GL_DEPTH_RANGE 0x0B70
#define GL_DEPTH_WRITEMASK 0x0B72
#define GL_DEPTH_CLEAR_VALUE 0x0B73
#define GL_DEPTH_FUNC 0x0B74
#define GL_STENCIL_CLEAR_VALUE 0x0B91
#define GL_STENCIL_FUNC 0x0B92
#define GL_STENCIL_FAIL 0x0B94
#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95
#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96
#define GL_STENCIL_REF 0x0B97
#define GL_STENCIL_VALUE_MASK 0x0B93
#define GL_STENCIL_WRITEMASK 0x0B98
#define GL_STENCIL_BACK_FUNC 0x8800
#define GL_STENCIL_BACK_FAIL 0x8801
#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802
#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803
#define GL_STENCIL_BACK_REF 0x8CA3
#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4
#define GL_STENCIL_BACK_WRITEMASK 0x8CA5
#define GL_VIEWPORT 0x0BA2
#define GL_SCISSOR_BOX 0x0C10
/* GL_SCISSOR_TEST */
#define GL_COLOR_CLEAR_VALUE 0x0C22
#define GL_COLOR_WRITEMASK 0x0C23
#define GL_UNPACK_ALIGNMENT 0x0CF5
#define GL_PACK_ALIGNMENT 0x0D05
#define GL_MAX_TEXTURE_SIZE 0x0D33
#define GL_MAX_VIEWPORT_DIMS 0x0D3A
#define GL_SUBPIXEL_BITS 0x0D50
#define GL_RED_BITS 0x0D52
#define GL_GREEN_BITS 0x0D53
#define GL_BLUE_BITS 0x0D54
#define GL_ALPHA_BITS 0x0D55
#define GL_DEPTH_BITS 0x0D56
#define GL_STENCIL_BITS 0x0D57
#define GL_POLYGON_OFFSET_UNITS 0x2A00
/* GL_POLYGON_OFFSET_FILL */
#define GL_POLYGON_OFFSET_FACTOR 0x8038
#define GL_TEXTURE_BINDING_2D 0x8069
#define GL_SAMPLE_BUFFERS 0x80A8
#define GL_SAMPLES 0x80A9
#define GL_SAMPLE_COVERAGE_VALUE 0x80AA
#define GL_SAMPLE_COVERAGE_INVERT 0x80AB
/* GetTextureParameter */
/* GL_TEXTURE_MAG_FILTER */
/* GL_TEXTURE_MIN_FILTER */
/* GL_TEXTURE_WRAP_S */
/* GL_TEXTURE_WRAP_T */
#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3
/* HintMode */
#define GL_DONT_CARE 0x1100
#define GL_FASTEST 0x1101
#define GL_NICEST 0x1102
/* HintTarget */
#define GL_GENERATE_MIPMAP_HINT 0x8192
/* DataType */
#define GL_BYTE 0x1400
#define GL_UNSIGNED_BYTE 0x1401
#define GL_SHORT 0x1402
#define GL_UNSIGNED_SHORT 0x1403
#define GL_INT 0x1404
#define GL_UNSIGNED_INT 0x1405
#define GL_FLOAT 0x1406
#define GL_FIXED 0x140C
/* PixelFormat */
#define GL_DEPTH_COMPONENT 0x1902
#define GL_ALPHA 0x1906
#define GL_RGB 0x1907
#define GL_RGBA 0x1908
#define GL_LUMINANCE 0x1909
#define GL_LUMINANCE_ALPHA 0x190A
/* PixelType */
/* GL_UNSIGNED_BYTE */
#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033
#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034
#define GL_UNSIGNED_SHORT_5_6_5 0x8363
/* Shaders */
#define GL_FRAGMENT_SHADER 0x8B30
#define GL_VERTEX_SHADER 0x8B31
#define GL_MAX_VERTEX_ATTRIBS 0x8869
#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB
#define GL_MAX_VARYING_VECTORS 0x8DFC
#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C
#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872
#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD
#define GL_SHADER_TYPE 0x8B4F
#define GL_DELETE_STATUS 0x8B80
#define GL_LINK_STATUS 0x8B82
#define GL_VALIDATE_STATUS 0x8B83
#define GL_ATTACHED_SHADERS 0x8B85
#define GL_ACTIVE_UNIFORMS 0x8B86
#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87
#define GL_ACTIVE_ATTRIBUTES 0x8B89
#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A
#define GL_SHADING_LANGUAGE_VERSION 0x8B8C
#define GL_CURRENT_PROGRAM 0x8B8D
/* StencilFunction */
#define GL_NEVER 0x0200
#define GL_LESS 0x0201
#define GL_EQUAL 0x0202
#define GL_LEQUAL 0x0203
#define GL_GREATER 0x0204
#define GL_NOTEQUAL 0x0205
#define GL_GEQUAL 0x0206
#define GL_ALWAYS 0x0207
/* StencilOp */
/* GL_ZERO */
#define GL_KEEP 0x1E00
#define GL_REPLACE 0x1E01
#define GL_INCR 0x1E02
#define GL_DECR 0x1E03
#define GL_INVERT 0x150A
#define GL_INCR_WRAP 0x8507
#define GL_DECR_WRAP 0x8508
/* StringName */
#define GL_VENDOR 0x1F00
#define GL_RENDERER 0x1F01
#define GL_VERSION 0x1F02
#define GL_EXTENSIONS 0x1F03
/* TextureMagFilter */
#define GL_NEAREST 0x2600
#define GL_LINEAR 0x2601
/* TextureMinFilter */
/* GL_NEAREST */
/* GL_LINEAR */
#define GL_NEAREST_MIPMAP_NEAREST 0x2700
#define GL_LINEAR_MIPMAP_NEAREST 0x2701
#define GL_NEAREST_MIPMAP_LINEAR 0x2702
#define GL_LINEAR_MIPMAP_LINEAR 0x2703
/* TextureParameterName */
#define GL_TEXTURE_MAG_FILTER 0x2800
#define GL_TEXTURE_MIN_FILTER 0x2801
#define GL_TEXTURE_WRAP_S 0x2802
#define GL_TEXTURE_WRAP_T 0x2803
/* TextureTarget */
/* GL_TEXTURE_2D */
#define GL_TEXTURE 0x1702
#define GL_TEXTURE_CUBE_MAP 0x8513
#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514
#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
/* TextureUnit */
#define GL_TEXTURE0 0x84C0
#define GL_TEXTURE1 0x84C1
#define GL_TEXTURE2 0x84C2
#define GL_TEXTURE3 0x84C3
#define GL_TEXTURE4 0x84C4
#define GL_TEXTURE5 0x84C5
#define GL_TEXTURE6 0x84C6
#define GL_TEXTURE7 0x84C7
#define GL_TEXTURE8 0x84C8
#define GL_TEXTURE9 0x84C9
#define GL_TEXTURE10 0x84CA
#define GL_TEXTURE11 0x84CB
#define GL_TEXTURE12 0x84CC
#define GL_TEXTURE13 0x84CD
#define GL_TEXTURE14 0x84CE
#define GL_TEXTURE15 0x84CF
#define GL_TEXTURE16 0x84D0
#define GL_TEXTURE17 0x84D1
#define GL_TEXTURE18 0x84D2
#define GL_TEXTURE19 0x84D3
#define GL_TEXTURE20 0x84D4
#define GL_TEXTURE21 0x84D5
#define GL_TEXTURE22 0x84D6
#define GL_TEXTURE23 0x84D7
#define GL_TEXTURE24 0x84D8
#define GL_TEXTURE25 0x84D9
#define GL_TEXTURE26 0x84DA
#define GL_TEXTURE27 0x84DB
#define GL_TEXTURE28 0x84DC
#define GL_TEXTURE29 0x84DD
#define GL_TEXTURE30 0x84DE
#define GL_TEXTURE31 0x84DF
#define GL_ACTIVE_TEXTURE 0x84E0
/* TextureWrapMode */
#define GL_REPEAT 0x2901
#define GL_CLAMP_TO_EDGE 0x812F
#define GL_MIRRORED_REPEAT 0x8370
/* Uniform Types */
#define GL_FLOAT_VEC2 0x8B50
#define GL_FLOAT_VEC3 0x8B51
#define GL_FLOAT_VEC4 0x8B52
#define GL_INT_VEC2 0x8B53
#define GL_INT_VEC3 0x8B54
#define GL_INT_VEC4 0x8B55
#define GL_BOOL 0x8B56
#define GL_BOOL_VEC2 0x8B57
#define GL_BOOL_VEC3 0x8B58
#define GL_BOOL_VEC4 0x8B59
#define GL_FLOAT_MAT2 0x8B5A
#define GL_FLOAT_MAT3 0x8B5B
#define GL_FLOAT_MAT4 0x8B5C
#define GL_SAMPLER_2D 0x8B5E
#define GL_SAMPLER_CUBE 0x8B60
/* Vertex Arrays */
#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
/* Read Format */
#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A
#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B
/* Shader Source */
#define GL_COMPILE_STATUS 0x8B81
#define GL_INFO_LOG_LENGTH 0x8B84
#define GL_SHADER_SOURCE_LENGTH 0x8B88
#define GL_SHADER_COMPILER 0x8DFA
/* Shader Binary */
#define GL_SHADER_BINARY_FORMATS 0x8DF8
#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9
/* Shader Precision-Specified Types */
#define GL_LOW_FLOAT 0x8DF0
#define GL_MEDIUM_FLOAT 0x8DF1
#define GL_HIGH_FLOAT 0x8DF2
#define GL_LOW_INT 0x8DF3
#define GL_MEDIUM_INT 0x8DF4
#define GL_HIGH_INT 0x8DF5
/* Framebuffer Object. */
#define GL_FRAMEBUFFER 0x8D40
#define GL_RENDERBUFFER 0x8D41
#define GL_RGBA4 0x8056
#define GL_RGB5_A1 0x8057
#define GL_RGB565 0x8D62
#define GL_DEPTH_COMPONENT16 0x81A5
#define GL_STENCIL_INDEX8 0x8D48
#define GL_RENDERBUFFER_WIDTH 0x8D42
#define GL_RENDERBUFFER_HEIGHT 0x8D43
#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44
#define GL_RENDERBUFFER_RED_SIZE 0x8D50
#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51
#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52
#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53
#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54
#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55
#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0
#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1
#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2
#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3
#define GL_COLOR_ATTACHMENT0 0x8CE0
#define GL_DEPTH_ATTACHMENT 0x8D00
#define GL_STENCIL_ATTACHMENT 0x8D20
#define GL_NONE 0
#define GL_FRAMEBUFFER_COMPLETE 0x8CD5
#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6
#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9
#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD
#define GL_FRAMEBUFFER_BINDING 0x8CA6
#define GL_RENDERBUFFER_BINDING 0x8CA7
#define GL_MAX_RENDERBUFFER_SIZE 0x84E8
#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506
/*-------------------------------------------------------------------------
* GL core functions.
*-----------------------------------------------------------------------*/
GL_APICALL void GL_APIENTRY glActiveTexture (GLenum texture);
GL_APICALL void GL_APIENTRY glAttachShader (GLuint program, GLuint shader);
GL_APICALL void GL_APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar* name);
GL_APICALL void GL_APIENTRY glBindBuffer (GLenum target, GLuint buffer);
GL_APICALL void GL_APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer);
GL_APICALL void GL_APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer);
GL_APICALL void GL_APIENTRY glBindTexture (GLenum target, GLuint texture);
GL_APICALL void GL_APIENTRY glBlendColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
GL_APICALL void GL_APIENTRY glBlendEquation ( GLenum mode );
GL_APICALL void GL_APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
GL_APICALL void GL_APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor);
GL_APICALL void GL_APIENTRY glBlendFuncSeparate (GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
GL_APICALL void GL_APIENTRY glBufferData (GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage);
GL_APICALL void GL_APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data);
GL_APICALL GLenum GL_APIENTRY glCheckFramebufferStatus (GLenum target);
GL_APICALL void GL_APIENTRY glClear (GLbitfield mask);
GL_APICALL void GL_APIENTRY glClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
GL_APICALL void GL_APIENTRY glClearDepthf (GLclampf depth);
GL_APICALL void GL_APIENTRY glClearStencil (GLint s);
GL_APICALL void GL_APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
GL_APICALL void GL_APIENTRY glCompileShader (GLuint shader);
GL_APICALL void GL_APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data);
GL_APICALL void GL_APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data);
GL_APICALL void GL_APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
GL_APICALL void GL_APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
GL_APICALL GLuint GL_APIENTRY glCreateProgram (void);
GL_APICALL GLuint GL_APIENTRY glCreateShader (GLenum type);
GL_APICALL void GL_APIENTRY glCullFace (GLenum mode);
GL_APICALL void GL_APIENTRY glDeleteBuffers (GLsizei n, const GLuint* buffers);
GL_APICALL void GL_APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint* framebuffers);
GL_APICALL void GL_APIENTRY glDeleteProgram (GLuint program);
GL_APICALL void GL_APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint* renderbuffers);
GL_APICALL void GL_APIENTRY glDeleteShader (GLuint shader);
GL_APICALL void GL_APIENTRY glDeleteTextures (GLsizei n, const GLuint* textures);
GL_APICALL void GL_APIENTRY glDepthFunc (GLenum func);
GL_APICALL void GL_APIENTRY glDepthMask (GLboolean flag);
GL_APICALL void GL_APIENTRY glDepthRangef (GLclampf zNear, GLclampf zFar);
GL_APICALL void GL_APIENTRY glDetachShader (GLuint program, GLuint shader);
GL_APICALL void GL_APIENTRY glDisable (GLenum cap);
GL_APICALL void GL_APIENTRY glDisableVertexAttribArray (GLuint index);
GL_APICALL void GL_APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count);
GL_APICALL void GL_APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const GLvoid* indices);
GL_APICALL void GL_APIENTRY glEnable (GLenum cap);
GL_APICALL void GL_APIENTRY glEnableVertexAttribArray (GLuint index);
GL_APICALL void GL_APIENTRY glFinish (void);
GL_APICALL void GL_APIENTRY glFlush (void);
GL_APICALL void GL_APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
GL_APICALL void GL_APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
GL_APICALL void GL_APIENTRY glFrontFace (GLenum mode);
GL_APICALL void GL_APIENTRY glGenBuffers (GLsizei n, GLuint* buffers);
GL_APICALL void GL_APIENTRY glGenerateMipmap (GLenum target);
GL_APICALL void GL_APIENTRY glGenFramebuffers (GLsizei n, GLuint* framebuffers);
GL_APICALL void GL_APIENTRY glGenRenderbuffers (GLsizei n, GLuint* renderbuffers);
GL_APICALL void GL_APIENTRY glGenTextures (GLsizei n, GLuint* textures);
GL_APICALL void GL_APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, GLchar* name);
GL_APICALL void GL_APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, GLchar* name);
GL_APICALL void GL_APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders);
GL_APICALL GLint GL_APIENTRY glGetAttribLocation (GLuint program, const GLchar* name);
GL_APICALL void GL_APIENTRY glGetBooleanv (GLenum pname, GLboolean* params);
GL_APICALL void GL_APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint* params);
GL_APICALL GLenum GL_APIENTRY glGetError (void);
GL_APICALL void GL_APIENTRY glGetFloatv (GLenum pname, GLfloat* params);
GL_APICALL void GL_APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetIntegerv (GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufsize, GLsizei* length, GLchar* infolog);
GL_APICALL void GL_APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* infolog);
GL_APICALL void GL_APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision);
GL_APICALL void GL_APIENTRY glGetShaderSource (GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* source);
GL_APICALL const GLubyte* GL_APIENTRY glGetString (GLenum name);
GL_APICALL void GL_APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat* params);
GL_APICALL void GL_APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat* params);
GL_APICALL void GL_APIENTRY glGetUniformiv (GLuint program, GLint location, GLint* params);
GL_APICALL GLint GL_APIENTRY glGetUniformLocation (GLuint program, const GLchar* name);
GL_APICALL void GL_APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat* params);
GL_APICALL void GL_APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, GLvoid** pointer);
GL_APICALL void GL_APIENTRY glHint (GLenum target, GLenum mode);
GL_APICALL GLboolean GL_APIENTRY glIsBuffer (GLuint buffer);
GL_APICALL GLboolean GL_APIENTRY glIsEnabled (GLenum cap);
GL_APICALL GLboolean GL_APIENTRY glIsFramebuffer (GLuint framebuffer);
GL_APICALL GLboolean GL_APIENTRY glIsProgram (GLuint program);
GL_APICALL GLboolean GL_APIENTRY glIsRenderbuffer (GLuint renderbuffer);
GL_APICALL GLboolean GL_APIENTRY glIsShader (GLuint shader);
GL_APICALL GLboolean GL_APIENTRY glIsTexture (GLuint texture);
GL_APICALL void GL_APIENTRY glLineWidth (GLfloat width);
GL_APICALL void GL_APIENTRY glLinkProgram (GLuint program);
GL_APICALL void GL_APIENTRY glPixelStorei (GLenum pname, GLint param);
GL_APICALL void GL_APIENTRY glPolygonOffset (GLfloat factor, GLfloat units);
GL_APICALL void GL_APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels);
GL_APICALL void GL_APIENTRY glReleaseShaderCompiler (void);
GL_APICALL void GL_APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
GL_APICALL void GL_APIENTRY glSampleCoverage (GLclampf value, GLboolean invert);
GL_APICALL void GL_APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
GL_APICALL void GL_APIENTRY glShaderBinary (GLsizei n, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length);
GL_APICALL void GL_APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length);
GL_APICALL void GL_APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask);
GL_APICALL void GL_APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask);
GL_APICALL void GL_APIENTRY glStencilMask (GLuint mask);
GL_APICALL void GL_APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask);
GL_APICALL void GL_APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass);
GL_APICALL void GL_APIENTRY glStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
GL_APICALL void GL_APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels);
GL_APICALL void GL_APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param);
GL_APICALL void GL_APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat* params);
GL_APICALL void GL_APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
GL_APICALL void GL_APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint* params);
GL_APICALL void GL_APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels);
GL_APICALL void GL_APIENTRY glUniform1f (GLint location, GLfloat x);
GL_APICALL void GL_APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat* v);
GL_APICALL void GL_APIENTRY glUniform1i (GLint location, GLint x);
GL_APICALL void GL_APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint* v);
GL_APICALL void GL_APIENTRY glUniform2f (GLint location, GLfloat x, GLfloat y);
GL_APICALL void GL_APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat* v);
GL_APICALL void GL_APIENTRY glUniform2i (GLint location, GLint x, GLint y);
GL_APICALL void GL_APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint* v);
GL_APICALL void GL_APIENTRY glUniform3f (GLint location, GLfloat x, GLfloat y, GLfloat z);
GL_APICALL void GL_APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat* v);
GL_APICALL void GL_APIENTRY glUniform3i (GLint location, GLint x, GLint y, GLint z);
GL_APICALL void GL_APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint* v);
GL_APICALL void GL_APIENTRY glUniform4f (GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
GL_APICALL void GL_APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat* v);
GL_APICALL void GL_APIENTRY glUniform4i (GLint location, GLint x, GLint y, GLint z, GLint w);
GL_APICALL void GL_APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint* v);
GL_APICALL void GL_APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
GL_APICALL void GL_APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
GL_APICALL void GL_APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
GL_APICALL void GL_APIENTRY glUseProgram (GLuint program);
GL_APICALL void GL_APIENTRY glValidateProgram (GLuint program);
GL_APICALL void GL_APIENTRY glVertexAttrib1f (GLuint indx, GLfloat x);
GL_APICALL void GL_APIENTRY glVertexAttrib1fv (GLuint indx, const GLfloat* values);
GL_APICALL void GL_APIENTRY glVertexAttrib2f (GLuint indx, GLfloat x, GLfloat y);
GL_APICALL void GL_APIENTRY glVertexAttrib2fv (GLuint indx, const GLfloat* values);
GL_APICALL void GL_APIENTRY glVertexAttrib3f (GLuint indx, GLfloat x, GLfloat y, GLfloat z);
GL_APICALL void GL_APIENTRY glVertexAttrib3fv (GLuint indx, const GLfloat* values);
GL_APICALL void GL_APIENTRY glVertexAttrib4f (GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
GL_APICALL void GL_APIENTRY glVertexAttrib4fv (GLuint indx, const GLfloat* values);
GL_APICALL void GL_APIENTRY glVertexAttribPointer (GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* ptr);
GL_APICALL void GL_APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
#ifdef __cplusplus
}
#endif
#endif /* __gl2_h_ */
| 31,876 | C | 50.249196 | 206 | 0.631133 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_keyboard.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_keyboard.h
*
* Include file for SDL keyboard event handling
*/
#ifndef SDL_keyboard_h_
#define SDL_keyboard_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_keycode.h"
#include "SDL_video.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief The SDL keysym structure, used in key events.
*
* \note If you are looking for translated character input, see the ::SDL_TEXTINPUT event.
*/
typedef struct SDL_Keysym
{
SDL_Scancode scancode; /**< SDL physical key code - see ::SDL_Scancode for details */
SDL_Keycode sym; /**< SDL virtual key code - see ::SDL_Keycode for details */
Uint16 mod; /**< current key modifiers */
Uint32 unused;
} SDL_Keysym;
/* Function prototypes */
/**
* \brief Get the window which currently has keyboard focus.
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_GetKeyboardFocus(void);
/**
* \brief Get a snapshot of the current state of the keyboard.
*
* \param numkeys if non-NULL, receives the length of the returned array.
*
* \return An array of key states. Indexes into this array are obtained by using ::SDL_Scancode values.
*
* \b Example:
* \code
* const Uint8 *state = SDL_GetKeyboardState(NULL);
* if ( state[SDL_SCANCODE_RETURN] ) {
* printf("<RETURN> is pressed.\n");
* }
* \endcode
*/
extern DECLSPEC const Uint8 *SDLCALL SDL_GetKeyboardState(int *numkeys);
/**
* \brief Get the current key modifier state for the keyboard.
*/
extern DECLSPEC SDL_Keymod SDLCALL SDL_GetModState(void);
/**
* \brief Set the current key modifier state for the keyboard.
*
* \note This does not change the keyboard state, only the key modifier flags.
*/
extern DECLSPEC void SDLCALL SDL_SetModState(SDL_Keymod modstate);
/**
* \brief Get the key code corresponding to the given scancode according
* to the current keyboard layout.
*
* See ::SDL_Keycode for details.
*
* \sa SDL_GetKeyName()
*/
extern DECLSPEC SDL_Keycode SDLCALL SDL_GetKeyFromScancode(SDL_Scancode scancode);
/**
* \brief Get the scancode corresponding to the given key code according to the
* current keyboard layout.
*
* See ::SDL_Scancode for details.
*
* \sa SDL_GetScancodeName()
*/
extern DECLSPEC SDL_Scancode SDLCALL SDL_GetScancodeFromKey(SDL_Keycode key);
/**
* \brief Get a human-readable name for a scancode.
*
* \return A pointer to the name for the scancode.
* If the scancode doesn't have a name, this function returns
* an empty string ("").
*
* \sa SDL_Scancode
*/
extern DECLSPEC const char *SDLCALL SDL_GetScancodeName(SDL_Scancode scancode);
/**
* \brief Get a scancode from a human-readable name
*
* \return scancode, or SDL_SCANCODE_UNKNOWN if the name wasn't recognized
*
* \sa SDL_Scancode
*/
extern DECLSPEC SDL_Scancode SDLCALL SDL_GetScancodeFromName(const char *name);
/**
* \brief Get a human-readable name for a key.
*
* \return A pointer to a UTF-8 string that stays valid at least until the next
* call to this function. If you need it around any longer, you must
* copy it. If the key doesn't have a name, this function returns an
* empty string ("").
*
* \sa SDL_Keycode
*/
extern DECLSPEC const char *SDLCALL SDL_GetKeyName(SDL_Keycode key);
/**
* \brief Get a key code from a human-readable name
*
* \return key code, or SDLK_UNKNOWN if the name wasn't recognized
*
* \sa SDL_Keycode
*/
extern DECLSPEC SDL_Keycode SDLCALL SDL_GetKeyFromName(const char *name);
/**
* \brief Start accepting Unicode text input events.
* This function will show the on-screen keyboard if supported.
*
* \sa SDL_StopTextInput()
* \sa SDL_SetTextInputRect()
* \sa SDL_HasScreenKeyboardSupport()
*/
extern DECLSPEC void SDLCALL SDL_StartTextInput(void);
/**
* \brief Return whether or not Unicode text input events are enabled.
*
* \sa SDL_StartTextInput()
* \sa SDL_StopTextInput()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsTextInputActive(void);
/**
* \brief Stop receiving any text input events.
* This function will hide the on-screen keyboard if supported.
*
* \sa SDL_StartTextInput()
* \sa SDL_HasScreenKeyboardSupport()
*/
extern DECLSPEC void SDLCALL SDL_StopTextInput(void);
/**
* \brief Set the rectangle used to type Unicode text inputs.
* This is used as a hint for IME and on-screen keyboard placement.
*
* \sa SDL_StartTextInput()
*/
extern DECLSPEC void SDLCALL SDL_SetTextInputRect(SDL_Rect *rect);
/**
* \brief Returns whether the platform has some screen keyboard support.
*
* \return SDL_TRUE if some keyboard support is available else SDL_FALSE.
*
* \note Not all screen keyboard functions are supported on all platforms.
*
* \sa SDL_IsScreenKeyboardShown()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasScreenKeyboardSupport(void);
/**
* \brief Returns whether the screen keyboard is shown for given window.
*
* \param window The window for which screen keyboard should be queried.
*
* \return SDL_TRUE if screen keyboard is shown else SDL_FALSE.
*
* \sa SDL_HasScreenKeyboardSupport()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsScreenKeyboardShown(SDL_Window *window);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_keyboard_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 6,437 | C | 28.53211 | 104 | 0.701569 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_test_compare.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_test_compare.h
*
* Include file for SDL test framework.
*
* This code is a part of the SDL2_test library, not the main SDL library.
*/
/*
Defines comparison functions (i.e. for surfaces).
*/
#ifndef SDL_test_compare_h_
#define SDL_test_compare_h_
#include "SDL.h"
#include "SDL_test_images.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Compares a surface and with reference image data for equality
*
* \param surface Surface used in comparison
* \param referenceSurface Test Surface used in comparison
* \param allowable_error Allowable difference (=sum of squared difference for each RGB component) in blending accuracy.
*
* \returns 0 if comparison succeeded, >0 (=number of pixels for which the comparison failed) if comparison failed, -1 if any of the surfaces were NULL, -2 if the surface sizes differ.
*/
int SDLTest_CompareSurfaces(SDL_Surface *surface, SDL_Surface *referenceSurface, int allowable_error);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_test_compare_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 2,163 | C | 29.914285 | 184 | 0.736477 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_assert.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_assert_h_
#define SDL_assert_h_
#include "SDL_config.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef SDL_ASSERT_LEVEL
#ifdef SDL_DEFAULT_ASSERT_LEVEL
#define SDL_ASSERT_LEVEL SDL_DEFAULT_ASSERT_LEVEL
#elif defined(_DEBUG) || defined(DEBUG) || \
(defined(__GNUC__) && !defined(__OPTIMIZE__))
#define SDL_ASSERT_LEVEL 2
#else
#define SDL_ASSERT_LEVEL 1
#endif
#endif /* SDL_ASSERT_LEVEL */
/*
These are macros and not first class functions so that the debugger breaks
on the assertion line and not in some random guts of SDL, and so each
assert can have unique static variables associated with it.
*/
#if defined(_MSC_VER)
/* Don't include intrin.h here because it contains C++ code */
extern void __cdecl __debugbreak(void);
#define SDL_TriggerBreakpoint() __debugbreak()
#elif ( (!defined(__NACL__)) && ((defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))) )
#define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "int $3\n\t" )
#elif defined(__386__) && defined(__WATCOMC__)
#define SDL_TriggerBreakpoint() { _asm { int 0x03 } }
#elif defined(HAVE_SIGNAL_H) && !defined(__WATCOMC__)
#include <signal.h>
#define SDL_TriggerBreakpoint() raise(SIGTRAP)
#else
/* How do we trigger breakpoints on this platform? */
#define SDL_TriggerBreakpoint()
#endif
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 supports __func__ as a standard. */
# define SDL_FUNCTION __func__
#elif ((__GNUC__ >= 2) || defined(_MSC_VER) || defined (__WATCOMC__))
# define SDL_FUNCTION __FUNCTION__
#else
# define SDL_FUNCTION "???"
#endif
#define SDL_FILE __FILE__
#define SDL_LINE __LINE__
/*
sizeof (x) makes the compiler still parse the expression even without
assertions enabled, so the code is always checked at compile time, but
doesn't actually generate code for it, so there are no side effects or
expensive checks at run time, just the constant size of what x WOULD be,
which presumably gets optimized out as unused.
This also solves the problem of...
int somevalue = blah();
SDL_assert(somevalue == 1);
...which would cause compiles to complain that somevalue is unused if we
disable assertions.
*/
/* "while (0,0)" fools Microsoft's compiler's /W4 warning level into thinking
this condition isn't constant. And looks like an owl's face! */
#ifdef _MSC_VER /* stupid /W4 warnings. */
#define SDL_NULL_WHILE_LOOP_CONDITION (0,0)
#else
#define SDL_NULL_WHILE_LOOP_CONDITION (0)
#endif
#define SDL_disabled_assert(condition) \
do { (void) sizeof ((condition)); } while (SDL_NULL_WHILE_LOOP_CONDITION)
typedef enum
{
SDL_ASSERTION_RETRY, /**< Retry the assert immediately. */
SDL_ASSERTION_BREAK, /**< Make the debugger trigger a breakpoint. */
SDL_ASSERTION_ABORT, /**< Terminate the program. */
SDL_ASSERTION_IGNORE, /**< Ignore the assert. */
SDL_ASSERTION_ALWAYS_IGNORE /**< Ignore the assert from now on. */
} SDL_AssertState;
typedef struct SDL_AssertData
{
int always_ignore;
unsigned int trigger_count;
const char *condition;
const char *filename;
int linenum;
const char *function;
const struct SDL_AssertData *next;
} SDL_AssertData;
#if (SDL_ASSERT_LEVEL > 0)
/* Never call this directly. Use the SDL_assert* macros. */
extern DECLSPEC SDL_AssertState SDLCALL SDL_ReportAssertion(SDL_AssertData *,
const char *,
const char *, int)
#if defined(__clang__)
#if __has_feature(attribute_analyzer_noreturn)
/* this tells Clang's static analysis that we're a custom assert function,
and that the analyzer should assume the condition was always true past this
SDL_assert test. */
__attribute__((analyzer_noreturn))
#endif
#endif
;
/* the do {} while(0) avoids dangling else problems:
if (x) SDL_assert(y); else blah();
... without the do/while, the "else" could attach to this macro's "if".
We try to handle just the minimum we need here in a macro...the loop,
the static vars, and break points. The heavy lifting is handled in
SDL_ReportAssertion(), in SDL_assert.c.
*/
#define SDL_enabled_assert(condition) \
do { \
while ( !(condition) ) { \
static struct SDL_AssertData sdl_assert_data = { \
0, 0, #condition, 0, 0, 0, 0 \
}; \
const SDL_AssertState sdl_assert_state = SDL_ReportAssertion(&sdl_assert_data, SDL_FUNCTION, SDL_FILE, SDL_LINE); \
if (sdl_assert_state == SDL_ASSERTION_RETRY) { \
continue; /* go again. */ \
} else if (sdl_assert_state == SDL_ASSERTION_BREAK) { \
SDL_TriggerBreakpoint(); \
} \
break; /* not retrying. */ \
} \
} while (SDL_NULL_WHILE_LOOP_CONDITION)
#endif /* enabled assertions support code */
/* Enable various levels of assertions. */
#if SDL_ASSERT_LEVEL == 0 /* assertions disabled */
# define SDL_assert(condition) SDL_disabled_assert(condition)
# define SDL_assert_release(condition) SDL_disabled_assert(condition)
# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition)
#elif SDL_ASSERT_LEVEL == 1 /* release settings. */
# define SDL_assert(condition) SDL_disabled_assert(condition)
# define SDL_assert_release(condition) SDL_enabled_assert(condition)
# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition)
#elif SDL_ASSERT_LEVEL == 2 /* normal settings. */
# define SDL_assert(condition) SDL_enabled_assert(condition)
# define SDL_assert_release(condition) SDL_enabled_assert(condition)
# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition)
#elif SDL_ASSERT_LEVEL == 3 /* paranoid settings. */
# define SDL_assert(condition) SDL_enabled_assert(condition)
# define SDL_assert_release(condition) SDL_enabled_assert(condition)
# define SDL_assert_paranoid(condition) SDL_enabled_assert(condition)
#else
# error Unknown assertion level.
#endif
/* this assertion is never disabled at any level. */
#define SDL_assert_always(condition) SDL_enabled_assert(condition)
typedef SDL_AssertState (SDLCALL *SDL_AssertionHandler)(
const SDL_AssertData* data, void* userdata);
/**
* \brief Set an application-defined assertion handler.
*
* This allows an app to show its own assertion UI and/or force the
* response to an assertion failure. If the app doesn't provide this, SDL
* will try to do the right thing, popping up a system-specific GUI dialog,
* and probably minimizing any fullscreen windows.
*
* This callback may fire from any thread, but it runs wrapped in a mutex, so
* it will only fire from one thread at a time.
*
* Setting the callback to NULL restores SDL's original internal handler.
*
* This callback is NOT reset to SDL's internal handler upon SDL_Quit()!
*
* Return SDL_AssertState value of how to handle the assertion failure.
*
* \param handler Callback function, called when an assertion fails.
* \param userdata A pointer passed to the callback as-is.
*/
extern DECLSPEC void SDLCALL SDL_SetAssertionHandler(
SDL_AssertionHandler handler,
void *userdata);
/**
* \brief Get the default assertion handler.
*
* This returns the function pointer that is called by default when an
* assertion is triggered. This is an internal function provided by SDL,
* that is used for assertions when SDL_SetAssertionHandler() hasn't been
* used to provide a different function.
*
* \return The default SDL_AssertionHandler that is called when an assert triggers.
*/
extern DECLSPEC SDL_AssertionHandler SDLCALL SDL_GetDefaultAssertionHandler(void);
/**
* \brief Get the current assertion handler.
*
* This returns the function pointer that is called when an assertion is
* triggered. This is either the value last passed to
* SDL_SetAssertionHandler(), or if no application-specified function is
* set, is equivalent to calling SDL_GetDefaultAssertionHandler().
*
* \param puserdata Pointer to a void*, which will store the "userdata"
* pointer that was passed to SDL_SetAssertionHandler().
* This value will always be NULL for the default handler.
* If you don't care about this data, it is safe to pass
* a NULL pointer to this function to ignore it.
* \return The SDL_AssertionHandler that is called when an assert triggers.
*/
extern DECLSPEC SDL_AssertionHandler SDLCALL SDL_GetAssertionHandler(void **puserdata);
/**
* \brief Get a list of all assertion failures.
*
* Get all assertions triggered since last call to SDL_ResetAssertionReport(),
* or the start of the program.
*
* The proper way to examine this data looks something like this:
*
* <code>
* const SDL_AssertData *item = SDL_GetAssertionReport();
* while (item) {
* printf("'%s', %s (%s:%d), triggered %u times, always ignore: %s.\\n",
* item->condition, item->function, item->filename,
* item->linenum, item->trigger_count,
* item->always_ignore ? "yes" : "no");
* item = item->next;
* }
* </code>
*
* \return List of all assertions.
* \sa SDL_ResetAssertionReport
*/
extern DECLSPEC const SDL_AssertData * SDLCALL SDL_GetAssertionReport(void);
/**
* \brief Reset the list of all assertion failures.
*
* Reset list of all assertions triggered.
*
* \sa SDL_GetAssertionReport
*/
extern DECLSPEC void SDLCALL SDL_ResetAssertionReport(void);
/* these had wrong naming conventions until 2.0.4. Please update your app! */
#define SDL_assert_state SDL_AssertState
#define SDL_assert_data SDL_AssertData
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_assert_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 11,045 | C | 36.828767 | 127 | 0.680489 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_clipboard.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_clipboard.h
*
* Include file for SDL clipboard handling
*/
#ifndef SDL_clipboard_h_
#define SDL_clipboard_h_
#include "SDL_stdinc.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* Function prototypes */
/**
* \brief Put UTF-8 text into the clipboard
*
* \sa SDL_GetClipboardText()
*/
extern DECLSPEC int SDLCALL SDL_SetClipboardText(const char *text);
/**
* \brief Get UTF-8 text from the clipboard, which must be freed with SDL_free()
*
* \sa SDL_SetClipboardText()
*/
extern DECLSPEC char * SDLCALL SDL_GetClipboardText(void);
/**
* \brief Returns a flag indicating whether the clipboard exists and contains a text string that is non-empty
*
* \sa SDL_GetClipboardText()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasClipboardText(void);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_clipboard_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 1,966 | C | 26.319444 | 109 | 0.728891 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_error.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_error.h
*
* Simple error message routines for SDL.
*/
#ifndef SDL_error_h_
#define SDL_error_h_
#include "SDL_stdinc.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* Public functions */
/* SDL_SetError() unconditionally returns -1. */
extern DECLSPEC int SDLCALL SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1);
extern DECLSPEC const char *SDLCALL SDL_GetError(void);
extern DECLSPEC void SDLCALL SDL_ClearError(void);
/**
* \name Internal error functions
*
* \internal
* Private error reporting function - used internally.
*/
/* @{ */
#define SDL_OutOfMemory() SDL_Error(SDL_ENOMEM)
#define SDL_Unsupported() SDL_Error(SDL_UNSUPPORTED)
#define SDL_InvalidParamError(param) SDL_SetError("Parameter '%s' is invalid", (param))
typedef enum
{
SDL_ENOMEM,
SDL_EFREAD,
SDL_EFWRITE,
SDL_EFSEEK,
SDL_UNSUPPORTED,
SDL_LASTERROR
} SDL_errorcode;
/* SDL_Error() unconditionally returns -1. */
extern DECLSPEC int SDLCALL SDL_Error(SDL_errorcode code);
/* @} *//* Internal error functions */
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_error_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 2,271 | C | 28.506493 | 114 | 0.719066 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_test.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_test.h
*
* Include file for SDL test framework.
*
* This code is a part of the SDL2_test library, not the main SDL library.
*/
#ifndef SDL_test_h_
#define SDL_test_h_
#include "SDL.h"
#include "SDL_test_assert.h"
#include "SDL_test_common.h"
#include "SDL_test_compare.h"
#include "SDL_test_crc32.h"
#include "SDL_test_font.h"
#include "SDL_test_fuzzer.h"
#include "SDL_test_harness.h"
#include "SDL_test_images.h"
#include "SDL_test_log.h"
#include "SDL_test_md5.h"
#include "SDL_test_memory.h"
#include "SDL_test_random.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* Global definitions */
/*
* Note: Maximum size of SDLTest log message is less than SDL's limit
* to ensure we can fit additional information such as the timestamp.
*/
#define SDLTEST_MAX_LOGMESSAGE_LENGTH 3584
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_test_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 2,000 | C | 27.585714 | 76 | 0.7245 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_video.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_video.h
*
* Header file for SDL video functions.
*/
#ifndef SDL_video_h_
#define SDL_video_h_
#include "SDL_stdinc.h"
#include "SDL_pixels.h"
#include "SDL_rect.h"
#include "SDL_surface.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief The structure that defines a display mode
*
* \sa SDL_GetNumDisplayModes()
* \sa SDL_GetDisplayMode()
* \sa SDL_GetDesktopDisplayMode()
* \sa SDL_GetCurrentDisplayMode()
* \sa SDL_GetClosestDisplayMode()
* \sa SDL_SetWindowDisplayMode()
* \sa SDL_GetWindowDisplayMode()
*/
typedef struct
{
Uint32 format; /**< pixel format */
int w; /**< width, in screen coordinates */
int h; /**< height, in screen coordinates */
int refresh_rate; /**< refresh rate (or zero for unspecified) */
void *driverdata; /**< driver-specific data, initialize to 0 */
} SDL_DisplayMode;
/**
* \brief The type used to identify a window
*
* \sa SDL_CreateWindow()
* \sa SDL_CreateWindowFrom()
* \sa SDL_DestroyWindow()
* \sa SDL_GetWindowData()
* \sa SDL_GetWindowFlags()
* \sa SDL_GetWindowGrab()
* \sa SDL_GetWindowPosition()
* \sa SDL_GetWindowSize()
* \sa SDL_GetWindowTitle()
* \sa SDL_HideWindow()
* \sa SDL_MaximizeWindow()
* \sa SDL_MinimizeWindow()
* \sa SDL_RaiseWindow()
* \sa SDL_RestoreWindow()
* \sa SDL_SetWindowData()
* \sa SDL_SetWindowFullscreen()
* \sa SDL_SetWindowGrab()
* \sa SDL_SetWindowIcon()
* \sa SDL_SetWindowPosition()
* \sa SDL_SetWindowSize()
* \sa SDL_SetWindowBordered()
* \sa SDL_SetWindowResizable()
* \sa SDL_SetWindowTitle()
* \sa SDL_ShowWindow()
*/
typedef struct SDL_Window SDL_Window;
/**
* \brief The flags on a window
*
* \sa SDL_GetWindowFlags()
*/
typedef enum
{
/* !!! FIXME: change this to name = (1<<x). */
SDL_WINDOW_FULLSCREEN = 0x00000001, /**< fullscreen window */
SDL_WINDOW_OPENGL = 0x00000002, /**< window usable with OpenGL context */
SDL_WINDOW_SHOWN = 0x00000004, /**< window is visible */
SDL_WINDOW_HIDDEN = 0x00000008, /**< window is not visible */
SDL_WINDOW_BORDERLESS = 0x00000010, /**< no window decoration */
SDL_WINDOW_RESIZABLE = 0x00000020, /**< window can be resized */
SDL_WINDOW_MINIMIZED = 0x00000040, /**< window is minimized */
SDL_WINDOW_MAXIMIZED = 0x00000080, /**< window is maximized */
SDL_WINDOW_INPUT_GRABBED = 0x00000100, /**< window has grabbed input focus */
SDL_WINDOW_INPUT_FOCUS = 0x00000200, /**< window has input focus */
SDL_WINDOW_MOUSE_FOCUS = 0x00000400, /**< window has mouse focus */
SDL_WINDOW_FULLSCREEN_DESKTOP = ( SDL_WINDOW_FULLSCREEN | 0x00001000 ),
SDL_WINDOW_FOREIGN = 0x00000800, /**< window not created by SDL */
SDL_WINDOW_ALLOW_HIGHDPI = 0x00002000, /**< window should be created in high-DPI mode if supported.
On macOS NSHighResolutionCapable must be set true in the
application's Info.plist for this to have any effect. */
SDL_WINDOW_MOUSE_CAPTURE = 0x00004000, /**< window has mouse captured (unrelated to INPUT_GRABBED) */
SDL_WINDOW_ALWAYS_ON_TOP = 0x00008000, /**< window should always be above others */
SDL_WINDOW_SKIP_TASKBAR = 0x00010000, /**< window should not be added to the taskbar */
SDL_WINDOW_UTILITY = 0x00020000, /**< window should be treated as a utility window */
SDL_WINDOW_TOOLTIP = 0x00040000, /**< window should be treated as a tooltip */
SDL_WINDOW_POPUP_MENU = 0x00080000, /**< window should be treated as a popup menu */
SDL_WINDOW_VULKAN = 0x10000000 /**< window usable for Vulkan surface */
} SDL_WindowFlags;
/**
* \brief Used to indicate that you don't care what the window position is.
*/
#define SDL_WINDOWPOS_UNDEFINED_MASK 0x1FFF0000u
#define SDL_WINDOWPOS_UNDEFINED_DISPLAY(X) (SDL_WINDOWPOS_UNDEFINED_MASK|(X))
#define SDL_WINDOWPOS_UNDEFINED SDL_WINDOWPOS_UNDEFINED_DISPLAY(0)
#define SDL_WINDOWPOS_ISUNDEFINED(X) \
(((X)&0xFFFF0000) == SDL_WINDOWPOS_UNDEFINED_MASK)
/**
* \brief Used to indicate that the window position should be centered.
*/
#define SDL_WINDOWPOS_CENTERED_MASK 0x2FFF0000u
#define SDL_WINDOWPOS_CENTERED_DISPLAY(X) (SDL_WINDOWPOS_CENTERED_MASK|(X))
#define SDL_WINDOWPOS_CENTERED SDL_WINDOWPOS_CENTERED_DISPLAY(0)
#define SDL_WINDOWPOS_ISCENTERED(X) \
(((X)&0xFFFF0000) == SDL_WINDOWPOS_CENTERED_MASK)
/**
* \brief Event subtype for window events
*/
typedef enum
{
SDL_WINDOWEVENT_NONE, /**< Never used */
SDL_WINDOWEVENT_SHOWN, /**< Window has been shown */
SDL_WINDOWEVENT_HIDDEN, /**< Window has been hidden */
SDL_WINDOWEVENT_EXPOSED, /**< Window has been exposed and should be
redrawn */
SDL_WINDOWEVENT_MOVED, /**< Window has been moved to data1, data2
*/
SDL_WINDOWEVENT_RESIZED, /**< Window has been resized to data1xdata2 */
SDL_WINDOWEVENT_SIZE_CHANGED, /**< The window size has changed, either as
a result of an API call or through the
system or user changing the window size. */
SDL_WINDOWEVENT_MINIMIZED, /**< Window has been minimized */
SDL_WINDOWEVENT_MAXIMIZED, /**< Window has been maximized */
SDL_WINDOWEVENT_RESTORED, /**< Window has been restored to normal size
and position */
SDL_WINDOWEVENT_ENTER, /**< Window has gained mouse focus */
SDL_WINDOWEVENT_LEAVE, /**< Window has lost mouse focus */
SDL_WINDOWEVENT_FOCUS_GAINED, /**< Window has gained keyboard focus */
SDL_WINDOWEVENT_FOCUS_LOST, /**< Window has lost keyboard focus */
SDL_WINDOWEVENT_CLOSE, /**< The window manager requests that the window be closed */
SDL_WINDOWEVENT_TAKE_FOCUS, /**< Window is being offered a focus (should SetWindowInputFocus() on itself or a subwindow, or ignore) */
SDL_WINDOWEVENT_HIT_TEST /**< Window had a hit test that wasn't SDL_HITTEST_NORMAL. */
} SDL_WindowEventID;
/**
* \brief An opaque handle to an OpenGL context.
*/
typedef void *SDL_GLContext;
/**
* \brief OpenGL configuration attributes
*/
typedef enum
{
SDL_GL_RED_SIZE,
SDL_GL_GREEN_SIZE,
SDL_GL_BLUE_SIZE,
SDL_GL_ALPHA_SIZE,
SDL_GL_BUFFER_SIZE,
SDL_GL_DOUBLEBUFFER,
SDL_GL_DEPTH_SIZE,
SDL_GL_STENCIL_SIZE,
SDL_GL_ACCUM_RED_SIZE,
SDL_GL_ACCUM_GREEN_SIZE,
SDL_GL_ACCUM_BLUE_SIZE,
SDL_GL_ACCUM_ALPHA_SIZE,
SDL_GL_STEREO,
SDL_GL_MULTISAMPLEBUFFERS,
SDL_GL_MULTISAMPLESAMPLES,
SDL_GL_ACCELERATED_VISUAL,
SDL_GL_RETAINED_BACKING,
SDL_GL_CONTEXT_MAJOR_VERSION,
SDL_GL_CONTEXT_MINOR_VERSION,
SDL_GL_CONTEXT_EGL,
SDL_GL_CONTEXT_FLAGS,
SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_SHARE_WITH_CURRENT_CONTEXT,
SDL_GL_FRAMEBUFFER_SRGB_CAPABLE,
SDL_GL_CONTEXT_RELEASE_BEHAVIOR,
SDL_GL_CONTEXT_RESET_NOTIFICATION,
SDL_GL_CONTEXT_NO_ERROR
} SDL_GLattr;
typedef enum
{
SDL_GL_CONTEXT_PROFILE_CORE = 0x0001,
SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = 0x0002,
SDL_GL_CONTEXT_PROFILE_ES = 0x0004 /**< GLX_CONTEXT_ES2_PROFILE_BIT_EXT */
} SDL_GLprofile;
typedef enum
{
SDL_GL_CONTEXT_DEBUG_FLAG = 0x0001,
SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = 0x0002,
SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = 0x0004,
SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = 0x0008
} SDL_GLcontextFlag;
typedef enum
{
SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE = 0x0000,
SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = 0x0001
} SDL_GLcontextReleaseFlag;
typedef enum
{
SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = 0x0000,
SDL_GL_CONTEXT_RESET_LOSE_CONTEXT = 0x0001
} SDL_GLContextResetNotification;
/* Function prototypes */
/**
* \brief Get the number of video drivers compiled into SDL
*
* \sa SDL_GetVideoDriver()
*/
extern DECLSPEC int SDLCALL SDL_GetNumVideoDrivers(void);
/**
* \brief Get the name of a built in video driver.
*
* \note The video drivers are presented in the order in which they are
* normally checked during initialization.
*
* \sa SDL_GetNumVideoDrivers()
*/
extern DECLSPEC const char *SDLCALL SDL_GetVideoDriver(int index);
/**
* \brief Initialize the video subsystem, optionally specifying a video driver.
*
* \param driver_name Initialize a specific driver by name, or NULL for the
* default video driver.
*
* \return 0 on success, -1 on error
*
* This function initializes the video subsystem; setting up a connection
* to the window manager, etc, and determines the available display modes
* and pixel formats, but does not initialize a window or graphics mode.
*
* \sa SDL_VideoQuit()
*/
extern DECLSPEC int SDLCALL SDL_VideoInit(const char *driver_name);
/**
* \brief Shuts down the video subsystem.
*
* This function closes all windows, and restores the original video mode.
*
* \sa SDL_VideoInit()
*/
extern DECLSPEC void SDLCALL SDL_VideoQuit(void);
/**
* \brief Returns the name of the currently initialized video driver.
*
* \return The name of the current video driver or NULL if no driver
* has been initialized
*
* \sa SDL_GetNumVideoDrivers()
* \sa SDL_GetVideoDriver()
*/
extern DECLSPEC const char *SDLCALL SDL_GetCurrentVideoDriver(void);
/**
* \brief Returns the number of available video displays.
*
* \sa SDL_GetDisplayBounds()
*/
extern DECLSPEC int SDLCALL SDL_GetNumVideoDisplays(void);
/**
* \brief Get the name of a display in UTF-8 encoding
*
* \return The name of a display, or NULL for an invalid display index.
*
* \sa SDL_GetNumVideoDisplays()
*/
extern DECLSPEC const char * SDLCALL SDL_GetDisplayName(int displayIndex);
/**
* \brief Get the desktop area represented by a display, with the primary
* display located at 0,0
*
* \return 0 on success, or -1 if the index is out of range.
*
* \sa SDL_GetNumVideoDisplays()
*/
extern DECLSPEC int SDLCALL SDL_GetDisplayBounds(int displayIndex, SDL_Rect * rect);
/**
* \brief Get the dots/pixels-per-inch for a display
*
* \note Diagonal, horizontal and vertical DPI can all be optionally
* returned if the parameter is non-NULL.
*
* \return 0 on success, or -1 if no DPI information is available or the index is out of range.
*
* \sa SDL_GetNumVideoDisplays()
*/
extern DECLSPEC int SDLCALL SDL_GetDisplayDPI(int displayIndex, float * ddpi, float * hdpi, float * vdpi);
/**
* \brief Get the usable desktop area represented by a display, with the
* primary display located at 0,0
*
* This is the same area as SDL_GetDisplayBounds() reports, but with portions
* reserved by the system removed. For example, on Mac OS X, this subtracts
* the area occupied by the menu bar and dock.
*
* Setting a window to be fullscreen generally bypasses these unusable areas,
* so these are good guidelines for the maximum space available to a
* non-fullscreen window.
*
* \return 0 on success, or -1 if the index is out of range.
*
* \sa SDL_GetDisplayBounds()
* \sa SDL_GetNumVideoDisplays()
*/
extern DECLSPEC int SDLCALL SDL_GetDisplayUsableBounds(int displayIndex, SDL_Rect * rect);
/**
* \brief Returns the number of available display modes.
*
* \sa SDL_GetDisplayMode()
*/
extern DECLSPEC int SDLCALL SDL_GetNumDisplayModes(int displayIndex);
/**
* \brief Fill in information about a specific display mode.
*
* \note The display modes are sorted in this priority:
* \li bits per pixel -> more colors to fewer colors
* \li width -> largest to smallest
* \li height -> largest to smallest
* \li refresh rate -> highest to lowest
*
* \sa SDL_GetNumDisplayModes()
*/
extern DECLSPEC int SDLCALL SDL_GetDisplayMode(int displayIndex, int modeIndex,
SDL_DisplayMode * mode);
/**
* \brief Fill in information about the desktop display mode.
*/
extern DECLSPEC int SDLCALL SDL_GetDesktopDisplayMode(int displayIndex, SDL_DisplayMode * mode);
/**
* \brief Fill in information about the current display mode.
*/
extern DECLSPEC int SDLCALL SDL_GetCurrentDisplayMode(int displayIndex, SDL_DisplayMode * mode);
/**
* \brief Get the closest match to the requested display mode.
*
* \param displayIndex The index of display from which mode should be queried.
* \param mode The desired display mode
* \param closest A pointer to a display mode to be filled in with the closest
* match of the available display modes.
*
* \return The passed in value \c closest, or NULL if no matching video mode
* was available.
*
* The available display modes are scanned, and \c closest is filled in with the
* closest mode matching the requested mode and returned. The mode format and
* refresh_rate default to the desktop mode if they are 0. The modes are
* scanned with size being first priority, format being second priority, and
* finally checking the refresh_rate. If all the available modes are too
* small, then NULL is returned.
*
* \sa SDL_GetNumDisplayModes()
* \sa SDL_GetDisplayMode()
*/
extern DECLSPEC SDL_DisplayMode * SDLCALL SDL_GetClosestDisplayMode(int displayIndex, const SDL_DisplayMode * mode, SDL_DisplayMode * closest);
/**
* \brief Get the display index associated with a window.
*
* \return the display index of the display containing the center of the
* window, or -1 on error.
*/
extern DECLSPEC int SDLCALL SDL_GetWindowDisplayIndex(SDL_Window * window);
/**
* \brief Set the display mode used when a fullscreen window is visible.
*
* By default the window's dimensions and the desktop format and refresh rate
* are used.
*
* \param window The window for which the display mode should be set.
* \param mode The mode to use, or NULL for the default mode.
*
* \return 0 on success, or -1 if setting the display mode failed.
*
* \sa SDL_GetWindowDisplayMode()
* \sa SDL_SetWindowFullscreen()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowDisplayMode(SDL_Window * window,
const SDL_DisplayMode
* mode);
/**
* \brief Fill in information about the display mode used when a fullscreen
* window is visible.
*
* \sa SDL_SetWindowDisplayMode()
* \sa SDL_SetWindowFullscreen()
*/
extern DECLSPEC int SDLCALL SDL_GetWindowDisplayMode(SDL_Window * window,
SDL_DisplayMode * mode);
/**
* \brief Get the pixel format associated with the window.
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetWindowPixelFormat(SDL_Window * window);
/**
* \brief Create a window with the specified position, dimensions, and flags.
*
* \param title The title of the window, in UTF-8 encoding.
* \param x The x position of the window, ::SDL_WINDOWPOS_CENTERED, or
* ::SDL_WINDOWPOS_UNDEFINED.
* \param y The y position of the window, ::SDL_WINDOWPOS_CENTERED, or
* ::SDL_WINDOWPOS_UNDEFINED.
* \param w The width of the window, in screen coordinates.
* \param h The height of the window, in screen coordinates.
* \param flags The flags for the window, a mask of any of the following:
* ::SDL_WINDOW_FULLSCREEN, ::SDL_WINDOW_OPENGL,
* ::SDL_WINDOW_HIDDEN, ::SDL_WINDOW_BORDERLESS,
* ::SDL_WINDOW_RESIZABLE, ::SDL_WINDOW_MAXIMIZED,
* ::SDL_WINDOW_MINIMIZED, ::SDL_WINDOW_INPUT_GRABBED,
* ::SDL_WINDOW_ALLOW_HIGHDPI, ::SDL_WINDOW_VULKAN.
*
* \return The created window, or NULL if window creation failed.
*
* If the window is created with the SDL_WINDOW_ALLOW_HIGHDPI flag, its size
* in pixels may differ from its size in screen coordinates on platforms with
* high-DPI support (e.g. iOS and Mac OS X). Use SDL_GetWindowSize() to query
* the client area's size in screen coordinates, and SDL_GL_GetDrawableSize(),
* SDL_Vulkan_GetDrawableSize(), or SDL_GetRendererOutputSize() to query the
* drawable size in pixels.
*
* If the window is created with any of the SDL_WINDOW_OPENGL or
* SDL_WINDOW_VULKAN flags, then the corresponding LoadLibrary function
* (SDL_GL_LoadLibrary or SDL_Vulkan_LoadLibrary) is called and the
* corresponding UnloadLibrary function is called by SDL_DestroyWindow().
*
* If SDL_WINDOW_VULKAN is specified and there isn't a working Vulkan driver,
* SDL_CreateWindow() will fail because SDL_Vulkan_LoadLibrary() will fail.
*
* \note On non-Apple devices, SDL requires you to either not link to the
* Vulkan loader or link to a dynamic library version. This limitation
* may be removed in a future version of SDL.
*
* \sa SDL_DestroyWindow()
* \sa SDL_GL_LoadLibrary()
* \sa SDL_Vulkan_LoadLibrary()
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_CreateWindow(const char *title,
int x, int y, int w,
int h, Uint32 flags);
/**
* \brief Create an SDL window from an existing native window.
*
* \param data A pointer to driver-dependent window creation data
*
* \return The created window, or NULL if window creation failed.
*
* \sa SDL_DestroyWindow()
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_CreateWindowFrom(const void *data);
/**
* \brief Get the numeric ID of a window, for logging purposes.
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetWindowID(SDL_Window * window);
/**
* \brief Get a window from a stored ID, or NULL if it doesn't exist.
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_GetWindowFromID(Uint32 id);
/**
* \brief Get the window flags.
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetWindowFlags(SDL_Window * window);
/**
* \brief Set the title of a window, in UTF-8 format.
*
* \sa SDL_GetWindowTitle()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowTitle(SDL_Window * window,
const char *title);
/**
* \brief Get the title of a window, in UTF-8 format.
*
* \sa SDL_SetWindowTitle()
*/
extern DECLSPEC const char *SDLCALL SDL_GetWindowTitle(SDL_Window * window);
/**
* \brief Set the icon for a window.
*
* \param window The window for which the icon should be set.
* \param icon The icon for the window.
*/
extern DECLSPEC void SDLCALL SDL_SetWindowIcon(SDL_Window * window,
SDL_Surface * icon);
/**
* \brief Associate an arbitrary named pointer with a window.
*
* \param window The window to associate with the pointer.
* \param name The name of the pointer.
* \param userdata The associated pointer.
*
* \return The previous value associated with 'name'
*
* \note The name is case-sensitive.
*
* \sa SDL_GetWindowData()
*/
extern DECLSPEC void* SDLCALL SDL_SetWindowData(SDL_Window * window,
const char *name,
void *userdata);
/**
* \brief Retrieve the data pointer associated with a window.
*
* \param window The window to query.
* \param name The name of the pointer.
*
* \return The value associated with 'name'
*
* \sa SDL_SetWindowData()
*/
extern DECLSPEC void *SDLCALL SDL_GetWindowData(SDL_Window * window,
const char *name);
/**
* \brief Set the position of a window.
*
* \param window The window to reposition.
* \param x The x coordinate of the window in screen coordinates, or
* ::SDL_WINDOWPOS_CENTERED or ::SDL_WINDOWPOS_UNDEFINED.
* \param y The y coordinate of the window in screen coordinates, or
* ::SDL_WINDOWPOS_CENTERED or ::SDL_WINDOWPOS_UNDEFINED.
*
* \note The window coordinate origin is the upper left of the display.
*
* \sa SDL_GetWindowPosition()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowPosition(SDL_Window * window,
int x, int y);
/**
* \brief Get the position of a window.
*
* \param window The window to query.
* \param x Pointer to variable for storing the x position, in screen
* coordinates. May be NULL.
* \param y Pointer to variable for storing the y position, in screen
* coordinates. May be NULL.
*
* \sa SDL_SetWindowPosition()
*/
extern DECLSPEC void SDLCALL SDL_GetWindowPosition(SDL_Window * window,
int *x, int *y);
/**
* \brief Set the size of a window's client area.
*
* \param window The window to resize.
* \param w The width of the window, in screen coordinates. Must be >0.
* \param h The height of the window, in screen coordinates. Must be >0.
*
* \note Fullscreen windows automatically match the size of the display mode,
* and you should use SDL_SetWindowDisplayMode() to change their size.
*
* The window size in screen coordinates may differ from the size in pixels, if
* the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a platform with
* high-dpi support (e.g. iOS or OS X). Use SDL_GL_GetDrawableSize() or
* SDL_GetRendererOutputSize() to get the real client area size in pixels.
*
* \sa SDL_GetWindowSize()
* \sa SDL_SetWindowDisplayMode()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowSize(SDL_Window * window, int w,
int h);
/**
* \brief Get the size of a window's client area.
*
* \param window The window to query.
* \param w Pointer to variable for storing the width, in screen
* coordinates. May be NULL.
* \param h Pointer to variable for storing the height, in screen
* coordinates. May be NULL.
*
* The window size in screen coordinates may differ from the size in pixels, if
* the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a platform with
* high-dpi support (e.g. iOS or OS X). Use SDL_GL_GetDrawableSize() or
* SDL_GetRendererOutputSize() to get the real client area size in pixels.
*
* \sa SDL_SetWindowSize()
*/
extern DECLSPEC void SDLCALL SDL_GetWindowSize(SDL_Window * window, int *w,
int *h);
/**
* \brief Get the size of a window's borders (decorations) around the client area.
*
* \param window The window to query.
* \param top Pointer to variable for storing the size of the top border. NULL is permitted.
* \param left Pointer to variable for storing the size of the left border. NULL is permitted.
* \param bottom Pointer to variable for storing the size of the bottom border. NULL is permitted.
* \param right Pointer to variable for storing the size of the right border. NULL is permitted.
*
* \return 0 on success, or -1 if getting this information is not supported.
*
* \note if this function fails (returns -1), the size values will be
* initialized to 0, 0, 0, 0 (if a non-NULL pointer is provided), as
* if the window in question was borderless.
*/
extern DECLSPEC int SDLCALL SDL_GetWindowBordersSize(SDL_Window * window,
int *top, int *left,
int *bottom, int *right);
/**
* \brief Set the minimum size of a window's client area.
*
* \param window The window to set a new minimum size.
* \param min_w The minimum width of the window, must be >0
* \param min_h The minimum height of the window, must be >0
*
* \note You can't change the minimum size of a fullscreen window, it
* automatically matches the size of the display mode.
*
* \sa SDL_GetWindowMinimumSize()
* \sa SDL_SetWindowMaximumSize()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowMinimumSize(SDL_Window * window,
int min_w, int min_h);
/**
* \brief Get the minimum size of a window's client area.
*
* \param window The window to query.
* \param w Pointer to variable for storing the minimum width, may be NULL
* \param h Pointer to variable for storing the minimum height, may be NULL
*
* \sa SDL_GetWindowMaximumSize()
* \sa SDL_SetWindowMinimumSize()
*/
extern DECLSPEC void SDLCALL SDL_GetWindowMinimumSize(SDL_Window * window,
int *w, int *h);
/**
* \brief Set the maximum size of a window's client area.
*
* \param window The window to set a new maximum size.
* \param max_w The maximum width of the window, must be >0
* \param max_h The maximum height of the window, must be >0
*
* \note You can't change the maximum size of a fullscreen window, it
* automatically matches the size of the display mode.
*
* \sa SDL_GetWindowMaximumSize()
* \sa SDL_SetWindowMinimumSize()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowMaximumSize(SDL_Window * window,
int max_w, int max_h);
/**
* \brief Get the maximum size of a window's client area.
*
* \param window The window to query.
* \param w Pointer to variable for storing the maximum width, may be NULL
* \param h Pointer to variable for storing the maximum height, may be NULL
*
* \sa SDL_GetWindowMinimumSize()
* \sa SDL_SetWindowMaximumSize()
*/
extern DECLSPEC void SDLCALL SDL_GetWindowMaximumSize(SDL_Window * window,
int *w, int *h);
/**
* \brief Set the border state of a window.
*
* This will add or remove the window's SDL_WINDOW_BORDERLESS flag and
* add or remove the border from the actual window. This is a no-op if the
* window's border already matches the requested state.
*
* \param window The window of which to change the border state.
* \param bordered SDL_FALSE to remove border, SDL_TRUE to add border.
*
* \note You can't change the border state of a fullscreen window.
*
* \sa SDL_GetWindowFlags()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowBordered(SDL_Window * window,
SDL_bool bordered);
/**
* \brief Set the user-resizable state of a window.
*
* This will add or remove the window's SDL_WINDOW_RESIZABLE flag and
* allow/disallow user resizing of the window. This is a no-op if the
* window's resizable state already matches the requested state.
*
* \param window The window of which to change the resizable state.
* \param resizable SDL_TRUE to allow resizing, SDL_FALSE to disallow.
*
* \note You can't change the resizable state of a fullscreen window.
*
* \sa SDL_GetWindowFlags()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowResizable(SDL_Window * window,
SDL_bool resizable);
/**
* \brief Show a window.
*
* \sa SDL_HideWindow()
*/
extern DECLSPEC void SDLCALL SDL_ShowWindow(SDL_Window * window);
/**
* \brief Hide a window.
*
* \sa SDL_ShowWindow()
*/
extern DECLSPEC void SDLCALL SDL_HideWindow(SDL_Window * window);
/**
* \brief Raise a window above other windows and set the input focus.
*/
extern DECLSPEC void SDLCALL SDL_RaiseWindow(SDL_Window * window);
/**
* \brief Make a window as large as possible.
*
* \sa SDL_RestoreWindow()
*/
extern DECLSPEC void SDLCALL SDL_MaximizeWindow(SDL_Window * window);
/**
* \brief Minimize a window to an iconic representation.
*
* \sa SDL_RestoreWindow()
*/
extern DECLSPEC void SDLCALL SDL_MinimizeWindow(SDL_Window * window);
/**
* \brief Restore the size and position of a minimized or maximized window.
*
* \sa SDL_MaximizeWindow()
* \sa SDL_MinimizeWindow()
*/
extern DECLSPEC void SDLCALL SDL_RestoreWindow(SDL_Window * window);
/**
* \brief Set a window's fullscreen state.
*
* \return 0 on success, or -1 if setting the display mode failed.
*
* \sa SDL_SetWindowDisplayMode()
* \sa SDL_GetWindowDisplayMode()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowFullscreen(SDL_Window * window,
Uint32 flags);
/**
* \brief Get the SDL surface associated with the window.
*
* \return The window's framebuffer surface, or NULL on error.
*
* A new surface will be created with the optimal format for the window,
* if necessary. This surface will be freed when the window is destroyed.
*
* \note You may not combine this with 3D or the rendering API on this window.
*
* \sa SDL_UpdateWindowSurface()
* \sa SDL_UpdateWindowSurfaceRects()
*/
extern DECLSPEC SDL_Surface * SDLCALL SDL_GetWindowSurface(SDL_Window * window);
/**
* \brief Copy the window surface to the screen.
*
* \return 0 on success, or -1 on error.
*
* \sa SDL_GetWindowSurface()
* \sa SDL_UpdateWindowSurfaceRects()
*/
extern DECLSPEC int SDLCALL SDL_UpdateWindowSurface(SDL_Window * window);
/**
* \brief Copy a number of rectangles on the window surface to the screen.
*
* \return 0 on success, or -1 on error.
*
* \sa SDL_GetWindowSurface()
* \sa SDL_UpdateWindowSurface()
*/
extern DECLSPEC int SDLCALL SDL_UpdateWindowSurfaceRects(SDL_Window * window,
const SDL_Rect * rects,
int numrects);
/**
* \brief Set a window's input grab mode.
*
* \param window The window for which the input grab mode should be set.
* \param grabbed This is SDL_TRUE to grab input, and SDL_FALSE to release input.
*
* If the caller enables a grab while another window is currently grabbed,
* the other window loses its grab in favor of the caller's window.
*
* \sa SDL_GetWindowGrab()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowGrab(SDL_Window * window,
SDL_bool grabbed);
/**
* \brief Get a window's input grab mode.
*
* \return This returns SDL_TRUE if input is grabbed, and SDL_FALSE otherwise.
*
* \sa SDL_SetWindowGrab()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GetWindowGrab(SDL_Window * window);
/**
* \brief Get the window that currently has an input grab enabled.
*
* \return This returns the window if input is grabbed, and NULL otherwise.
*
* \sa SDL_SetWindowGrab()
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_GetGrabbedWindow(void);
/**
* \brief Set the brightness (gamma correction) for a window.
*
* \return 0 on success, or -1 if setting the brightness isn't supported.
*
* \sa SDL_GetWindowBrightness()
* \sa SDL_SetWindowGammaRamp()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowBrightness(SDL_Window * window, float brightness);
/**
* \brief Get the brightness (gamma correction) for a window.
*
* \return The last brightness value passed to SDL_SetWindowBrightness()
*
* \sa SDL_SetWindowBrightness()
*/
extern DECLSPEC float SDLCALL SDL_GetWindowBrightness(SDL_Window * window);
/**
* \brief Set the opacity for a window
*
* \param window The window which will be made transparent or opaque
* \param opacity Opacity (0.0f - transparent, 1.0f - opaque) This will be
* clamped internally between 0.0f and 1.0f.
*
* \return 0 on success, or -1 if setting the opacity isn't supported.
*
* \sa SDL_GetWindowOpacity()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowOpacity(SDL_Window * window, float opacity);
/**
* \brief Get the opacity of a window.
*
* If transparency isn't supported on this platform, opacity will be reported
* as 1.0f without error.
*
* \param window The window in question.
* \param out_opacity Opacity (0.0f - transparent, 1.0f - opaque)
*
* \return 0 on success, or -1 on error (invalid window, etc).
*
* \sa SDL_SetWindowOpacity()
*/
extern DECLSPEC int SDLCALL SDL_GetWindowOpacity(SDL_Window * window, float * out_opacity);
/**
* \brief Sets the window as a modal for another window (TODO: reconsider this function and/or its name)
*
* \param modal_window The window that should be modal
* \param parent_window The parent window
*
* \return 0 on success, or -1 otherwise.
*/
extern DECLSPEC int SDLCALL SDL_SetWindowModalFor(SDL_Window * modal_window, SDL_Window * parent_window);
/**
* \brief Explicitly sets input focus to the window.
*
* You almost certainly want SDL_RaiseWindow() instead of this function. Use
* this with caution, as you might give focus to a window that's completely
* obscured by other windows.
*
* \param window The window that should get the input focus
*
* \return 0 on success, or -1 otherwise.
* \sa SDL_RaiseWindow()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowInputFocus(SDL_Window * window);
/**
* \brief Set the gamma ramp for a window.
*
* \param window The window for which the gamma ramp should be set.
* \param red The translation table for the red channel, or NULL.
* \param green The translation table for the green channel, or NULL.
* \param blue The translation table for the blue channel, or NULL.
*
* \return 0 on success, or -1 if gamma ramps are unsupported.
*
* Set the gamma translation table for the red, green, and blue channels
* of the video hardware. Each table is an array of 256 16-bit quantities,
* representing a mapping between the input and output for that channel.
* The input is the index into the array, and the output is the 16-bit
* gamma value at that index, scaled to the output color precision.
*
* \sa SDL_GetWindowGammaRamp()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowGammaRamp(SDL_Window * window,
const Uint16 * red,
const Uint16 * green,
const Uint16 * blue);
/**
* \brief Get the gamma ramp for a window.
*
* \param window The window from which the gamma ramp should be queried.
* \param red A pointer to a 256 element array of 16-bit quantities to hold
* the translation table for the red channel, or NULL.
* \param green A pointer to a 256 element array of 16-bit quantities to hold
* the translation table for the green channel, or NULL.
* \param blue A pointer to a 256 element array of 16-bit quantities to hold
* the translation table for the blue channel, or NULL.
*
* \return 0 on success, or -1 if gamma ramps are unsupported.
*
* \sa SDL_SetWindowGammaRamp()
*/
extern DECLSPEC int SDLCALL SDL_GetWindowGammaRamp(SDL_Window * window,
Uint16 * red,
Uint16 * green,
Uint16 * blue);
/**
* \brief Possible return values from the SDL_HitTest callback.
*
* \sa SDL_HitTest
*/
typedef enum
{
SDL_HITTEST_NORMAL, /**< Region is normal. No special properties. */
SDL_HITTEST_DRAGGABLE, /**< Region can drag entire window. */
SDL_HITTEST_RESIZE_TOPLEFT,
SDL_HITTEST_RESIZE_TOP,
SDL_HITTEST_RESIZE_TOPRIGHT,
SDL_HITTEST_RESIZE_RIGHT,
SDL_HITTEST_RESIZE_BOTTOMRIGHT,
SDL_HITTEST_RESIZE_BOTTOM,
SDL_HITTEST_RESIZE_BOTTOMLEFT,
SDL_HITTEST_RESIZE_LEFT
} SDL_HitTestResult;
/**
* \brief Callback used for hit-testing.
*
* \sa SDL_SetWindowHitTest
*/
typedef SDL_HitTestResult (SDLCALL *SDL_HitTest)(SDL_Window *win,
const SDL_Point *area,
void *data);
/**
* \brief Provide a callback that decides if a window region has special properties.
*
* Normally windows are dragged and resized by decorations provided by the
* system window manager (a title bar, borders, etc), but for some apps, it
* makes sense to drag them from somewhere else inside the window itself; for
* example, one might have a borderless window that wants to be draggable
* from any part, or simulate its own title bar, etc.
*
* This function lets the app provide a callback that designates pieces of
* a given window as special. This callback is run during event processing
* if we need to tell the OS to treat a region of the window specially; the
* use of this callback is known as "hit testing."
*
* Mouse input may not be delivered to your application if it is within
* a special area; the OS will often apply that input to moving the window or
* resizing the window and not deliver it to the application.
*
* Specifying NULL for a callback disables hit-testing. Hit-testing is
* disabled by default.
*
* Platforms that don't support this functionality will return -1
* unconditionally, even if you're attempting to disable hit-testing.
*
* Your callback may fire at any time, and its firing does not indicate any
* specific behavior (for example, on Windows, this certainly might fire
* when the OS is deciding whether to drag your window, but it fires for lots
* of other reasons, too, some unrelated to anything you probably care about
* _and when the mouse isn't actually at the location it is testing_).
* Since this can fire at any time, you should try to keep your callback
* efficient, devoid of allocations, etc.
*
* \param window The window to set hit-testing on.
* \param callback The callback to call when doing a hit-test.
* \param callback_data An app-defined void pointer passed to the callback.
* \return 0 on success, -1 on error (including unsupported).
*/
extern DECLSPEC int SDLCALL SDL_SetWindowHitTest(SDL_Window * window,
SDL_HitTest callback,
void *callback_data);
/**
* \brief Destroy a window.
*/
extern DECLSPEC void SDLCALL SDL_DestroyWindow(SDL_Window * window);
/**
* \brief Returns whether the screensaver is currently enabled (default off).
*
* \sa SDL_EnableScreenSaver()
* \sa SDL_DisableScreenSaver()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsScreenSaverEnabled(void);
/**
* \brief Allow the screen to be blanked by a screensaver
*
* \sa SDL_IsScreenSaverEnabled()
* \sa SDL_DisableScreenSaver()
*/
extern DECLSPEC void SDLCALL SDL_EnableScreenSaver(void);
/**
* \brief Prevent the screen from being blanked by a screensaver
*
* \sa SDL_IsScreenSaverEnabled()
* \sa SDL_EnableScreenSaver()
*/
extern DECLSPEC void SDLCALL SDL_DisableScreenSaver(void);
/**
* \name OpenGL support functions
*/
/* @{ */
/**
* \brief Dynamically load an OpenGL library.
*
* \param path The platform dependent OpenGL library name, or NULL to open the
* default OpenGL library.
*
* \return 0 on success, or -1 if the library couldn't be loaded.
*
* This should be done after initializing the video driver, but before
* creating any OpenGL windows. If no OpenGL library is loaded, the default
* library will be loaded upon creation of the first OpenGL window.
*
* \note If you do this, you need to retrieve all of the GL functions used in
* your program from the dynamic library using SDL_GL_GetProcAddress().
*
* \sa SDL_GL_GetProcAddress()
* \sa SDL_GL_UnloadLibrary()
*/
extern DECLSPEC int SDLCALL SDL_GL_LoadLibrary(const char *path);
/**
* \brief Get the address of an OpenGL function.
*/
extern DECLSPEC void *SDLCALL SDL_GL_GetProcAddress(const char *proc);
/**
* \brief Unload the OpenGL library previously loaded by SDL_GL_LoadLibrary().
*
* \sa SDL_GL_LoadLibrary()
*/
extern DECLSPEC void SDLCALL SDL_GL_UnloadLibrary(void);
/**
* \brief Return true if an OpenGL extension is supported for the current
* context.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GL_ExtensionSupported(const char
*extension);
/**
* \brief Reset all previously set OpenGL context attributes to their default values
*/
extern DECLSPEC void SDLCALL SDL_GL_ResetAttributes(void);
/**
* \brief Set an OpenGL window attribute before window creation.
*
* \return 0 on success, or -1 if the attribute could not be set.
*/
extern DECLSPEC int SDLCALL SDL_GL_SetAttribute(SDL_GLattr attr, int value);
/**
* \brief Get the actual value for an attribute from the current context.
*
* \return 0 on success, or -1 if the attribute could not be retrieved.
* The integer at \c value will be modified in either case.
*/
extern DECLSPEC int SDLCALL SDL_GL_GetAttribute(SDL_GLattr attr, int *value);
/**
* \brief Create an OpenGL context for use with an OpenGL window, and make it
* current.
*
* \sa SDL_GL_DeleteContext()
*/
extern DECLSPEC SDL_GLContext SDLCALL SDL_GL_CreateContext(SDL_Window *
window);
/**
* \brief Set up an OpenGL context for rendering into an OpenGL window.
*
* \note The context must have been created with a compatible window.
*/
extern DECLSPEC int SDLCALL SDL_GL_MakeCurrent(SDL_Window * window,
SDL_GLContext context);
/**
* \brief Get the currently active OpenGL window.
*/
extern DECLSPEC SDL_Window* SDLCALL SDL_GL_GetCurrentWindow(void);
/**
* \brief Get the currently active OpenGL context.
*/
extern DECLSPEC SDL_GLContext SDLCALL SDL_GL_GetCurrentContext(void);
/**
* \brief Get the size of a window's underlying drawable in pixels (for use
* with glViewport).
*
* \param window Window from which the drawable size should be queried
* \param w Pointer to variable for storing the width in pixels, may be NULL
* \param h Pointer to variable for storing the height in pixels, may be NULL
*
* This may differ from SDL_GetWindowSize() if we're rendering to a high-DPI
* drawable, i.e. the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a
* platform with high-DPI support (Apple calls this "Retina"), and not disabled
* by the SDL_HINT_VIDEO_HIGHDPI_DISABLED hint.
*
* \sa SDL_GetWindowSize()
* \sa SDL_CreateWindow()
*/
extern DECLSPEC void SDLCALL SDL_GL_GetDrawableSize(SDL_Window * window, int *w,
int *h);
/**
* \brief Set the swap interval for the current OpenGL context.
*
* \param interval 0 for immediate updates, 1 for updates synchronized with the
* vertical retrace. If the system supports it, you may
* specify -1 to allow late swaps to happen immediately
* instead of waiting for the next retrace.
*
* \return 0 on success, or -1 if setting the swap interval is not supported.
*
* \sa SDL_GL_GetSwapInterval()
*/
extern DECLSPEC int SDLCALL SDL_GL_SetSwapInterval(int interval);
/**
* \brief Get the swap interval for the current OpenGL context.
*
* \return 0 if there is no vertical retrace synchronization, 1 if the buffer
* swap is synchronized with the vertical retrace, and -1 if late
* swaps happen immediately instead of waiting for the next retrace.
* If the system can't determine the swap interval, or there isn't a
* valid current context, this will return 0 as a safe default.
*
* \sa SDL_GL_SetSwapInterval()
*/
extern DECLSPEC int SDLCALL SDL_GL_GetSwapInterval(void);
/**
* \brief Swap the OpenGL buffers for a window, if double-buffering is
* supported.
*/
extern DECLSPEC void SDLCALL SDL_GL_SwapWindow(SDL_Window * window);
/**
* \brief Delete an OpenGL context.
*
* \sa SDL_GL_CreateContext()
*/
extern DECLSPEC void SDLCALL SDL_GL_DeleteContext(SDL_GLContext context);
/* @} *//* OpenGL support functions */
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_video_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 45,433 | C | 35.3472 | 143 | 0.656879 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_mouse.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_mouse.h
*
* Include file for SDL mouse event handling.
*/
#ifndef SDL_mouse_h_
#define SDL_mouse_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_video.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
typedef struct SDL_Cursor SDL_Cursor; /**< Implementation dependent */
/**
* \brief Cursor types for SDL_CreateSystemCursor().
*/
typedef enum
{
SDL_SYSTEM_CURSOR_ARROW, /**< Arrow */
SDL_SYSTEM_CURSOR_IBEAM, /**< I-beam */
SDL_SYSTEM_CURSOR_WAIT, /**< Wait */
SDL_SYSTEM_CURSOR_CROSSHAIR, /**< Crosshair */
SDL_SYSTEM_CURSOR_WAITARROW, /**< Small wait cursor (or Wait if not available) */
SDL_SYSTEM_CURSOR_SIZENWSE, /**< Double arrow pointing northwest and southeast */
SDL_SYSTEM_CURSOR_SIZENESW, /**< Double arrow pointing northeast and southwest */
SDL_SYSTEM_CURSOR_SIZEWE, /**< Double arrow pointing west and east */
SDL_SYSTEM_CURSOR_SIZENS, /**< Double arrow pointing north and south */
SDL_SYSTEM_CURSOR_SIZEALL, /**< Four pointed arrow pointing north, south, east, and west */
SDL_SYSTEM_CURSOR_NO, /**< Slashed circle or crossbones */
SDL_SYSTEM_CURSOR_HAND, /**< Hand */
SDL_NUM_SYSTEM_CURSORS
} SDL_SystemCursor;
/**
* \brief Scroll direction types for the Scroll event
*/
typedef enum
{
SDL_MOUSEWHEEL_NORMAL, /**< The scroll direction is normal */
SDL_MOUSEWHEEL_FLIPPED /**< The scroll direction is flipped / natural */
} SDL_MouseWheelDirection;
/* Function prototypes */
/**
* \brief Get the window which currently has mouse focus.
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_GetMouseFocus(void);
/**
* \brief Retrieve the current state of the mouse.
*
* The current button state is returned as a button bitmask, which can
* be tested using the SDL_BUTTON(X) macros, and x and y are set to the
* mouse cursor position relative to the focus window for the currently
* selected mouse. You can pass NULL for either x or y.
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetMouseState(int *x, int *y);
/**
* \brief Get the current state of the mouse, in relation to the desktop
*
* This works just like SDL_GetMouseState(), but the coordinates will be
* reported relative to the top-left of the desktop. This can be useful if
* you need to track the mouse outside of a specific window and
* SDL_CaptureMouse() doesn't fit your needs. For example, it could be
* useful if you need to track the mouse while dragging a window, where
* coordinates relative to a window might not be in sync at all times.
*
* \note SDL_GetMouseState() returns the mouse position as SDL understands
* it from the last pump of the event queue. This function, however,
* queries the OS for the current mouse position, and as such, might
* be a slightly less efficient function. Unless you know what you're
* doing and have a good reason to use this function, you probably want
* SDL_GetMouseState() instead.
*
* \param x Returns the current X coord, relative to the desktop. Can be NULL.
* \param y Returns the current Y coord, relative to the desktop. Can be NULL.
* \return The current button state as a bitmask, which can be tested using the SDL_BUTTON(X) macros.
*
* \sa SDL_GetMouseState
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetGlobalMouseState(int *x, int *y);
/**
* \brief Retrieve the relative state of the mouse.
*
* The current button state is returned as a button bitmask, which can
* be tested using the SDL_BUTTON(X) macros, and x and y are set to the
* mouse deltas since the last call to SDL_GetRelativeMouseState().
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetRelativeMouseState(int *x, int *y);
/**
* \brief Moves the mouse to the given position within the window.
*
* \param window The window to move the mouse into, or NULL for the current mouse focus
* \param x The x coordinate within the window
* \param y The y coordinate within the window
*
* \note This function generates a mouse motion event
*/
extern DECLSPEC void SDLCALL SDL_WarpMouseInWindow(SDL_Window * window,
int x, int y);
/**
* \brief Moves the mouse to the given position in global screen space.
*
* \param x The x coordinate
* \param y The y coordinate
* \return 0 on success, -1 on error (usually: unsupported by a platform).
*
* \note This function generates a mouse motion event
*/
extern DECLSPEC int SDLCALL SDL_WarpMouseGlobal(int x, int y);
/**
* \brief Set relative mouse mode.
*
* \param enabled Whether or not to enable relative mode
*
* \return 0 on success, or -1 if relative mode is not supported.
*
* While the mouse is in relative mode, the cursor is hidden, and the
* driver will try to report continuous motion in the current window.
* Only relative motion events will be delivered, the mouse position
* will not change.
*
* \note This function will flush any pending mouse motion.
*
* \sa SDL_GetRelativeMouseMode()
*/
extern DECLSPEC int SDLCALL SDL_SetRelativeMouseMode(SDL_bool enabled);
/**
* \brief Capture the mouse, to track input outside an SDL window.
*
* \param enabled Whether or not to enable capturing
*
* Capturing enables your app to obtain mouse events globally, instead of
* just within your window. Not all video targets support this function.
* When capturing is enabled, the current window will get all mouse events,
* but unlike relative mode, no change is made to the cursor and it is
* not restrained to your window.
*
* This function may also deny mouse input to other windows--both those in
* your application and others on the system--so you should use this
* function sparingly, and in small bursts. For example, you might want to
* track the mouse while the user is dragging something, until the user
* releases a mouse button. It is not recommended that you capture the mouse
* for long periods of time, such as the entire time your app is running.
*
* While captured, mouse events still report coordinates relative to the
* current (foreground) window, but those coordinates may be outside the
* bounds of the window (including negative values). Capturing is only
* allowed for the foreground window. If the window loses focus while
* capturing, the capture will be disabled automatically.
*
* While capturing is enabled, the current window will have the
* SDL_WINDOW_MOUSE_CAPTURE flag set.
*
* \return 0 on success, or -1 if not supported.
*/
extern DECLSPEC int SDLCALL SDL_CaptureMouse(SDL_bool enabled);
/**
* \brief Query whether relative mouse mode is enabled.
*
* \sa SDL_SetRelativeMouseMode()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GetRelativeMouseMode(void);
/**
* \brief Create a cursor, using the specified bitmap data and
* mask (in MSB format).
*
* The cursor width must be a multiple of 8 bits.
*
* The cursor is created in black and white according to the following:
* <table>
* <tr><td> data </td><td> mask </td><td> resulting pixel on screen </td></tr>
* <tr><td> 0 </td><td> 1 </td><td> White </td></tr>
* <tr><td> 1 </td><td> 1 </td><td> Black </td></tr>
* <tr><td> 0 </td><td> 0 </td><td> Transparent </td></tr>
* <tr><td> 1 </td><td> 0 </td><td> Inverted color if possible, black
* if not. </td></tr>
* </table>
*
* \sa SDL_FreeCursor()
*/
extern DECLSPEC SDL_Cursor *SDLCALL SDL_CreateCursor(const Uint8 * data,
const Uint8 * mask,
int w, int h, int hot_x,
int hot_y);
/**
* \brief Create a color cursor.
*
* \sa SDL_FreeCursor()
*/
extern DECLSPEC SDL_Cursor *SDLCALL SDL_CreateColorCursor(SDL_Surface *surface,
int hot_x,
int hot_y);
/**
* \brief Create a system cursor.
*
* \sa SDL_FreeCursor()
*/
extern DECLSPEC SDL_Cursor *SDLCALL SDL_CreateSystemCursor(SDL_SystemCursor id);
/**
* \brief Set the active cursor.
*/
extern DECLSPEC void SDLCALL SDL_SetCursor(SDL_Cursor * cursor);
/**
* \brief Return the active cursor.
*/
extern DECLSPEC SDL_Cursor *SDLCALL SDL_GetCursor(void);
/**
* \brief Return the default cursor.
*/
extern DECLSPEC SDL_Cursor *SDLCALL SDL_GetDefaultCursor(void);
/**
* \brief Frees a cursor created with SDL_CreateCursor() or similar functions.
*
* \sa SDL_CreateCursor()
* \sa SDL_CreateColorCursor()
* \sa SDL_CreateSystemCursor()
*/
extern DECLSPEC void SDLCALL SDL_FreeCursor(SDL_Cursor * cursor);
/**
* \brief Toggle whether or not the cursor is shown.
*
* \param toggle 1 to show the cursor, 0 to hide it, -1 to query the current
* state.
*
* \return 1 if the cursor is shown, or 0 if the cursor is hidden.
*/
extern DECLSPEC int SDLCALL SDL_ShowCursor(int toggle);
/**
* Used as a mask when testing buttons in buttonstate.
* - Button 1: Left mouse button
* - Button 2: Middle mouse button
* - Button 3: Right mouse button
*/
#define SDL_BUTTON(X) (1 << ((X)-1))
#define SDL_BUTTON_LEFT 1
#define SDL_BUTTON_MIDDLE 2
#define SDL_BUTTON_RIGHT 3
#define SDL_BUTTON_X1 4
#define SDL_BUTTON_X2 5
#define SDL_BUTTON_LMASK SDL_BUTTON(SDL_BUTTON_LEFT)
#define SDL_BUTTON_MMASK SDL_BUTTON(SDL_BUTTON_MIDDLE)
#define SDL_BUTTON_RMASK SDL_BUTTON(SDL_BUTTON_RIGHT)
#define SDL_BUTTON_X1MASK SDL_BUTTON(SDL_BUTTON_X1)
#define SDL_BUTTON_X2MASK SDL_BUTTON(SDL_BUTTON_X2)
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_mouse_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 10,924 | C | 35.056105 | 102 | 0.676218 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_test_common.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_test_common.h
*
* Include file for SDL test framework.
*
* This code is a part of the SDL2_test library, not the main SDL library.
*/
/* Ported from original test\common.h file. */
#ifndef SDL_test_common_h_
#define SDL_test_common_h_
#include "SDL.h"
#if defined(__PSP__)
#define DEFAULT_WINDOW_WIDTH 480
#define DEFAULT_WINDOW_HEIGHT 272
#else
#define DEFAULT_WINDOW_WIDTH 640
#define DEFAULT_WINDOW_HEIGHT 480
#endif
#define VERBOSE_VIDEO 0x00000001
#define VERBOSE_MODES 0x00000002
#define VERBOSE_RENDER 0x00000004
#define VERBOSE_EVENT 0x00000008
#define VERBOSE_AUDIO 0x00000010
typedef struct
{
/* SDL init flags */
char **argv;
Uint32 flags;
Uint32 verbose;
/* Video info */
const char *videodriver;
int display;
const char *window_title;
const char *window_icon;
Uint32 window_flags;
int window_x;
int window_y;
int window_w;
int window_h;
int window_minW;
int window_minH;
int window_maxW;
int window_maxH;
int logical_w;
int logical_h;
float scale;
int depth;
int refresh_rate;
int num_windows;
SDL_Window **windows;
/* Renderer info */
const char *renderdriver;
Uint32 render_flags;
SDL_bool skip_renderer;
SDL_Renderer **renderers;
SDL_Texture **targets;
/* Audio info */
const char *audiodriver;
SDL_AudioSpec audiospec;
/* GL settings */
int gl_red_size;
int gl_green_size;
int gl_blue_size;
int gl_alpha_size;
int gl_buffer_size;
int gl_depth_size;
int gl_stencil_size;
int gl_double_buffer;
int gl_accum_red_size;
int gl_accum_green_size;
int gl_accum_blue_size;
int gl_accum_alpha_size;
int gl_stereo;
int gl_multisamplebuffers;
int gl_multisamplesamples;
int gl_retained_backing;
int gl_accelerated;
int gl_major_version;
int gl_minor_version;
int gl_debug;
int gl_profile_mask;
} SDLTest_CommonState;
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* Function prototypes */
/**
* \brief Parse command line parameters and create common state.
*
* \param argv Array of command line parameters
* \param flags Flags indicating which subsystem to initialize (i.e. SDL_INIT_VIDEO | SDL_INIT_AUDIO)
*
* \returns Returns a newly allocated common state object.
*/
SDLTest_CommonState *SDLTest_CommonCreateState(char **argv, Uint32 flags);
/**
* \brief Process one common argument.
*
* \param state The common state describing the test window to create.
* \param index The index of the argument to process in argv[].
*
* \returns The number of arguments processed (i.e. 1 for --fullscreen, 2 for --video [videodriver], or -1 on error.
*/
int SDLTest_CommonArg(SDLTest_CommonState * state, int index);
/**
* \brief Returns common usage information
*
* \param state The common state describing the test window to create.
*
* \returns String with usage information
*/
const char *SDLTest_CommonUsage(SDLTest_CommonState * state);
/**
* \brief Open test window.
*
* \param state The common state describing the test window to create.
*
* \returns True if initialization succeeded, false otherwise
*/
SDL_bool SDLTest_CommonInit(SDLTest_CommonState * state);
/**
* \brief Common event handler for test windows.
*
* \param state The common state used to create test window.
* \param event The event to handle.
* \param done Flag indicating we are done.
*
*/
void SDLTest_CommonEvent(SDLTest_CommonState * state, SDL_Event * event, int *done);
/**
* \brief Close test window.
*
* \param state The common state used to create test window.
*
*/
void SDLTest_CommonQuit(SDLTest_CommonState * state);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_test_common_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 4,906 | C | 24.962963 | 116 | 0.700163 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_opengles2.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_opengles2.h
*
* This is a simple file to encapsulate the OpenGL ES 2.0 API headers.
*/
#include "SDL_config.h"
#ifndef _MSC_VER
#ifdef __IPHONEOS__
#include <OpenGLES/ES2/gl.h>
#include <OpenGLES/ES2/glext.h>
#else
#include <GLES2/gl2platform.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#endif
#else /* _MSC_VER */
/* OpenGL ES2 headers for Visual Studio */
#include "SDL_opengles2_khrplatform.h"
#include "SDL_opengles2_gl2platform.h"
#include "SDL_opengles2_gl2.h"
#include "SDL_opengles2_gl2ext.h"
#endif /* _MSC_VER */
#ifndef APIENTRY
#define APIENTRY GL_APIENTRY
#endif
| 1,552 | C | 28.301886 | 76 | 0.740979 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_power.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_power_h_
#define SDL_power_h_
/**
* \file SDL_power.h
*
* Header for the SDL power management routines.
*/
#include "SDL_stdinc.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief The basic state for the system's power supply.
*/
typedef enum
{
SDL_POWERSTATE_UNKNOWN, /**< cannot determine power status */
SDL_POWERSTATE_ON_BATTERY, /**< Not plugged in, running on the battery */
SDL_POWERSTATE_NO_BATTERY, /**< Plugged in, no battery available */
SDL_POWERSTATE_CHARGING, /**< Plugged in, charging battery */
SDL_POWERSTATE_CHARGED /**< Plugged in, battery charged */
} SDL_PowerState;
/**
* \brief Get the current power supply details.
*
* \param secs Seconds of battery life left. You can pass a NULL here if
* you don't care. Will return -1 if we can't determine a
* value, or we're not running on a battery.
*
* \param pct Percentage of battery life left, between 0 and 100. You can
* pass a NULL here if you don't care. Will return -1 if we
* can't determine a value, or we're not running on a battery.
*
* \return The state of the battery (if any).
*/
extern DECLSPEC SDL_PowerState SDLCALL SDL_GetPowerInfo(int *secs, int *pct);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_power_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 2,463 | C | 31.421052 | 79 | 0.691433 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_rwops.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_rwops.h
*
* This file provides a general interface for SDL to read and write
* data streams. It can easily be extended to files, memory, etc.
*/
#ifndef SDL_rwops_h_
#define SDL_rwops_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* RWops Types */
#define SDL_RWOPS_UNKNOWN 0U /**< Unknown stream type */
#define SDL_RWOPS_WINFILE 1U /**< Win32 file */
#define SDL_RWOPS_STDFILE 2U /**< Stdio file */
#define SDL_RWOPS_JNIFILE 3U /**< Android asset */
#define SDL_RWOPS_MEMORY 4U /**< Memory stream */
#define SDL_RWOPS_MEMORY_RO 5U /**< Read-Only memory stream */
/**
* This is the read/write operation structure -- very basic.
*/
typedef struct SDL_RWops
{
/**
* Return the size of the file in this rwops, or -1 if unknown
*/
Sint64 (SDLCALL * size) (struct SDL_RWops * context);
/**
* Seek to \c offset relative to \c whence, one of stdio's whence values:
* RW_SEEK_SET, RW_SEEK_CUR, RW_SEEK_END
*
* \return the final offset in the data stream, or -1 on error.
*/
Sint64 (SDLCALL * seek) (struct SDL_RWops * context, Sint64 offset,
int whence);
/**
* Read up to \c maxnum objects each of size \c size from the data
* stream to the area pointed at by \c ptr.
*
* \return the number of objects read, or 0 at error or end of file.
*/
size_t (SDLCALL * read) (struct SDL_RWops * context, void *ptr,
size_t size, size_t maxnum);
/**
* Write exactly \c num objects each of size \c size from the area
* pointed at by \c ptr to data stream.
*
* \return the number of objects written, or 0 at error or end of file.
*/
size_t (SDLCALL * write) (struct SDL_RWops * context, const void *ptr,
size_t size, size_t num);
/**
* Close and free an allocated SDL_RWops structure.
*
* \return 0 if successful or -1 on write error when flushing data.
*/
int (SDLCALL * close) (struct SDL_RWops * context);
Uint32 type;
union
{
#if defined(__ANDROID__)
struct
{
void *fileNameRef;
void *inputStreamRef;
void *readableByteChannelRef;
void *readMethod;
void *assetFileDescriptorRef;
long position;
long size;
long offset;
int fd;
} androidio;
#elif defined(__WIN32__)
struct
{
SDL_bool append;
void *h;
struct
{
void *data;
size_t size;
size_t left;
} buffer;
} windowsio;
#endif
#ifdef HAVE_STDIO_H
struct
{
SDL_bool autoclose;
FILE *fp;
} stdio;
#endif
struct
{
Uint8 *base;
Uint8 *here;
Uint8 *stop;
} mem;
struct
{
void *data1;
void *data2;
} unknown;
} hidden;
} SDL_RWops;
/**
* \name RWFrom functions
*
* Functions to create SDL_RWops structures from various data streams.
*/
/* @{ */
extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFile(const char *file,
const char *mode);
#ifdef HAVE_STDIO_H
extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFP(FILE * fp,
SDL_bool autoclose);
#else
extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFP(void * fp,
SDL_bool autoclose);
#endif
extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromMem(void *mem, int size);
extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromConstMem(const void *mem,
int size);
/* @} *//* RWFrom functions */
extern DECLSPEC SDL_RWops *SDLCALL SDL_AllocRW(void);
extern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops * area);
#define RW_SEEK_SET 0 /**< Seek from the beginning of data */
#define RW_SEEK_CUR 1 /**< Seek relative to current read point */
#define RW_SEEK_END 2 /**< Seek relative to the end of data */
/**
* \name Read/write macros
*
* Macros to easily read and write from an SDL_RWops structure.
*/
/* @{ */
#define SDL_RWsize(ctx) (ctx)->size(ctx)
#define SDL_RWseek(ctx, offset, whence) (ctx)->seek(ctx, offset, whence)
#define SDL_RWtell(ctx) (ctx)->seek(ctx, 0, RW_SEEK_CUR)
#define SDL_RWread(ctx, ptr, size, n) (ctx)->read(ctx, ptr, size, n)
#define SDL_RWwrite(ctx, ptr, size, n) (ctx)->write(ctx, ptr, size, n)
#define SDL_RWclose(ctx) (ctx)->close(ctx)
/* @} *//* Read/write macros */
/**
* Load all the data from an SDL data stream.
*
* The data is allocated with a zero byte at the end (null terminated)
*
* If \c datasize is not NULL, it is filled with the size of the data read.
*
* If \c freesrc is non-zero, the stream will be closed after being read.
*
* The data should be freed with SDL_free().
*
* \return the data, or NULL if there was an error.
*/
extern DECLSPEC void *SDLCALL SDL_LoadFile_RW(SDL_RWops * src, size_t *datasize,
int freesrc);
/**
* Load an entire file.
*
* Convenience macro.
*/
#define SDL_LoadFile(file, datasize) SDL_LoadFile_RW(SDL_RWFromFile(file, "rb"), datasize, 1)
/**
* \name Read endian functions
*
* Read an item of the specified endianness and return in native format.
*/
/* @{ */
extern DECLSPEC Uint8 SDLCALL SDL_ReadU8(SDL_RWops * src);
extern DECLSPEC Uint16 SDLCALL SDL_ReadLE16(SDL_RWops * src);
extern DECLSPEC Uint16 SDLCALL SDL_ReadBE16(SDL_RWops * src);
extern DECLSPEC Uint32 SDLCALL SDL_ReadLE32(SDL_RWops * src);
extern DECLSPEC Uint32 SDLCALL SDL_ReadBE32(SDL_RWops * src);
extern DECLSPEC Uint64 SDLCALL SDL_ReadLE64(SDL_RWops * src);
extern DECLSPEC Uint64 SDLCALL SDL_ReadBE64(SDL_RWops * src);
/* @} *//* Read endian functions */
/**
* \name Write endian functions
*
* Write an item of native format to the specified endianness.
*/
/* @{ */
extern DECLSPEC size_t SDLCALL SDL_WriteU8(SDL_RWops * dst, Uint8 value);
extern DECLSPEC size_t SDLCALL SDL_WriteLE16(SDL_RWops * dst, Uint16 value);
extern DECLSPEC size_t SDLCALL SDL_WriteBE16(SDL_RWops * dst, Uint16 value);
extern DECLSPEC size_t SDLCALL SDL_WriteLE32(SDL_RWops * dst, Uint32 value);
extern DECLSPEC size_t SDLCALL SDL_WriteBE32(SDL_RWops * dst, Uint32 value);
extern DECLSPEC size_t SDLCALL SDL_WriteLE64(SDL_RWops * dst, Uint64 value);
extern DECLSPEC size_t SDLCALL SDL_WriteBE64(SDL_RWops * dst, Uint64 value);
/* @} *//* Write endian functions */
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_rwops_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 7,951 | C | 30.184314 | 95 | 0.618035 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_shape.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_shape_h_
#define SDL_shape_h_
#include "SDL_stdinc.h"
#include "SDL_pixels.h"
#include "SDL_rect.h"
#include "SDL_surface.h"
#include "SDL_video.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/** \file SDL_shape.h
*
* Header file for the shaped window API.
*/
#define SDL_NONSHAPEABLE_WINDOW -1
#define SDL_INVALID_SHAPE_ARGUMENT -2
#define SDL_WINDOW_LACKS_SHAPE -3
/**
* \brief Create a window that can be shaped with the specified position, dimensions, and flags.
*
* \param title The title of the window, in UTF-8 encoding.
* \param x The x position of the window, ::SDL_WINDOWPOS_CENTERED, or
* ::SDL_WINDOWPOS_UNDEFINED.
* \param y The y position of the window, ::SDL_WINDOWPOS_CENTERED, or
* ::SDL_WINDOWPOS_UNDEFINED.
* \param w The width of the window.
* \param h The height of the window.
* \param flags The flags for the window, a mask of SDL_WINDOW_BORDERLESS with any of the following:
* ::SDL_WINDOW_OPENGL, ::SDL_WINDOW_INPUT_GRABBED,
* ::SDL_WINDOW_HIDDEN, ::SDL_WINDOW_RESIZABLE,
* ::SDL_WINDOW_MAXIMIZED, ::SDL_WINDOW_MINIMIZED,
* ::SDL_WINDOW_BORDERLESS is always set, and ::SDL_WINDOW_FULLSCREEN is always unset.
*
* \return The window created, or NULL if window creation failed.
*
* \sa SDL_DestroyWindow()
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_CreateShapedWindow(const char *title,unsigned int x,unsigned int y,unsigned int w,unsigned int h,Uint32 flags);
/**
* \brief Return whether the given window is a shaped window.
*
* \param window The window to query for being shaped.
*
* \return SDL_TRUE if the window is a window that can be shaped, SDL_FALSE if the window is unshaped or NULL.
*
* \sa SDL_CreateShapedWindow
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsShapedWindow(const SDL_Window *window);
/** \brief An enum denoting the specific type of contents present in an SDL_WindowShapeParams union. */
typedef enum {
/** \brief The default mode, a binarized alpha cutoff of 1. */
ShapeModeDefault,
/** \brief A binarized alpha cutoff with a given integer value. */
ShapeModeBinarizeAlpha,
/** \brief A binarized alpha cutoff with a given integer value, but with the opposite comparison. */
ShapeModeReverseBinarizeAlpha,
/** \brief A color key is applied. */
ShapeModeColorKey
} WindowShapeMode;
#define SDL_SHAPEMODEALPHA(mode) (mode == ShapeModeDefault || mode == ShapeModeBinarizeAlpha || mode == ShapeModeReverseBinarizeAlpha)
/** \brief A union containing parameters for shaped windows. */
typedef union {
/** \brief A cutoff alpha value for binarization of the window shape's alpha channel. */
Uint8 binarizationCutoff;
SDL_Color colorKey;
} SDL_WindowShapeParams;
/** \brief A struct that tags the SDL_WindowShapeParams union with an enum describing the type of its contents. */
typedef struct SDL_WindowShapeMode {
/** \brief The mode of these window-shape parameters. */
WindowShapeMode mode;
/** \brief Window-shape parameters. */
SDL_WindowShapeParams parameters;
} SDL_WindowShapeMode;
/**
* \brief Set the shape and parameters of a shaped window.
*
* \param window The shaped window whose parameters should be set.
* \param shape A surface encoding the desired shape for the window.
* \param shape_mode The parameters to set for the shaped window.
*
* \return 0 on success, SDL_INVALID_SHAPE_ARGUMENT on an invalid shape argument, or SDL_NONSHAPEABLE_WINDOW
* if the SDL_Window given does not reference a valid shaped window.
*
* \sa SDL_WindowShapeMode
* \sa SDL_GetShapedWindowMode.
*/
extern DECLSPEC int SDLCALL SDL_SetWindowShape(SDL_Window *window,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode);
/**
* \brief Get the shape parameters of a shaped window.
*
* \param window The shaped window whose parameters should be retrieved.
* \param shape_mode An empty shape-mode structure to fill, or NULL to check whether the window has a shape.
*
* \return 0 if the window has a shape and, provided shape_mode was not NULL, shape_mode has been filled with the mode
* data, SDL_NONSHAPEABLE_WINDOW if the SDL_Window given is not a shaped window, or SDL_WINDOW_LACKS_SHAPE if
* the SDL_Window given is a shapeable window currently lacking a shape.
*
* \sa SDL_WindowShapeMode
* \sa SDL_SetWindowShape
*/
extern DECLSPEC int SDLCALL SDL_GetShapedWindowMode(SDL_Window *window,SDL_WindowShapeMode *shape_mode);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_shape_h_ */
| 5,681 | C | 38.186207 | 152 | 0.718711 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_gamecontroller.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_gamecontroller.h
*
* Include file for SDL game controller event handling
*/
#ifndef SDL_gamecontroller_h_
#define SDL_gamecontroller_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_rwops.h"
#include "SDL_joystick.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \file SDL_gamecontroller.h
*
* In order to use these functions, SDL_Init() must have been called
* with the ::SDL_INIT_GAMECONTROLLER flag. This causes SDL to scan the system
* for game controllers, and load appropriate drivers.
*
* If you would like to receive controller updates while the application
* is in the background, you should set the following hint before calling
* SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS
*/
/**
* The gamecontroller structure used to identify an SDL game controller
*/
struct _SDL_GameController;
typedef struct _SDL_GameController SDL_GameController;
typedef enum
{
SDL_CONTROLLER_BINDTYPE_NONE = 0,
SDL_CONTROLLER_BINDTYPE_BUTTON,
SDL_CONTROLLER_BINDTYPE_AXIS,
SDL_CONTROLLER_BINDTYPE_HAT
} SDL_GameControllerBindType;
/**
* Get the SDL joystick layer binding for this controller button/axis mapping
*/
typedef struct SDL_GameControllerButtonBind
{
SDL_GameControllerBindType bindType;
union
{
int button;
int axis;
struct {
int hat;
int hat_mask;
} hat;
} value;
} SDL_GameControllerButtonBind;
/**
* To count the number of game controllers in the system for the following:
* int nJoysticks = SDL_NumJoysticks();
* int nGameControllers = 0;
* for (int i = 0; i < nJoysticks; i++) {
* if (SDL_IsGameController(i)) {
* nGameControllers++;
* }
* }
*
* Using the SDL_HINT_GAMECONTROLLERCONFIG hint or the SDL_GameControllerAddMapping() you can add support for controllers SDL is unaware of or cause an existing controller to have a different binding. The format is:
* guid,name,mappings
*
* Where GUID is the string value from SDL_JoystickGetGUIDString(), name is the human readable string for the device and mappings are controller mappings to joystick ones.
* Under Windows there is a reserved GUID of "xinput" that covers any XInput devices.
* The mapping format for joystick is:
* bX - a joystick button, index X
* hX.Y - hat X with value Y
* aX - axis X of the joystick
* Buttons can be used as a controller axis and vice versa.
*
* This string shows an example of a valid mapping for a controller
* "03000000341a00003608000000000000,PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7",
*
*/
/**
* Load a set of mappings from a seekable SDL data stream (memory or file), filtered by the current SDL_GetPlatform()
* A community sourced database of controllers is available at https://raw.github.com/gabomdq/SDL_GameControllerDB/master/gamecontrollerdb.txt
*
* If \c freerw is non-zero, the stream will be closed after being read.
*
* \return number of mappings added, -1 on error
*/
extern DECLSPEC int SDLCALL SDL_GameControllerAddMappingsFromRW(SDL_RWops * rw, int freerw);
/**
* Load a set of mappings from a file, filtered by the current SDL_GetPlatform()
*
* Convenience macro.
*/
#define SDL_GameControllerAddMappingsFromFile(file) SDL_GameControllerAddMappingsFromRW(SDL_RWFromFile(file, "rb"), 1)
/**
* Add or update an existing mapping configuration
*
* \return 1 if mapping is added, 0 if updated, -1 on error
*/
extern DECLSPEC int SDLCALL SDL_GameControllerAddMapping(const char* mappingString);
/**
* Get the number of mappings installed
*
* \return the number of mappings
*/
extern DECLSPEC int SDLCALL SDL_GameControllerNumMappings(void);
/**
* Get the mapping at a particular index.
*
* \return the mapping string. Must be freed with SDL_free(). Returns NULL if the index is out of range.
*/
extern DECLSPEC char * SDLCALL SDL_GameControllerMappingForIndex(int mapping_index);
/**
* Get a mapping string for a GUID
*
* \return the mapping string. Must be freed with SDL_free(). Returns NULL if no mapping is available
*/
extern DECLSPEC char * SDLCALL SDL_GameControllerMappingForGUID(SDL_JoystickGUID guid);
/**
* Get a mapping string for an open GameController
*
* \return the mapping string. Must be freed with SDL_free(). Returns NULL if no mapping is available
*/
extern DECLSPEC char * SDLCALL SDL_GameControllerMapping(SDL_GameController * gamecontroller);
/**
* Is the joystick on this index supported by the game controller interface?
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsGameController(int joystick_index);
/**
* Get the implementation dependent name of a game controller.
* This can be called before any controllers are opened.
* If no name can be found, this function returns NULL.
*/
extern DECLSPEC const char *SDLCALL SDL_GameControllerNameForIndex(int joystick_index);
/**
* Open a game controller for use.
* The index passed as an argument refers to the N'th game controller on the system.
* This index is not the value which will identify this controller in future
* controller events. The joystick's instance id (::SDL_JoystickID) will be
* used there instead.
*
* \return A controller identifier, or NULL if an error occurred.
*/
extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerOpen(int joystick_index);
/**
* Return the SDL_GameController associated with an instance id.
*/
extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerFromInstanceID(SDL_JoystickID joyid);
/**
* Return the name for this currently opened controller
*/
extern DECLSPEC const char *SDLCALL SDL_GameControllerName(SDL_GameController *gamecontroller);
/**
* Get the USB vendor ID of an opened controller, if available.
* If the vendor ID isn't available this function returns 0.
*/
extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetVendor(SDL_GameController * gamecontroller);
/**
* Get the USB product ID of an opened controller, if available.
* If the product ID isn't available this function returns 0.
*/
extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetProduct(SDL_GameController * gamecontroller);
/**
* Get the product version of an opened controller, if available.
* If the product version isn't available this function returns 0.
*/
extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetProductVersion(SDL_GameController * gamecontroller);
/**
* Returns SDL_TRUE if the controller has been opened and currently connected,
* or SDL_FALSE if it has not.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerGetAttached(SDL_GameController *gamecontroller);
/**
* Get the underlying joystick object used by a controller
*/
extern DECLSPEC SDL_Joystick *SDLCALL SDL_GameControllerGetJoystick(SDL_GameController *gamecontroller);
/**
* Enable/disable controller event polling.
*
* If controller events are disabled, you must call SDL_GameControllerUpdate()
* yourself and check the state of the controller when you want controller
* information.
*
* The state can be one of ::SDL_QUERY, ::SDL_ENABLE or ::SDL_IGNORE.
*/
extern DECLSPEC int SDLCALL SDL_GameControllerEventState(int state);
/**
* Update the current state of the open game controllers.
*
* This is called automatically by the event loop if any game controller
* events are enabled.
*/
extern DECLSPEC void SDLCALL SDL_GameControllerUpdate(void);
/**
* The list of axes available from a controller
*
* Thumbstick axis values range from SDL_JOYSTICK_AXIS_MIN to SDL_JOYSTICK_AXIS_MAX,
* and are centered within ~8000 of zero, though advanced UI will allow users to set
* or autodetect the dead zone, which varies between controllers.
*
* Trigger axis values range from 0 to SDL_JOYSTICK_AXIS_MAX.
*/
typedef enum
{
SDL_CONTROLLER_AXIS_INVALID = -1,
SDL_CONTROLLER_AXIS_LEFTX,
SDL_CONTROLLER_AXIS_LEFTY,
SDL_CONTROLLER_AXIS_RIGHTX,
SDL_CONTROLLER_AXIS_RIGHTY,
SDL_CONTROLLER_AXIS_TRIGGERLEFT,
SDL_CONTROLLER_AXIS_TRIGGERRIGHT,
SDL_CONTROLLER_AXIS_MAX
} SDL_GameControllerAxis;
/**
* turn this string into a axis mapping
*/
extern DECLSPEC SDL_GameControllerAxis SDLCALL SDL_GameControllerGetAxisFromString(const char *pchString);
/**
* turn this axis enum into a string mapping
*/
extern DECLSPEC const char* SDLCALL SDL_GameControllerGetStringForAxis(SDL_GameControllerAxis axis);
/**
* Get the SDL joystick layer binding for this controller button mapping
*/
extern DECLSPEC SDL_GameControllerButtonBind SDLCALL
SDL_GameControllerGetBindForAxis(SDL_GameController *gamecontroller,
SDL_GameControllerAxis axis);
/**
* Get the current state of an axis control on a game controller.
*
* The state is a value ranging from -32768 to 32767 (except for the triggers,
* which range from 0 to 32767).
*
* The axis indices start at index 0.
*/
extern DECLSPEC Sint16 SDLCALL
SDL_GameControllerGetAxis(SDL_GameController *gamecontroller,
SDL_GameControllerAxis axis);
/**
* The list of buttons available from a controller
*/
typedef enum
{
SDL_CONTROLLER_BUTTON_INVALID = -1,
SDL_CONTROLLER_BUTTON_A,
SDL_CONTROLLER_BUTTON_B,
SDL_CONTROLLER_BUTTON_X,
SDL_CONTROLLER_BUTTON_Y,
SDL_CONTROLLER_BUTTON_BACK,
SDL_CONTROLLER_BUTTON_GUIDE,
SDL_CONTROLLER_BUTTON_START,
SDL_CONTROLLER_BUTTON_LEFTSTICK,
SDL_CONTROLLER_BUTTON_RIGHTSTICK,
SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
SDL_CONTROLLER_BUTTON_DPAD_UP,
SDL_CONTROLLER_BUTTON_DPAD_DOWN,
SDL_CONTROLLER_BUTTON_DPAD_LEFT,
SDL_CONTROLLER_BUTTON_DPAD_RIGHT,
SDL_CONTROLLER_BUTTON_MAX
} SDL_GameControllerButton;
/**
* turn this string into a button mapping
*/
extern DECLSPEC SDL_GameControllerButton SDLCALL SDL_GameControllerGetButtonFromString(const char *pchString);
/**
* turn this button enum into a string mapping
*/
extern DECLSPEC const char* SDLCALL SDL_GameControllerGetStringForButton(SDL_GameControllerButton button);
/**
* Get the SDL joystick layer binding for this controller button mapping
*/
extern DECLSPEC SDL_GameControllerButtonBind SDLCALL
SDL_GameControllerGetBindForButton(SDL_GameController *gamecontroller,
SDL_GameControllerButton button);
/**
* Get the current state of a button on a game controller.
*
* The button indices start at index 0.
*/
extern DECLSPEC Uint8 SDLCALL SDL_GameControllerGetButton(SDL_GameController *gamecontroller,
SDL_GameControllerButton button);
/**
* Close a controller previously opened with SDL_GameControllerOpen().
*/
extern DECLSPEC void SDLCALL SDL_GameControllerClose(SDL_GameController *gamecontroller);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_gamecontroller_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 12,233 | C | 32.702479 | 279 | 0.735306 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/begin_code.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file begin_code.h
*
* This file sets things up for C dynamic library function definitions,
* static inlined functions, and structures aligned at 4-byte alignment.
* If you don't like ugly C preprocessor code, don't look at this file. :)
*/
/* This shouldn't be nested -- included it around code only. */
#ifdef _begin_code_h
#error Nested inclusion of begin_code.h
#endif
#define _begin_code_h
#ifndef SDL_DEPRECATED
# if (__GNUC__ >= 4) /* technically, this arrived in gcc 3.1, but oh well. */
# define SDL_DEPRECATED __attribute__((deprecated))
# else
# define SDL_DEPRECATED
# endif
#endif
#ifndef SDL_UNUSED
# ifdef __GNUC__
# define SDL_UNUSED __attribute__((unused))
# else
# define SDL_UNUSED
# endif
#endif
/* Some compilers use a special export keyword */
#ifndef DECLSPEC
# if defined(__WIN32__) || defined(__WINRT__)
# ifdef __BORLANDC__
# ifdef BUILD_SDL
# define DECLSPEC
# else
# define DECLSPEC __declspec(dllimport)
# endif
# else
# define DECLSPEC __declspec(dllexport)
# endif
# elif defined(__OS2__)
# ifdef BUILD_SDL
# define DECLSPEC __declspec(dllexport)
# else
# define DECLSPEC
# endif
# else
# if defined(__GNUC__) && __GNUC__ >= 4
# define DECLSPEC __attribute__ ((visibility("default")))
# else
# define DECLSPEC
# endif
# endif
#endif
/* By default SDL uses the C calling convention */
#ifndef SDLCALL
#if (defined(__WIN32__) || defined(__WINRT__)) && !defined(__GNUC__)
#define SDLCALL __cdecl
#elif defined(__OS2__) || defined(__EMX__)
#define SDLCALL _System
# if defined (__GNUC__) && !defined(_System)
# define _System /* for old EMX/GCC compat. */
# endif
#else
#define SDLCALL
#endif
#endif /* SDLCALL */
/* Removed DECLSPEC on Symbian OS because SDL cannot be a DLL in EPOC */
#ifdef __SYMBIAN32__
#undef DECLSPEC
#define DECLSPEC
#endif /* __SYMBIAN32__ */
/* Force structure packing at 4 byte alignment.
This is necessary if the header is included in code which has structure
packing set to an alternate value, say for loading structures from disk.
The packing is reset to the previous value in close_code.h
*/
#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__)
#ifdef _MSC_VER
#pragma warning(disable: 4103)
#endif
#ifdef __BORLANDC__
#pragma nopackwarning
#endif
#ifdef _M_X64
/* Use 8-byte alignment on 64-bit architectures, so pointers are aligned */
#pragma pack(push,8)
#else
#pragma pack(push,4)
#endif
#endif /* Compiler needs structure packing set */
#ifndef SDL_INLINE
#if defined(__GNUC__)
#define SDL_INLINE __inline__
#elif defined(_MSC_VER) || defined(__BORLANDC__) || \
defined(__DMC__) || defined(__SC__) || \
defined(__WATCOMC__) || defined(__LCC__) || \
defined(__DECC) || defined(__CC_ARM)
#define SDL_INLINE __inline
#ifndef __inline__
#define __inline__ __inline
#endif
#else
#define SDL_INLINE inline
#ifndef __inline__
#define __inline__ inline
#endif
#endif
#endif /* SDL_INLINE not defined */
#ifndef SDL_FORCE_INLINE
#if defined(_MSC_VER)
#define SDL_FORCE_INLINE __forceinline
#elif ( (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) )
#define SDL_FORCE_INLINE __attribute__((always_inline)) static __inline__
#else
#define SDL_FORCE_INLINE static SDL_INLINE
#endif
#endif /* SDL_FORCE_INLINE not defined */
#ifndef SDL_NORETURN
#if defined(__GNUC__)
#define SDL_NORETURN __attribute__((noreturn))
#elif defined(_MSC_VER)
#define SDL_NORETURN __declspec(noreturn)
#else
#define SDL_NORETURN
#endif
#endif /* SDL_NORETURN not defined */
/* Apparently this is needed by several Windows compilers */
#if !defined(__MACH__)
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif /* NULL */
#endif /* ! Mac OS X - breaks precompiled headers */
| 4,731 | C | 27.166667 | 79 | 0.689918 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_mutex.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_mutex_h_
#define SDL_mutex_h_
/**
* \file SDL_mutex.h
*
* Functions to provide thread synchronization primitives.
*/
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* Synchronization functions which can time out return this value
* if they time out.
*/
#define SDL_MUTEX_TIMEDOUT 1
/**
* This is the timeout value which corresponds to never time out.
*/
#define SDL_MUTEX_MAXWAIT (~(Uint32)0)
/**
* \name Mutex functions
*/
/* @{ */
/* The SDL mutex structure, defined in SDL_sysmutex.c */
struct SDL_mutex;
typedef struct SDL_mutex SDL_mutex;
/**
* Create a mutex, initialized unlocked.
*/
extern DECLSPEC SDL_mutex *SDLCALL SDL_CreateMutex(void);
/**
* Lock the mutex.
*
* \return 0, or -1 on error.
*/
#define SDL_mutexP(m) SDL_LockMutex(m)
extern DECLSPEC int SDLCALL SDL_LockMutex(SDL_mutex * mutex);
/**
* Try to lock the mutex
*
* \return 0, SDL_MUTEX_TIMEDOUT, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_TryLockMutex(SDL_mutex * mutex);
/**
* Unlock the mutex.
*
* \return 0, or -1 on error.
*
* \warning It is an error to unlock a mutex that has not been locked by
* the current thread, and doing so results in undefined behavior.
*/
#define SDL_mutexV(m) SDL_UnlockMutex(m)
extern DECLSPEC int SDLCALL SDL_UnlockMutex(SDL_mutex * mutex);
/**
* Destroy a mutex.
*/
extern DECLSPEC void SDLCALL SDL_DestroyMutex(SDL_mutex * mutex);
/* @} *//* Mutex functions */
/**
* \name Semaphore functions
*/
/* @{ */
/* The SDL semaphore structure, defined in SDL_syssem.c */
struct SDL_semaphore;
typedef struct SDL_semaphore SDL_sem;
/**
* Create a semaphore, initialized with value, returns NULL on failure.
*/
extern DECLSPEC SDL_sem *SDLCALL SDL_CreateSemaphore(Uint32 initial_value);
/**
* Destroy a semaphore.
*/
extern DECLSPEC void SDLCALL SDL_DestroySemaphore(SDL_sem * sem);
/**
* This function suspends the calling thread until the semaphore pointed
* to by \c sem has a positive count. It then atomically decreases the
* semaphore count.
*/
extern DECLSPEC int SDLCALL SDL_SemWait(SDL_sem * sem);
/**
* Non-blocking variant of SDL_SemWait().
*
* \return 0 if the wait succeeds, ::SDL_MUTEX_TIMEDOUT if the wait would
* block, and -1 on error.
*/
extern DECLSPEC int SDLCALL SDL_SemTryWait(SDL_sem * sem);
/**
* Variant of SDL_SemWait() with a timeout in milliseconds.
*
* \return 0 if the wait succeeds, ::SDL_MUTEX_TIMEDOUT if the wait does not
* succeed in the allotted time, and -1 on error.
*
* \warning On some platforms this function is implemented by looping with a
* delay of 1 ms, and so should be avoided if possible.
*/
extern DECLSPEC int SDLCALL SDL_SemWaitTimeout(SDL_sem * sem, Uint32 ms);
/**
* Atomically increases the semaphore's count (not blocking).
*
* \return 0, or -1 on error.
*/
extern DECLSPEC int SDLCALL SDL_SemPost(SDL_sem * sem);
/**
* Returns the current count of the semaphore.
*/
extern DECLSPEC Uint32 SDLCALL SDL_SemValue(SDL_sem * sem);
/* @} *//* Semaphore functions */
/**
* \name Condition variable functions
*/
/* @{ */
/* The SDL condition variable structure, defined in SDL_syscond.c */
struct SDL_cond;
typedef struct SDL_cond SDL_cond;
/**
* Create a condition variable.
*
* Typical use of condition variables:
*
* Thread A:
* SDL_LockMutex(lock);
* while ( ! condition ) {
* SDL_CondWait(cond, lock);
* }
* SDL_UnlockMutex(lock);
*
* Thread B:
* SDL_LockMutex(lock);
* ...
* condition = true;
* ...
* SDL_CondSignal(cond);
* SDL_UnlockMutex(lock);
*
* There is some discussion whether to signal the condition variable
* with the mutex locked or not. There is some potential performance
* benefit to unlocking first on some platforms, but there are some
* potential race conditions depending on how your code is structured.
*
* In general it's safer to signal the condition variable while the
* mutex is locked.
*/
extern DECLSPEC SDL_cond *SDLCALL SDL_CreateCond(void);
/**
* Destroy a condition variable.
*/
extern DECLSPEC void SDLCALL SDL_DestroyCond(SDL_cond * cond);
/**
* Restart one of the threads that are waiting on the condition variable.
*
* \return 0 or -1 on error.
*/
extern DECLSPEC int SDLCALL SDL_CondSignal(SDL_cond * cond);
/**
* Restart all threads that are waiting on the condition variable.
*
* \return 0 or -1 on error.
*/
extern DECLSPEC int SDLCALL SDL_CondBroadcast(SDL_cond * cond);
/**
* Wait on the condition variable, unlocking the provided mutex.
*
* \warning The mutex must be locked before entering this function!
*
* The mutex is re-locked once the condition variable is signaled.
*
* \return 0 when it is signaled, or -1 on error.
*/
extern DECLSPEC int SDLCALL SDL_CondWait(SDL_cond * cond, SDL_mutex * mutex);
/**
* Waits for at most \c ms milliseconds, and returns 0 if the condition
* variable is signaled, ::SDL_MUTEX_TIMEDOUT if the condition is not
* signaled in the allotted time, and -1 on error.
*
* \warning On some platforms this function is implemented by looping with a
* delay of 1 ms, and so should be avoided if possible.
*/
extern DECLSPEC int SDLCALL SDL_CondWaitTimeout(SDL_cond * cond,
SDL_mutex * mutex, Uint32 ms);
/* @} *//* Condition variable functions */
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_mutex_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 6,665 | C | 25.452381 | 78 | 0.686572 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/sdl2/SDL2/SDL_render.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_render.h
*
* Header file for SDL 2D rendering functions.
*
* This API supports the following features:
* * single pixel points
* * single pixel lines
* * filled rectangles
* * texture images
*
* The primitives may be drawn in opaque, blended, or additive modes.
*
* The texture images may be drawn in opaque, blended, or additive modes.
* They can have an additional color tint or alpha modulation applied to
* them, and may also be stretched with linear interpolation.
*
* This API is designed to accelerate simple 2D operations. You may
* want more functionality such as polygons and particle effects and
* in that case you should use SDL's OpenGL/Direct3D support or one
* of the many good 3D engines.
*
* These functions must be called from the main thread.
* See this bug for details: http://bugzilla.libsdl.org/show_bug.cgi?id=1995
*/
#ifndef SDL_render_h_
#define SDL_render_h_
#include "SDL_stdinc.h"
#include "SDL_rect.h"
#include "SDL_video.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Flags used when creating a rendering context
*/
typedef enum
{
SDL_RENDERER_SOFTWARE = 0x00000001, /**< The renderer is a software fallback */
SDL_RENDERER_ACCELERATED = 0x00000002, /**< The renderer uses hardware
acceleration */
SDL_RENDERER_PRESENTVSYNC = 0x00000004, /**< Present is synchronized
with the refresh rate */
SDL_RENDERER_TARGETTEXTURE = 0x00000008 /**< The renderer supports
rendering to texture */
} SDL_RendererFlags;
/**
* \brief Information on the capabilities of a render driver or context.
*/
typedef struct SDL_RendererInfo
{
const char *name; /**< The name of the renderer */
Uint32 flags; /**< Supported ::SDL_RendererFlags */
Uint32 num_texture_formats; /**< The number of available texture formats */
Uint32 texture_formats[16]; /**< The available texture formats */
int max_texture_width; /**< The maximum texture width */
int max_texture_height; /**< The maximum texture height */
} SDL_RendererInfo;
/**
* \brief The access pattern allowed for a texture.
*/
typedef enum
{
SDL_TEXTUREACCESS_STATIC, /**< Changes rarely, not lockable */
SDL_TEXTUREACCESS_STREAMING, /**< Changes frequently, lockable */
SDL_TEXTUREACCESS_TARGET /**< Texture can be used as a render target */
} SDL_TextureAccess;
/**
* \brief The texture channel modulation used in SDL_RenderCopy().
*/
typedef enum
{
SDL_TEXTUREMODULATE_NONE = 0x00000000, /**< No modulation */
SDL_TEXTUREMODULATE_COLOR = 0x00000001, /**< srcC = srcC * color */
SDL_TEXTUREMODULATE_ALPHA = 0x00000002 /**< srcA = srcA * alpha */
} SDL_TextureModulate;
/**
* \brief Flip constants for SDL_RenderCopyEx
*/
typedef enum
{
SDL_FLIP_NONE = 0x00000000, /**< Do not flip */
SDL_FLIP_HORIZONTAL = 0x00000001, /**< flip horizontally */
SDL_FLIP_VERTICAL = 0x00000002 /**< flip vertically */
} SDL_RendererFlip;
/**
* \brief A structure representing rendering state
*/
struct SDL_Renderer;
typedef struct SDL_Renderer SDL_Renderer;
/**
* \brief An efficient driver-specific representation of pixel data
*/
struct SDL_Texture;
typedef struct SDL_Texture SDL_Texture;
/* Function prototypes */
/**
* \brief Get the number of 2D rendering drivers available for the current
* display.
*
* A render driver is a set of code that handles rendering and texture
* management on a particular display. Normally there is only one, but
* some drivers may have several available with different capabilities.
*
* \sa SDL_GetRenderDriverInfo()
* \sa SDL_CreateRenderer()
*/
extern DECLSPEC int SDLCALL SDL_GetNumRenderDrivers(void);
/**
* \brief Get information about a specific 2D rendering driver for the current
* display.
*
* \param index The index of the driver to query information about.
* \param info A pointer to an SDL_RendererInfo struct to be filled with
* information on the rendering driver.
*
* \return 0 on success, -1 if the index was out of range.
*
* \sa SDL_CreateRenderer()
*/
extern DECLSPEC int SDLCALL SDL_GetRenderDriverInfo(int index,
SDL_RendererInfo * info);
/**
* \brief Create a window and default renderer
*
* \param width The width of the window
* \param height The height of the window
* \param window_flags The flags used to create the window
* \param window A pointer filled with the window, or NULL on error
* \param renderer A pointer filled with the renderer, or NULL on error
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_CreateWindowAndRenderer(
int width, int height, Uint32 window_flags,
SDL_Window **window, SDL_Renderer **renderer);
/**
* \brief Create a 2D rendering context for a window.
*
* \param window The window where rendering is displayed.
* \param index The index of the rendering driver to initialize, or -1 to
* initialize the first one supporting the requested flags.
* \param flags ::SDL_RendererFlags.
*
* \return A valid rendering context or NULL if there was an error.
*
* \sa SDL_CreateSoftwareRenderer()
* \sa SDL_GetRendererInfo()
* \sa SDL_DestroyRenderer()
*/
extern DECLSPEC SDL_Renderer * SDLCALL SDL_CreateRenderer(SDL_Window * window,
int index, Uint32 flags);
/**
* \brief Create a 2D software rendering context for a surface.
*
* \param surface The surface where rendering is done.
*
* \return A valid rendering context or NULL if there was an error.
*
* \sa SDL_CreateRenderer()
* \sa SDL_DestroyRenderer()
*/
extern DECLSPEC SDL_Renderer * SDLCALL SDL_CreateSoftwareRenderer(SDL_Surface * surface);
/**
* \brief Get the renderer associated with a window.
*/
extern DECLSPEC SDL_Renderer * SDLCALL SDL_GetRenderer(SDL_Window * window);
/**
* \brief Get information about a rendering context.
*/
extern DECLSPEC int SDLCALL SDL_GetRendererInfo(SDL_Renderer * renderer,
SDL_RendererInfo * info);
/**
* \brief Get the output size in pixels of a rendering context.
*/
extern DECLSPEC int SDLCALL SDL_GetRendererOutputSize(SDL_Renderer * renderer,
int *w, int *h);
/**
* \brief Create a texture for a rendering context.
*
* \param renderer The renderer.
* \param format The format of the texture.
* \param access One of the enumerated values in ::SDL_TextureAccess.
* \param w The width of the texture in pixels.
* \param h The height of the texture in pixels.
*
* \return The created texture is returned, or NULL if no rendering context was
* active, the format was unsupported, or the width or height were out
* of range.
*
* \note The contents of the texture are not defined at creation.
*
* \sa SDL_QueryTexture()
* \sa SDL_UpdateTexture()
* \sa SDL_DestroyTexture()
*/
extern DECLSPEC SDL_Texture * SDLCALL SDL_CreateTexture(SDL_Renderer * renderer,
Uint32 format,
int access, int w,
int h);
/**
* \brief Create a texture from an existing surface.
*
* \param renderer The renderer.
* \param surface The surface containing pixel data used to fill the texture.
*
* \return The created texture is returned, or NULL on error.
*
* \note The surface is not modified or freed by this function.
*
* \sa SDL_QueryTexture()
* \sa SDL_DestroyTexture()
*/
extern DECLSPEC SDL_Texture * SDLCALL SDL_CreateTextureFromSurface(SDL_Renderer * renderer, SDL_Surface * surface);
/**
* \brief Query the attributes of a texture
*
* \param texture A texture to be queried.
* \param format A pointer filled in with the raw format of the texture. The
* actual format may differ, but pixel transfers will use this
* format.
* \param access A pointer filled in with the actual access to the texture.
* \param w A pointer filled in with the width of the texture in pixels.
* \param h A pointer filled in with the height of the texture in pixels.
*
* \return 0 on success, or -1 if the texture is not valid.
*/
extern DECLSPEC int SDLCALL SDL_QueryTexture(SDL_Texture * texture,
Uint32 * format, int *access,
int *w, int *h);
/**
* \brief Set an additional color value used in render copy operations.
*
* \param texture The texture to update.
* \param r The red color value multiplied into copy operations.
* \param g The green color value multiplied into copy operations.
* \param b The blue color value multiplied into copy operations.
*
* \return 0 on success, or -1 if the texture is not valid or color modulation
* is not supported.
*
* \sa SDL_GetTextureColorMod()
*/
extern DECLSPEC int SDLCALL SDL_SetTextureColorMod(SDL_Texture * texture,
Uint8 r, Uint8 g, Uint8 b);
/**
* \brief Get the additional color value used in render copy operations.
*
* \param texture The texture to query.
* \param r A pointer filled in with the current red color value.
* \param g A pointer filled in with the current green color value.
* \param b A pointer filled in with the current blue color value.
*
* \return 0 on success, or -1 if the texture is not valid.
*
* \sa SDL_SetTextureColorMod()
*/
extern DECLSPEC int SDLCALL SDL_GetTextureColorMod(SDL_Texture * texture,
Uint8 * r, Uint8 * g,
Uint8 * b);
/**
* \brief Set an additional alpha value used in render copy operations.
*
* \param texture The texture to update.
* \param alpha The alpha value multiplied into copy operations.
*
* \return 0 on success, or -1 if the texture is not valid or alpha modulation
* is not supported.
*
* \sa SDL_GetTextureAlphaMod()
*/
extern DECLSPEC int SDLCALL SDL_SetTextureAlphaMod(SDL_Texture * texture,
Uint8 alpha);
/**
* \brief Get the additional alpha value used in render copy operations.
*
* \param texture The texture to query.
* \param alpha A pointer filled in with the current alpha value.
*
* \return 0 on success, or -1 if the texture is not valid.
*
* \sa SDL_SetTextureAlphaMod()
*/
extern DECLSPEC int SDLCALL SDL_GetTextureAlphaMod(SDL_Texture * texture,
Uint8 * alpha);
/**
* \brief Set the blend mode used for texture copy operations.
*
* \param texture The texture to update.
* \param blendMode ::SDL_BlendMode to use for texture blending.
*
* \return 0 on success, or -1 if the texture is not valid or the blend mode is
* not supported.
*
* \note If the blend mode is not supported, the closest supported mode is
* chosen.
*
* \sa SDL_GetTextureBlendMode()
*/
extern DECLSPEC int SDLCALL SDL_SetTextureBlendMode(SDL_Texture * texture,
SDL_BlendMode blendMode);
/**
* \brief Get the blend mode used for texture copy operations.
*
* \param texture The texture to query.
* \param blendMode A pointer filled in with the current blend mode.
*
* \return 0 on success, or -1 if the texture is not valid.
*
* \sa SDL_SetTextureBlendMode()
*/
extern DECLSPEC int SDLCALL SDL_GetTextureBlendMode(SDL_Texture * texture,
SDL_BlendMode *blendMode);
/**
* \brief Update the given texture rectangle with new pixel data.
*
* \param texture The texture to update
* \param rect A pointer to the rectangle of pixels to update, or NULL to
* update the entire texture.
* \param pixels The raw pixel data in the format of the texture.
* \param pitch The number of bytes in a row of pixel data, including padding between lines.
*
* The pixel data must be in the format of the texture. The pixel format can be
* queried with SDL_QueryTexture.
*
* \return 0 on success, or -1 if the texture is not valid.
*
* \note This is a fairly slow function.
*/
extern DECLSPEC int SDLCALL SDL_UpdateTexture(SDL_Texture * texture,
const SDL_Rect * rect,
const void *pixels, int pitch);
/**
* \brief Update a rectangle within a planar YV12 or IYUV texture with new pixel data.
*
* \param texture The texture to update
* \param rect A pointer to the rectangle of pixels to update, or NULL to
* update the entire texture.
* \param Yplane The raw pixel data for the Y plane.
* \param Ypitch The number of bytes between rows of pixel data for the Y plane.
* \param Uplane The raw pixel data for the U plane.
* \param Upitch The number of bytes between rows of pixel data for the U plane.
* \param Vplane The raw pixel data for the V plane.
* \param Vpitch The number of bytes between rows of pixel data for the V plane.
*
* \return 0 on success, or -1 if the texture is not valid.
*
* \note You can use SDL_UpdateTexture() as long as your pixel data is
* a contiguous block of Y and U/V planes in the proper order, but
* this function is available if your pixel data is not contiguous.
*/
extern DECLSPEC int SDLCALL SDL_UpdateYUVTexture(SDL_Texture * texture,
const SDL_Rect * rect,
const Uint8 *Yplane, int Ypitch,
const Uint8 *Uplane, int Upitch,
const Uint8 *Vplane, int Vpitch);
/**
* \brief Lock a portion of the texture for write-only pixel access.
*
* \param texture The texture to lock for access, which was created with
* ::SDL_TEXTUREACCESS_STREAMING.
* \param rect A pointer to the rectangle to lock for access. If the rect
* is NULL, the entire texture will be locked.
* \param pixels This is filled in with a pointer to the locked pixels,
* appropriately offset by the locked area.
* \param pitch This is filled in with the pitch of the locked pixels.
*
* \return 0 on success, or -1 if the texture is not valid or was not created with ::SDL_TEXTUREACCESS_STREAMING.
*
* \sa SDL_UnlockTexture()
*/
extern DECLSPEC int SDLCALL SDL_LockTexture(SDL_Texture * texture,
const SDL_Rect * rect,
void **pixels, int *pitch);
/**
* \brief Unlock a texture, uploading the changes to video memory, if needed.
*
* \sa SDL_LockTexture()
*/
extern DECLSPEC void SDLCALL SDL_UnlockTexture(SDL_Texture * texture);
/**
* \brief Determines whether a window supports the use of render targets
*
* \param renderer The renderer that will be checked
*
* \return SDL_TRUE if supported, SDL_FALSE if not.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_RenderTargetSupported(SDL_Renderer *renderer);
/**
* \brief Set a texture as the current rendering target.
*
* \param renderer The renderer.
* \param texture The targeted texture, which must be created with the SDL_TEXTUREACCESS_TARGET flag, or NULL for the default render target
*
* \return 0 on success, or -1 on error
*
* \sa SDL_GetRenderTarget()
*/
extern DECLSPEC int SDLCALL SDL_SetRenderTarget(SDL_Renderer *renderer,
SDL_Texture *texture);
/**
* \brief Get the current render target or NULL for the default render target.
*
* \return The current render target
*
* \sa SDL_SetRenderTarget()
*/
extern DECLSPEC SDL_Texture * SDLCALL SDL_GetRenderTarget(SDL_Renderer *renderer);
/**
* \brief Set device independent resolution for rendering
*
* \param renderer The renderer for which resolution should be set.
* \param w The width of the logical resolution
* \param h The height of the logical resolution
*
* This function uses the viewport and scaling functionality to allow a fixed logical
* resolution for rendering, regardless of the actual output resolution. If the actual
* output resolution doesn't have the same aspect ratio the output rendering will be
* centered within the output display.
*
* If the output display is a window, mouse events in the window will be filtered
* and scaled so they seem to arrive within the logical resolution.
*
* \note If this function results in scaling or subpixel drawing by the
* rendering backend, it will be handled using the appropriate
* quality hints.
*
* \sa SDL_RenderGetLogicalSize()
* \sa SDL_RenderSetScale()
* \sa SDL_RenderSetViewport()
*/
extern DECLSPEC int SDLCALL SDL_RenderSetLogicalSize(SDL_Renderer * renderer, int w, int h);
/**
* \brief Get device independent resolution for rendering
*
* \param renderer The renderer from which resolution should be queried.
* \param w A pointer filled with the width of the logical resolution
* \param h A pointer filled with the height of the logical resolution
*
* \sa SDL_RenderSetLogicalSize()
*/
extern DECLSPEC void SDLCALL SDL_RenderGetLogicalSize(SDL_Renderer * renderer, int *w, int *h);
/**
* \brief Set whether to force integer scales for resolution-independent rendering
*
* \param renderer The renderer for which integer scaling should be set.
* \param enable Enable or disable integer scaling
*
* This function restricts the logical viewport to integer values - that is, when
* a resolution is between two multiples of a logical size, the viewport size is
* rounded down to the lower multiple.
*
* \sa SDL_RenderSetLogicalSize()
*/
extern DECLSPEC int SDLCALL SDL_RenderSetIntegerScale(SDL_Renderer * renderer,
SDL_bool enable);
/**
* \brief Get whether integer scales are forced for resolution-independent rendering
*
* \param renderer The renderer from which integer scaling should be queried.
*
* \sa SDL_RenderSetIntegerScale()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_RenderGetIntegerScale(SDL_Renderer * renderer);
/**
* \brief Set the drawing area for rendering on the current target.
*
* \param renderer The renderer for which the drawing area should be set.
* \param rect The rectangle representing the drawing area, or NULL to set the viewport to the entire target.
*
* The x,y of the viewport rect represents the origin for rendering.
*
* \return 0 on success, or -1 on error
*
* \note If the window associated with the renderer is resized, the viewport is automatically reset.
*
* \sa SDL_RenderGetViewport()
* \sa SDL_RenderSetLogicalSize()
*/
extern DECLSPEC int SDLCALL SDL_RenderSetViewport(SDL_Renderer * renderer,
const SDL_Rect * rect);
/**
* \brief Get the drawing area for the current target.
*
* \sa SDL_RenderSetViewport()
*/
extern DECLSPEC void SDLCALL SDL_RenderGetViewport(SDL_Renderer * renderer,
SDL_Rect * rect);
/**
* \brief Set the clip rectangle for the current target.
*
* \param renderer The renderer for which clip rectangle should be set.
* \param rect A pointer to the rectangle to set as the clip rectangle, or
* NULL to disable clipping.
*
* \return 0 on success, or -1 on error
*
* \sa SDL_RenderGetClipRect()
*/
extern DECLSPEC int SDLCALL SDL_RenderSetClipRect(SDL_Renderer * renderer,
const SDL_Rect * rect);
/**
* \brief Get the clip rectangle for the current target.
*
* \param renderer The renderer from which clip rectangle should be queried.
* \param rect A pointer filled in with the current clip rectangle, or
* an empty rectangle if clipping is disabled.
*
* \sa SDL_RenderSetClipRect()
*/
extern DECLSPEC void SDLCALL SDL_RenderGetClipRect(SDL_Renderer * renderer,
SDL_Rect * rect);
/**
* \brief Get whether clipping is enabled on the given renderer.
*
* \param renderer The renderer from which clip state should be queried.
*
* \sa SDL_RenderGetClipRect()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_RenderIsClipEnabled(SDL_Renderer * renderer);
/**
* \brief Set the drawing scale for rendering on the current target.
*
* \param renderer The renderer for which the drawing scale should be set.
* \param scaleX The horizontal scaling factor
* \param scaleY The vertical scaling factor
*
* The drawing coordinates are scaled by the x/y scaling factors
* before they are used by the renderer. This allows resolution
* independent drawing with a single coordinate system.
*
* \note If this results in scaling or subpixel drawing by the
* rendering backend, it will be handled using the appropriate
* quality hints. For best results use integer scaling factors.
*
* \sa SDL_RenderGetScale()
* \sa SDL_RenderSetLogicalSize()
*/
extern DECLSPEC int SDLCALL SDL_RenderSetScale(SDL_Renderer * renderer,
float scaleX, float scaleY);
/**
* \brief Get the drawing scale for the current target.
*
* \param renderer The renderer from which drawing scale should be queried.
* \param scaleX A pointer filled in with the horizontal scaling factor
* \param scaleY A pointer filled in with the vertical scaling factor
*
* \sa SDL_RenderSetScale()
*/
extern DECLSPEC void SDLCALL SDL_RenderGetScale(SDL_Renderer * renderer,
float *scaleX, float *scaleY);
/**
* \brief Set the color used for drawing operations (Rect, Line and Clear).
*
* \param renderer The renderer for which drawing color should be set.
* \param r The red value used to draw on the rendering target.
* \param g The green value used to draw on the rendering target.
* \param b The blue value used to draw on the rendering target.
* \param a The alpha value used to draw on the rendering target, usually
* ::SDL_ALPHA_OPAQUE (255).
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_SetRenderDrawColor(SDL_Renderer * renderer,
Uint8 r, Uint8 g, Uint8 b,
Uint8 a);
/**
* \brief Get the color used for drawing operations (Rect, Line and Clear).
*
* \param renderer The renderer from which drawing color should be queried.
* \param r A pointer to the red value used to draw on the rendering target.
* \param g A pointer to the green value used to draw on the rendering target.
* \param b A pointer to the blue value used to draw on the rendering target.
* \param a A pointer to the alpha value used to draw on the rendering target,
* usually ::SDL_ALPHA_OPAQUE (255).
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_GetRenderDrawColor(SDL_Renderer * renderer,
Uint8 * r, Uint8 * g, Uint8 * b,
Uint8 * a);
/**
* \brief Set the blend mode used for drawing operations (Fill and Line).
*
* \param renderer The renderer for which blend mode should be set.
* \param blendMode ::SDL_BlendMode to use for blending.
*
* \return 0 on success, or -1 on error
*
* \note If the blend mode is not supported, the closest supported mode is
* chosen.
*
* \sa SDL_GetRenderDrawBlendMode()
*/
extern DECLSPEC int SDLCALL SDL_SetRenderDrawBlendMode(SDL_Renderer * renderer,
SDL_BlendMode blendMode);
/**
* \brief Get the blend mode used for drawing operations.
*
* \param renderer The renderer from which blend mode should be queried.
* \param blendMode A pointer filled in with the current blend mode.
*
* \return 0 on success, or -1 on error
*
* \sa SDL_SetRenderDrawBlendMode()
*/
extern DECLSPEC int SDLCALL SDL_GetRenderDrawBlendMode(SDL_Renderer * renderer,
SDL_BlendMode *blendMode);
/**
* \brief Clear the current rendering target with the drawing color
*
* This function clears the entire rendering target, ignoring the viewport and
* the clip rectangle.
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_RenderClear(SDL_Renderer * renderer);
/**
* \brief Draw a point on the current rendering target.
*
* \param renderer The renderer which should draw a point.
* \param x The x coordinate of the point.
* \param y The y coordinate of the point.
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_RenderDrawPoint(SDL_Renderer * renderer,
int x, int y);
/**
* \brief Draw multiple points on the current rendering target.
*
* \param renderer The renderer which should draw multiple points.
* \param points The points to draw
* \param count The number of points to draw
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_RenderDrawPoints(SDL_Renderer * renderer,
const SDL_Point * points,
int count);
/**
* \brief Draw a line on the current rendering target.
*
* \param renderer The renderer which should draw a line.
* \param x1 The x coordinate of the start point.
* \param y1 The y coordinate of the start point.
* \param x2 The x coordinate of the end point.
* \param y2 The y coordinate of the end point.
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_RenderDrawLine(SDL_Renderer * renderer,
int x1, int y1, int x2, int y2);
/**
* \brief Draw a series of connected lines on the current rendering target.
*
* \param renderer The renderer which should draw multiple lines.
* \param points The points along the lines
* \param count The number of points, drawing count-1 lines
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_RenderDrawLines(SDL_Renderer * renderer,
const SDL_Point * points,
int count);
/**
* \brief Draw a rectangle on the current rendering target.
*
* \param renderer The renderer which should draw a rectangle.
* \param rect A pointer to the destination rectangle, or NULL to outline the entire rendering target.
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_RenderDrawRect(SDL_Renderer * renderer,
const SDL_Rect * rect);
/**
* \brief Draw some number of rectangles on the current rendering target.
*
* \param renderer The renderer which should draw multiple rectangles.
* \param rects A pointer to an array of destination rectangles.
* \param count The number of rectangles.
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_RenderDrawRects(SDL_Renderer * renderer,
const SDL_Rect * rects,
int count);
/**
* \brief Fill a rectangle on the current rendering target with the drawing color.
*
* \param renderer The renderer which should fill a rectangle.
* \param rect A pointer to the destination rectangle, or NULL for the entire
* rendering target.
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_RenderFillRect(SDL_Renderer * renderer,
const SDL_Rect * rect);
/**
* \brief Fill some number of rectangles on the current rendering target with the drawing color.
*
* \param renderer The renderer which should fill multiple rectangles.
* \param rects A pointer to an array of destination rectangles.
* \param count The number of rectangles.
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_RenderFillRects(SDL_Renderer * renderer,
const SDL_Rect * rects,
int count);
/**
* \brief Copy a portion of the texture to the current rendering target.
*
* \param renderer The renderer which should copy parts of a texture.
* \param texture The source texture.
* \param srcrect A pointer to the source rectangle, or NULL for the entire
* texture.
* \param dstrect A pointer to the destination rectangle, or NULL for the
* entire rendering target.
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_RenderCopy(SDL_Renderer * renderer,
SDL_Texture * texture,
const SDL_Rect * srcrect,
const SDL_Rect * dstrect);
/**
* \brief Copy a portion of the source texture to the current rendering target, rotating it by angle around the given center
*
* \param renderer The renderer which should copy parts of a texture.
* \param texture The source texture.
* \param srcrect A pointer to the source rectangle, or NULL for the entire
* texture.
* \param dstrect A pointer to the destination rectangle, or NULL for the
* entire rendering target.
* \param angle An angle in degrees that indicates the rotation that will be applied to dstrect, rotating it in a clockwise direction
* \param center A pointer to a point indicating the point around which dstrect will be rotated (if NULL, rotation will be done around dstrect.w/2, dstrect.h/2).
* \param flip An SDL_RendererFlip value stating which flipping actions should be performed on the texture
*
* \return 0 on success, or -1 on error
*/
extern DECLSPEC int SDLCALL SDL_RenderCopyEx(SDL_Renderer * renderer,
SDL_Texture * texture,
const SDL_Rect * srcrect,
const SDL_Rect * dstrect,
const double angle,
const SDL_Point *center,
const SDL_RendererFlip flip);
/**
* \brief Read pixels from the current rendering target.
*
* \param renderer The renderer from which pixels should be read.
* \param rect A pointer to the rectangle to read, or NULL for the entire
* render target.
* \param format The desired format of the pixel data, or 0 to use the format
* of the rendering target
* \param pixels A pointer to be filled in with the pixel data
* \param pitch The pitch of the pixels parameter.
*
* \return 0 on success, or -1 if pixel reading is not supported.
*
* \warning This is a very slow operation, and should not be used frequently.
*/
extern DECLSPEC int SDLCALL SDL_RenderReadPixels(SDL_Renderer * renderer,
const SDL_Rect * rect,
Uint32 format,
void *pixels, int pitch);
/**
* \brief Update the screen with rendering performed.
*/
extern DECLSPEC void SDLCALL SDL_RenderPresent(SDL_Renderer * renderer);
/**
* \brief Destroy the specified texture.
*
* \sa SDL_CreateTexture()
* \sa SDL_CreateTextureFromSurface()
*/
extern DECLSPEC void SDLCALL SDL_DestroyTexture(SDL_Texture * texture);
/**
* \brief Destroy the rendering context for a window and free associated
* textures.
*
* \sa SDL_CreateRenderer()
*/
extern DECLSPEC void SDLCALL SDL_DestroyRenderer(SDL_Renderer * renderer);
/**
* \brief Bind the texture to the current OpenGL/ES/ES2 context for use with
* OpenGL instructions.
*
* \param texture The SDL texture to bind
* \param texw A pointer to a float that will be filled with the texture width
* \param texh A pointer to a float that will be filled with the texture height
*
* \return 0 on success, or -1 if the operation is not supported
*/
extern DECLSPEC int SDLCALL SDL_GL_BindTexture(SDL_Texture *texture, float *texw, float *texh);
/**
* \brief Unbind a texture from the current OpenGL/ES/ES2 context.
*
* \param texture The SDL texture to unbind
*
* \return 0 on success, or -1 if the operation is not supported
*/
extern DECLSPEC int SDLCALL SDL_GL_UnbindTexture(SDL_Texture *texture);
/**
* \brief Get the CAMetalLayer associated with the given Metal renderer
*
* \param renderer The renderer to query
*
* \return CAMetalLayer* on success, or NULL if the renderer isn't a Metal renderer
*
* \sa SDL_RenderGetMetalCommandEncoder()
*/
extern DECLSPEC void *SDLCALL SDL_RenderGetMetalLayer(SDL_Renderer * renderer);
/**
* \brief Get the Metal command encoder for the current frame
*
* \param renderer The renderer to query
*
* \return id<MTLRenderCommandEncoder> on success, or NULL if the renderer isn't a Metal renderer
*
* \sa SDL_RenderGetMetalLayer()
*/
extern DECLSPEC void *SDLCALL SDL_RenderGetMetalCommandEncoder(SDL_Renderer * renderer);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_render_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 35,405 | C | 36.98927 | 164 | 0.64361 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/semu/xr/openxr/openxr.py | from typing import Union, Callable
import os
import sys
import ctypes
import cv2
import numpy
import numpy as np
if __name__ != "__main__":
import pxr
import omni
from pxr import UsdGeom, Gf, Usd
from omni.syntheticdata import sensors, _syntheticdata
else:
class pxr:
class Gf:
Vec3d = lambda x,y,z: (x,y,z)
Quatd = lambda w,x,y,z: (w,x,y,z)
class Usd:
Prim = None
class UsdGeom:
pass
class Sdf:
Path = None
Gf = pxr.Gf
# constants
XR_KHR_OPENGL_ENABLE_EXTENSION_NAME = "XR_KHR_opengl_enable"
XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME = "XR_KHR_opengl_es_enable"
XR_KHR_VULKAN_ENABLE_EXTENSION_NAME = "XR_KHR_vulkan_enable"
XR_KHR_D3D11_ENABLE_EXTENSION_NAME = "XR_KHR_D3D11_enable"
XR_KHR_D3D12_ENABLE_EXTENSION_NAME = "XR_KHR_D3D12_enable"
XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY = 1
XR_FORM_FACTOR_HANDHELD_DISPLAY = 2
XR_ENVIRONMENT_BLEND_MODE_OPAQUE = 1
XR_ENVIRONMENT_BLEND_MODE_ADDITIVE = 2
XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND = 3
XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO = 1
XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO = 2
XR_REFERENCE_SPACE_TYPE_VIEW = 1 # +Y up, +X to the right, and -Z forward
XR_REFERENCE_SPACE_TYPE_LOCAL = 2 # +Y up, +X to the right, and -Z forward
XR_REFERENCE_SPACE_TYPE_STAGE = 3 # +Y up, and the X and Z axes aligned with the rectangle edges
XR_ACTION_TYPE_BOOLEAN_INPUT = 1
XR_ACTION_TYPE_FLOAT_INPUT = 2
XR_ACTION_TYPE_VECTOR2F_INPUT = 3
XR_ACTION_TYPE_POSE_INPUT = 4
XR_ACTION_TYPE_VIBRATION_OUTPUT = 100
XR_NO_DURATION = 0
XR_INFINITE_DURATION = 2**32
XR_MIN_HAPTIC_DURATION = -1
XR_FREQUENCY_UNSPECIFIED = 0
def acquire_openxr_interface(disable_openxr: bool = False):
return OpenXR(disable_openxr)
def release_openxr_interface(xr):
if xr is not None:
xr.destroy()
xr = None
# structures (ctypes)
XrActionType = ctypes.c_int
XrStructureType = ctypes.c_int
class XrQuaternionf(ctypes.Structure):
_fields_ = [('x', ctypes.c_float), ('y', ctypes.c_float), ('z', ctypes.c_float), ('w', ctypes.c_float)]
class XrVector3f(ctypes.Structure):
_fields_ = [('x', ctypes.c_float), ('y', ctypes.c_float), ('z', ctypes.c_float)]
class XrPosef(ctypes.Structure):
_fields_ = [('orientation', XrQuaternionf), ('position', XrVector3f)]
class XrFovf(ctypes.Structure):
_fields_ = _fields_ = [('angleLeft', ctypes.c_float), ('angleRight', ctypes.c_float), ('angleUp', ctypes.c_float), ('angleDown', ctypes.c_float)]
class XrView(ctypes.Structure):
_fields_ = [('type', XrStructureType), ('next', ctypes.c_void_p), ('pose', XrPosef), ('fov', XrFovf)]
class XrViewConfigurationView(ctypes.Structure):
_fields_ = [('type', XrStructureType), ('next', ctypes.c_void_p),
('recommendedImageRectWidth', ctypes.c_uint32), ('maxImageRectWidth', ctypes.c_uint32),
('recommendedImageRectHeight', ctypes.c_uint32), ('maxImageRectHeight', ctypes.c_uint32),
('recommendedSwapchainSampleCount', ctypes.c_uint32), ('maxSwapchainSampleCount', ctypes.c_uint32)]
class ActionState(ctypes.Structure):
_fields_ = [('type', XrActionType),
('path', ctypes.c_char_p),
('isActive', ctypes.c_bool),
('stateBool', ctypes.c_bool),
('stateFloat', ctypes.c_float),
('stateVectorX', ctypes.c_float),
('stateVectorY', ctypes.c_float)]
class ActionPoseState(ctypes.Structure):
_fields_ = [('type', XrActionType),
('path', ctypes.c_char_p),
('isActive', ctypes.c_bool),
('pose', XrPosef)]
class OpenXR:
def __init__(self, disable_openxr: bool = False) -> None:
self._disable_openxr = disable_openxr
if self._disable_openxr:
print("[WARNING] Extension launched with OpenXR support disabled")
self._lib = None
self._app = None
self._graphics = None
self._use_ctypes = False
# views
self._prim_left = None
self._prim_right = None
self._frame_left = None
self._frame_right = None
self._viewport_window_left = None
self._viewport_window_right = None
self._meters_per_unit = 1.0
self._reference_position = Gf.Vec3d(0, 0, 0)
self._reference_rotation = Gf.Vec3d(0, 0, 0)
self._rectification_quat_left = Gf.Quatd(1, 0, 0, 0)
self._rectification_quat_right = Gf.Quatd(1, 0, 0, 0)
self._viewport_interface = None
self._transform_fit = None
self._transform_flip = None
# callbacks
self._callback_action_events = {}
self._callback_action_pose_events = {}
self._callback_middle_render = None
self._callback_render = None
def init(self, graphics: str = "OpenGL", use_ctypes: bool = False) -> bool:
"""
Init OpenXR application by loading the related libraries
Parameters
----------
graphics: str
OpenXR graphics API supported by the runtime (OpenGL, OpenGLES, Vulkan, D3D11, D3D12).
Note: At the moment only OpenGL is available
use_ctypes: bool, optional
If true, use ctypes as C/C++ interface instead of pybind11 (default)
Returns
-------
bool
True if initialization was successful, otherwise False
"""
# get viewport interface
try:
self._viewport_interface = omni.kit.viewport.get_viewport_interface()
except Exception as e:
print("[INFO] Using legacy viewport interface")
self._viewport_interface = omni.kit.viewport_legacy.get_viewport_interface()
# TODO: what about no graphic API (only controllers for example)?
self._use_ctypes = use_ctypes
# graphics API
if graphics in ["OpenGL", XR_KHR_OPENGL_ENABLE_EXTENSION_NAME]:
self._graphics = XR_KHR_OPENGL_ENABLE_EXTENSION_NAME
elif graphics in ["OpenGLES", XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME]:
self._graphics = XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME
raise NotImplementedError("OpenGLES graphics API is not implemented yet")
elif graphics in ["Vulkan", XR_KHR_VULKAN_ENABLE_EXTENSION_NAME]:
self._graphics = XR_KHR_VULKAN_ENABLE_EXTENSION_NAME
raise NotImplementedError("Vulkan graphics API is not implemented yet")
elif graphics in ["D3D11", XR_KHR_D3D11_ENABLE_EXTENSION_NAME]:
self._graphics = XR_KHR_D3D11_ENABLE_EXTENSION_NAME
raise NotImplementedError("D3D11 graphics API is not implemented yet")
elif graphics in ["D3D12", XR_KHR_D3D12_ENABLE_EXTENSION_NAME]:
self._graphics = XR_KHR_D3D12_ENABLE_EXTENSION_NAME
raise NotImplementedError("D3D12 graphics API is not implemented yet")
else:
raise ValueError("Invalid graphics API ({}). Valid graphics APIs are OpenGL, OpenGLES, Vulkan, D3D11, D3D12".format(graphics))
# libraries path
if __name__ == "__main__":
extension_path = os.getcwd()[:os.getcwd().find("/semu/xr/openxr")]
else:
extension_path = __file__[:__file__.find("/semu/xr/openxr")]
if self._disable_openxr:
return True
try:
# ctypes
if self._use_ctypes:
ctypes.PyDLL(os.path.join(extension_path, "bin", "libGL.so"), mode = ctypes.RTLD_GLOBAL)
ctypes.PyDLL(os.path.join(extension_path, "bin", "libSDL2.so"), mode = ctypes.RTLD_GLOBAL)
ctypes.PyDLL(os.path.join(extension_path, "bin", "libopenxr_loader.so"), mode = ctypes.RTLD_GLOBAL)
self._lib = ctypes.PyDLL(os.path.join(extension_path, "bin", "xrlib_c.so"), mode = ctypes.RTLD_GLOBAL)
self._app = self._lib.openXrApplication()
print("[INFO] OpenXR initialized using ctypes interface")
# pybind11
else:
sys.setdlopenflags(os.RTLD_GLOBAL | os.RTLD_LAZY)
sys.path.append(os.path.join(extension_path, "bin"))
# change cwd
tmp_dir= os.getcwd()
os.chdir(extension_path)
#import library
import xrlib_p
#restore cwd
os.chdir(tmp_dir)
self._lib = xrlib_p
self._app = xrlib_p.OpenXrApplication()
print("[INFO] OpenXR initialized using pybind11 interface")
except Exception as e:
print("[ERROR] OpenXR initialization:", e)
return False
return True
def destroy(self) -> bool:
"""
Destroy OpenXR application
Returns
-------
bool
True if destruction was successful, otherwise False
"""
if self._app is not None:
if self._use_ctypes:
return bool(self._lib.destroy(self._app))
else:
return self._app.destroy()
self._lib = None
self._app = None
return True
def is_session_running(self) -> bool:
"""
OpenXR session's running status
Returns
-------
bool
Return True if the OpenXR session is running, False otherwise
"""
if self._disable_openxr:
return True
if self._use_ctypes:
return bool(self._lib.isSessionRunning(self._app))
else:
return self._app.isSessionRunning()
def create_instance(self, application_name: str = "Omniverse (XR)", engine_name: str = "", api_layers: list = [], extensions: list = []) -> bool:
"""
Create an OpenXR instance to allow communication with an OpenXR runtime
OpenXR internal function calls:
- xrEnumerateApiLayerProperties
- xrEnumerateInstanceExtensionProperties
- xrCreateInstance
Parameters
----------
application_name: str, optional
Name of the OpenXR application (default: 'Omniverse (VR)')
engine_name: str, optional
Name of the engine (if any) used to create the application (empty by default)
api_layers: list of str, optional
[API layers](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#api-layers) to be inserted between the OpenXR application and the runtime implementation.
extensions: list of str, optional
[Extensions](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#extensions) to be loaded.
Note: At the moment only the graphic extensions are configured.
Note: The graphics API selected during initialization (init) is automatically included in the extensions to be loaded.
Returns
-------
bool
True if the instance has been created successfully, otherwise False
"""
if self._disable_openxr:
return True
if self._graphics not in extensions:
extensions += [self._graphics]
if self._use_ctypes:
# format API layes
requested_api_layers = (ctypes.c_char_p * len(api_layers))()
requested_api_layers[:] = [layer.encode('utf-8') for layer in api_layers]
# format extensions
requested_extensions = (ctypes.c_char_p * len(extensions))()
requested_extensions[:] = [extension.encode('utf-8') for extension in extensions]
return bool(self._lib.createInstance(self._app,
ctypes.create_string_buffer(application_name.encode('utf-8')),
ctypes.create_string_buffer(engine_name.encode('utf-8')),
requested_api_layers,
len(api_layers),
requested_extensions,
len(extensions)))
else:
return self._app.createInstance(application_name, engine_name, api_layers, extensions)
def get_system(self, form_factor: int = 1, blend_mode: int = 1, view_configuration_type: int = 2) -> bool:
"""
Obtain the system represented by a collection of related devices at runtime
OpenXR internal function calls:
- xrGetSystem
- xrGetInstanceProperties
- xrGetSystemProperties
- xrEnumerateViewConfigurations
- xrGetViewConfigurationProperties
- xrEnumerateViewConfigurationViews
- xrEnumerateEnvironmentBlendModes
- xrCreateActionSet (actionSetName: 'actionset', localizedActionSetName: 'localized_actionset')
Parameters
----------
form_factor: {XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY, XR_FORM_FACTOR_HANDHELD_DISPLAY}, optional
Desired [form factor](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#form_factor_description) from XrFormFactor enum (default: XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY)
blend_mode: {XR_ENVIRONMENT_BLEND_MODE_OPAQUE, XR_ENVIRONMENT_BLEND_MODE_ADDITIVE, XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND}, optional
Desired environment [blend mode](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#environment_blend_mode) from XrEnvironmentBlendMode enum (default: XR_ENVIRONMENT_BLEND_MODE_OPAQUE)
view_configuration_type: {XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO}, optional
Primary [view configuration](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#view_configurations) type from XrViewConfigurationType enum (default: XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO)
Returns
-------
bool
True if the system has been obtained successfully, otherwise False
"""
# check form_factor
if not form_factor in [XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY, XR_FORM_FACTOR_HANDHELD_DISPLAY]:
raise ValueError("Invalid form factor ({}). Valid form factors are XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY ({}), XR_FORM_FACTOR_HANDHELD_DISPLAY ({})" \
.format(form_factor, XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY, XR_FORM_FACTOR_HANDHELD_DISPLAY))
# check blend_mode
if not blend_mode in [XR_ENVIRONMENT_BLEND_MODE_OPAQUE, XR_ENVIRONMENT_BLEND_MODE_ADDITIVE, XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND]:
raise ValueError("Invalid blend mode ({}). Valid blend modes are XR_ENVIRONMENT_BLEND_MODE_OPAQUE ({}), XR_ENVIRONMENT_BLEND_MODE_ADDITIVE ({}), XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND ({})" \
.format(blend_mode, XR_ENVIRONMENT_BLEND_MODE_OPAQUE, XR_ENVIRONMENT_BLEND_MODE_ADDITIVE, XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND))
# check view_configuration_type
if not view_configuration_type in [XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO]:
raise ValueError("Invalid view configuration type ({}). Valid view configuration types are XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO ({}), XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO ({})" \
.format(view_configuration_type, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO))
if self._disable_openxr:
return True
if self._use_ctypes:
return bool(self._lib.getSystem(self._app, form_factor, blend_mode, view_configuration_type))
else:
return self._app.getSystem(form_factor, blend_mode, view_configuration_type)
def create_session(self) -> bool:
"""
Create an OpenXR session that represents an application's intention to display XR content
OpenXR internal function calls:
- xrCreateSession
- xrEnumerateReferenceSpaces
- xrCreateReferenceSpace
- xrGetReferenceSpaceBoundsRect
- xrSuggestInteractionProfileBindings
- xrAttachSessionActionSets
- xrCreateActionSpace
- xrEnumerateSwapchainFormats
- xrCreateSwapchain
- xrEnumerateSwapchainImages
Returns
-------
bool
True if the session has been created successfully, otherwise False
"""
if self._disable_openxr:
return True
if self._use_ctypes:
return bool(self._lib.createSession(self._app))
else:
return self._app.createSession()
def poll_events(self) -> bool:
"""
[Event polling](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#event-polling) and processing
OpenXR internal function calls:
- xrPollEvent
- xrBeginSession
- xrEndSession
Returns
-------
bool
False if the running session needs to end (due to the user closing or switching the application, etc.), otherwise False
"""
if self._disable_openxr:
return True
if self._use_ctypes:
exit_loop = ctypes.c_bool(False)
result = bool(self._lib.pollEvents(self._app, ctypes.byref(exit_loop)))
return result and not exit_loop.value
else:
result = self._app.pollEvents()
return result[0] and not result[1]
def poll_actions(self) -> bool:
"""
[Action](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_action_overview) polling
OpenXR internal function calls:
- xrSyncActions
- xrGetActionStateBoolean
- xrGetActionStateFloat
- xrGetActionStateVector2f
- xrGetActionStatePose
Returns
-------
bool
True if there is no error during polling, otherwise False
"""
if self._disable_openxr:
return True
if self._use_ctypes:
requested_action_states = (ActionState * len(self._callback_action_events.keys()))()
result = bool(self._lib.pollActions(self._app, requested_action_states, len(requested_action_states)))
for state in requested_action_states:
value = None
if not state.type:
break
if state.type == XR_ACTION_TYPE_BOOLEAN_INPUT:
value = state.stateBool
elif state.type == XR_ACTION_TYPE_FLOAT_INPUT:
value = state.stateFloat
elif state.type == XR_ACTION_TYPE_VECTOR2F_INPUT:
value = (state.stateVectorX, state.stateVectorY)
elif state.type == XR_ACTION_TYPE_POSE_INPUT:
continue
elif state.type == XR_ACTION_TYPE_VIBRATION_OUTPUT:
continue
self._callback_action_events[state.path.decode("utf-8")](state.path.decode("utf-8"), value)
return result
else:
result = self._app.pollActions()
for state in result[1]:
value = None
if state["type"] == XR_ACTION_TYPE_BOOLEAN_INPUT:
value = state["stateBool"]
elif state["type"] == XR_ACTION_TYPE_FLOAT_INPUT:
value = state["stateFloat"]
elif state["type"] == XR_ACTION_TYPE_VECTOR2F_INPUT:
value = (state["stateVectorX"], state["stateVectorY"])
elif state["type"] == XR_ACTION_TYPE_POSE_INPUT:
continue
elif state["type"] == XR_ACTION_TYPE_VIBRATION_OUTPUT:
continue
self._callback_action_events[state["path"]](state["path"], value)
return result[0]
def render_views(self, reference_space: int = 2) -> bool:
"""
Present rendered images to the user's views according to the selected reference space
OpenXR internal function calls:
- xrWaitFrame
- xrBeginFrame
- xrLocateSpace
- xrLocateViews
- xrAcquireSwapchainImage
- xrWaitSwapchainImage
- xrReleaseSwapchainImage
- xrEndFrame
Parameters
----------
reference_space: {XR_REFERENCE_SPACE_TYPE_VIEW, XR_REFERENCE_SPACE_TYPE_LOCAL, XR_REFERENCE_SPACE_TYPE_STAGE}, optional
Desired [reference space](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#reference-spaces) type from XrReferenceSpaceType enum used to render the images (default: XR_REFERENCE_SPACE_TYPE_LOCAL)
Returns
-------
bool
True if there is no error during rendering, otherwise False
"""
if self._callback_render is None:
print("[INFO] No callback has been established for rendering events. Internal callback will be used")
self.subscribe_render_event()
if self._disable_openxr:
# test sensor reading
if self._viewport_window_left is not None:
frame_left = sensors.get_rgb(self._viewport_window_left)
cv2.imshow("frame_left {}".format(frame_left.shape), frame_left)
cv2.waitKey(1)
if self._viewport_window_right is not None:
frame_right = sensors.get_rgb(self._viewport_window_right)
cv2.imshow("frame_right {}".format(frame_right.shape), frame_right)
cv2.waitKey(1)
return True
if self._use_ctypes:
requested_action_pose_states = (ActionPoseState * len(self._callback_action_pose_events.keys()))()
result = bool(self._lib.renderViews(self._app, reference_space, requested_action_pose_states, len(requested_action_pose_states)))
for state in requested_action_pose_states:
value = None
if state.type == XR_ACTION_TYPE_POSE_INPUT and state.isActive:
value = (Gf.Vec3d(state.pose.position.x, -state.pose.position.z, state.pose.position.y) / self._meters_per_unit,
Gf.Quatd(state.pose.orientation.w, state.pose.orientation.x, state.pose.orientation.y, state.pose.orientation.z))
self._callback_action_pose_events[state.path.decode("utf-8")](state.path.decode("utf-8"), value)
return result
else:
result = self._app.renderViews(reference_space)
for state in result[1]:
value = None
if state["type"] == XR_ACTION_TYPE_POSE_INPUT and state["isActive"]:
value = (Gf.Vec3d(state["pose"]["position"]["x"], -state["pose"]["position"]["z"], state["pose"]["position"]["y"]) / self._meters_per_unit,
Gf.Quatd(state["pose"]["orientation"]["w"], state["pose"]["orientation"]["x"], state["pose"]["orientation"]["y"], state["pose"]["orientation"]["z"]))
self._callback_action_pose_events[state["path"]](state["path"], value)
return result[0]
# action utilities
def subscribe_action_event(self, path: str, callback: Union[Callable[[str, object], None], None] = None, action_type: Union[int, None] = None, reference_space: Union[int, None] = 2) -> bool:
"""
Create an action given a path and subscribe a callback function to the update event of this action
If action_type is None the action type will be automatically defined by parsing the last segment of the path according to the following policy:
- XR_ACTION_TYPE_BOOLEAN_INPUT: /click, /touch
- XR_ACTION_TYPE_FLOAT_INPUT: /value, /force
- XR_ACTION_TYPE_VECTOR2F_INPUT: /x, /y
- XR_ACTION_TYPE_POSE_INPUT: /pose
- XR_ACTION_TYPE_VIBRATION_OUTPUT: /haptic, /haptic_left, /haptic_right, /haptic_left_trigger, /haptic_right_trigger
The callback function (a callable object) should have only the following 2 parameters:
- path: str
The complete path (user path and subpath) of the action that invokes the callback
- value: bool, float, tuple(float, float), tuple(pxr.Gf.Vec3d, pxr.Gf.Quatd)
The current state of the action according to its type
- XR_ACTION_TYPE_BOOLEAN_INPUT: bool
- XR_ACTION_TYPE_FLOAT_INPUT: float
- XR_ACTION_TYPE_VECTOR2F_INPUT (x, y): tuple(float, float)
- XR_ACTION_TYPE_POSE_INPUT (position (in stage unit), rotation as quaternion): tuple(pxr.Gf.Vec3d, pxr.Gf.Quatd)
XR_ACTION_TYPE_VIBRATION_OUTPUT actions will not invoke their callback function. In this case the callback must be None
XR_ACTION_TYPE_POSE_INPUT also specifies, through the definition of the reference_space parameter, the reference space used to retrieve the pose
The collection of available paths corresponds to the following [interaction profiles](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-interaction-profiles):
- [Khronos Simple Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_khronos_simple_controller_profile)
- [Google Daydream Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_google_daydream_controller_profile)
- [HTC Vive Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_htc_vive_controller_profile)
- [HTC Vive Pro](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_htc_vive_pro_profile)
- [Microsoft Mixed Reality Motion Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_microsoft_mixed_reality_motion_controller_profile)
- [Microsoft Xbox Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_microsoft_xbox_controller_profile)
- [Oculus Go Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_oculus_go_controller_profile)
- [Oculus Touch Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_oculus_touch_controller_profile)
- [Valve Index Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_valve_index_controller_profile)
OpenXR internal function calls:
- xrCreateAction
Parameters
----------
path: str
Complete [path](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved) (user path and subpath) referring to the action
callback: callable object (2 parameters) or None for XR_ACTION_TYPE_VIBRATION_OUTPUT
Callback invoked when the state of the action changes
action_type: {XR_ACTION_TYPE_BOOLEAN_INPUT, XR_ACTION_TYPE_FLOAT_INPUT, XR_ACTION_TYPE_VECTOR2F_INPUT, XR_ACTION_TYPE_POSE_INPUT, XR_ACTION_TYPE_VIBRATION_OUTPUT} or None, optional
Action [type](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrActionType) from XrActionType enum (default: None)
reference_space: {XR_REFERENCE_SPACE_TYPE_VIEW, XR_REFERENCE_SPACE_TYPE_LOCAL, XR_REFERENCE_SPACE_TYPE_STAGE}, optional
Desired [reference space](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#reference-spaces) type from XrReferenceSpaceType enum used to retrieve the pose (default: XR_REFERENCE_SPACE_TYPE_LOCAL)
Returns
-------
bool
True if there is no error during action creation, otherwise False
"""
if action_type is None:
if path.split("/")[-1] in ["click", "touch"]:
action_type = XR_ACTION_TYPE_BOOLEAN_INPUT
elif path.split("/")[-1] in ["value", "force"]:
action_type = XR_ACTION_TYPE_FLOAT_INPUT
elif path.split("/")[-1] in ["x", "y"]:
action_type = XR_ACTION_TYPE_VECTOR2F_INPUT
elif path.split("/")[-1] in ["pose"]:
action_type = XR_ACTION_TYPE_POSE_INPUT
elif path.split("/")[-1] in ["haptic", "haptic_left", "haptic_right", "haptic_left_trigger", "haptic_right_trigger"]:
action_type = XR_ACTION_TYPE_VIBRATION_OUTPUT
else:
raise ValueError("The action type cannot be retrieved from the path {}".format(path))
if callback is None and action_type != XR_ACTION_TYPE_VIBRATION_OUTPUT:
raise ValueError("The callback was not defined")
self._callback_action_events[path] = callback
if action_type == XR_ACTION_TYPE_POSE_INPUT:
self._callback_action_pose_events[path] = callback
if self._disable_openxr:
return True
if self._use_ctypes:
return bool(self._lib.addAction(self._app, ctypes.create_string_buffer(path.encode('utf-8')), action_type, reference_space))
else:
return self._app.addAction(path, action_type, reference_space)
def apply_haptic_feedback(self, path: str, haptic_feedback: dict = {}) -> bool:
"""
Apply a [haptic feedback](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_output_actions_and_haptics) to a device defined by a path (user path and subpath)
OpenXR internal function calls:
- xrApplyHapticFeedback
Parameters
----------
path: str
Complete [path](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved) (user path and subpath) referring to the action
haptic_feedback: dict
A python dictionary containing the field names and value of a XrHapticBaseHeader-based structure.
Note: At the moment the only haptics type supported is the unextended OpenXR [XrHapticVibration](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrHapticVibration)
Returns
-------
bool
True if there is no error during the haptic feedback application, otherwise False
"""
amplitude = haptic_feedback.get("amplitude", 0.5)
duration = haptic_feedback.get("duration", XR_MIN_HAPTIC_DURATION)
frequency = haptic_feedback.get("frequency", XR_FREQUENCY_UNSPECIFIED)
if self._disable_openxr:
return True
if self._use_ctypes:
amplitude = ctypes.c_float(amplitude)
duration = ctypes.c_int64(duration)
frequency = ctypes.c_float(frequency)
return bool(self._lib.applyHapticFeedback(self._app, ctypes.create_string_buffer(path.encode('utf-8')), amplitude, duration, frequency))
else:
return self._app.applyHapticFeedback(path, amplitude, duration, frequency)
def stop_haptic_feedback(self, path: str) -> bool:
"""
Stop a [haptic feedback](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_output_actions_and_haptics) applied to a device defined by a path (user path and subpath)
OpenXR internal function calls:
- xrStopHapticFeedback
Parameters
----------
path: str
Complete [path](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved) (user path and subpath) referring to the action
Returns
-------
bool
True if there is no error during the haptic feedback stop, otherwise False
"""
if self._disable_openxr:
return True
if self._use_ctypes:
return bool(self._lib.stopHapticFeedback(self._app, ctypes.create_string_buffer(path.encode('utf-8'))))
else:
return self._app.stopHapticFeedback(path)
# view utilities
def setup_mono_view(self, camera: Union[str, pxr.Sdf.Path, pxr.Usd.Prim] = "/OpenXR/Cameras/camera", camera_properties: dict = {"focalLength": 10}) -> None:
"""
Setup Omniverse viewport and camera for monoscopic rendering
This method obtains the viewport window for the given camera. If the viewport window does not exist, a new one is created and the camera is set as active. If the given camera does not exist, a new camera is created with the same path and set to the recommended resolution of the display device
Parameters
----------
camera: str, pxr.Sdf.Path or pxr.Usd.Prim, optional
Omniverse camera prim or path (default: '/OpenXR/Cameras/camera')
camera_properties: dict
Dictionary containing the [camera properties](https://docs.omniverse.nvidia.com/app_create/prod_materials-and-rendering/cameras.html#camera-properties) supported by the Omniverse kit to be set (default: {"focalLength": 10})
"""
self.setup_stereo_view(camera, None, camera_properties)
def setup_stereo_view(self, left_camera: Union[str, pxr.Sdf.Path, pxr.Usd.Prim] = "/OpenXR/Cameras/left_camera", right_camera: Union[str, pxr.Sdf.Path, pxr.Usd.Prim, None] = "/OpenXR/Cameras/right_camera", camera_properties: dict = {"focalLength": 10}) -> None:
"""
Setup Omniverse viewports and cameras for stereoscopic rendering
This method obtains the viewport window for each camera. If the viewport window does not exist, a new one is created and the camera is set as active. If the given cameras do not exist, new cameras are created with the same path and set to the recommended resolution of the display device
Parameters
----------
left_camera: str, pxr.Sdf.Path or pxr.Usd.Prim, optional
Omniverse left camera prim or path (default: '/OpenXR/Cameras/left_camera')
right_camera: str, pxr.Sdf.Path or pxr.Usd.Prim, optional
Omniverse right camera prim or path (default: '/OpenXR/Cameras/right_camera')
camera_properties: dict
Dictionary containing the [camera properties](https://docs.omniverse.nvidia.com/app_create/prod_materials-and-rendering/cameras.html#camera-properties) supported by the Omniverse kit to be set (default: {"focalLength": 10})
"""
def get_or_create_vieport_window(camera, teleport=True, window_size=(400, 300), resolution=(1280, 720)):
window = None
camera = str(camera.GetPath() if type(camera) is Usd.Prim else camera)
# get viewport window
for interface in self._viewport_interface.get_instance_list():
w = self._viewport_interface.get_viewport_window(interface)
if camera == w.get_active_camera():
window = w
# check visibility
if not w.is_visible():
w.set_visible(True)
break
# create viewport window if not exist
if window is None:
window = self._viewport_interface.get_viewport_window(self._viewport_interface.create_instance())
window.set_window_size(*window_size)
window.set_active_camera(camera)
window.set_texture_resolution(*resolution)
if teleport:
window.set_camera_position(camera, 1.0, 1.0, 1.0, True)
window.set_camera_target(camera, 0.0, 0.0, 0.0, True)
return window
stage = omni.usd.get_context().get_stage()
# left camera
teleport_camera = False
self._prim_left = None
if type(left_camera) is Usd.Prim:
self._prim_left = left_camera
elif stage.GetPrimAtPath(left_camera).IsValid():
self._prim_left = stage.GetPrimAtPath(left_camera)
else:
teleport_camera = True
self._prim_left = stage.DefinePrim(omni.usd.get_stage_next_free_path(stage, left_camera, False), "Camera")
self._viewport_window_left = get_or_create_vieport_window(self._prim_left, teleport=teleport_camera)
# right camera
teleport_camera = False
self._prim_right = None
if right_camera is not None:
if type(right_camera) is Usd.Prim:
self._prim_right = right_camera
elif stage.GetPrimAtPath(right_camera).IsValid():
self._prim_right = stage.GetPrimAtPath(right_camera)
else:
teleport_camera = True
self._prim_right = stage.DefinePrim(omni.usd.get_stage_next_free_path(stage, right_camera, False), "Camera")
self._viewport_window_right = get_or_create_vieport_window(self._prim_right, teleport=teleport_camera)
# set recommended resolution
resolutions = self.get_recommended_resolutions()
if len(resolutions) and self._viewport_window_left is not None:
self._viewport_window_left.set_texture_resolution(*resolutions[0])
if len(resolutions) == 2 and self._viewport_window_right is not None:
self._viewport_window_right.set_texture_resolution(*resolutions[1])
# set camera properties
for property in camera_properties:
self._prim_left.GetAttribute(property).Set(camera_properties[property])
if right_camera is not None:
self._prim_right.GetAttribute(property).Set(camera_properties[property])
# enable sensors
if self._viewport_window_left is not None:
sensors.enable_sensors(self._viewport_window_left, [_syntheticdata.SensorType.Rgb])
if self._viewport_window_right is not None:
sensors.enable_sensors(self._viewport_window_right, [_syntheticdata.SensorType.Rgb])
def get_recommended_resolutions(self) -> tuple:
"""
Get the recommended resolution of the display device
Returns
-------
tuple
Tuple containing the recommended resolutions (width, height) of each device view.
If the tuple length is 2, index 0 represents the left eye and index 1 represents the right eye
"""
if self._disable_openxr:
return ([512, 512], [1024, 1024])
if self._use_ctypes:
num_views = self._lib.getViewConfigurationViewsSize(self._app)
views = (XrViewConfigurationView * num_views)()
if self._lib.getViewConfigurationViews(self._app, views, num_views):
return [(view.recommendedImageRectWidth, view.recommendedImageRectHeight) for view in views]
else:
return tuple([])
else:
return tuple([(view["recommendedImageRectWidth"], view["recommendedImageRectHeight"]) for view in self._app.getViewConfigurationViews()])
def set_reference_system_pose(self, position: Union[pxr.Gf.Vec3d, None] = None, rotation: Union[pxr.Gf.Vec3d, None] = None) -> None:
"""
Set the pose of the origin of the reference system
Parameters
----------
position: pxr.Gf.Vec3d or None, optional
Cartesian position (in stage unit) (default: None)
rotation: pxr.Gf.Vec3d or None, optional
Rotation (in degress) on each axis (default: None)
"""
self._reference_position = position
self._reference_rotation = rotation
def set_stereo_rectification(self, x: float = 0, y: float = 0, z: float = 0) -> None:
"""
Set the angle (in radians) of the rotation axes for stereoscopic view rectification
Parameters
----------
x: float, optional
Angle (in radians) of the X-axis (default: 0)
y: float, optional
Angle (in radians) of the Y-axis (default: 0)
x: float, optional
Angle (in radians) of the Z-axis (default: 0)
"""
self._rectification_quat_left = pxr.Gf.Quatd(1, 0, 0, 0)
self._rectification_quat_right = pxr.Gf.Quatd(1, 0, 0, 0)
if x: # w,x,y,z = cos(a/2), sin(a/2), 0, 0
self._rectification_quat_left *= pxr.Gf.Quatd(np.cos(x/2), np.sin(x/2), 0, 0)
self._rectification_quat_right *= pxr.Gf.Quatd(np.cos(-x/2), np.sin(-x/2), 0, 0)
if y: # w,x,y,z = cos(a/2), 0, sin(a/2), 0
self._rectification_quat_left *= pxr.Gf.Quatd(np.cos(y/2), 0, np.sin(y/2), 0)
self._rectification_quat_right *= pxr.Gf.Quatd(np.cos(-y/2), 0, np.sin(-y/2), 0)
if z: # w,x,y,z = cos(a/2), 0, 0, sin(a/2)
self._rectification_quat_left *= pxr.Gf.Quatd(np.cos(z/2), 0, 0, np.sin(z/2))
self._rectification_quat_right *= pxr.Gf.Quatd(np.cos(-z/2), 0, 0, np.sin(-z/2))
def set_meters_per_unit(self, meters_per_unit: float):
"""
Specify the meters per unit to be applied to transformations
E.g. 1 meter: 1.0, 1 centimeter: 0.01
Parameters
----------
meters_per_unit: float
Meters per unit
"""
assert meters_per_unit != 0
self._meters_per_unit = meters_per_unit
def set_frame_transformations(self, fit: bool = False, flip: Union[int, tuple, None] = None) -> None:
"""
Specify the transformations to be applied to the rendered images
Parameters
----------
fit: bool, optional
Adjust each rendered image to the recommended resolution of the display device by cropping and scaling the image from its center (default: False)
OpenCV.resize method with INTER_LINEAR interpolation will be used to scale the image to the recommended resolution
flip: int, tuple or None, optional
Flip each image around vertical (0), horizontal (1), or both axes (0,1) (default: None)
"""
self._transform_fit = fit
self._transform_flip = flip
def teleport_prim(self, prim: pxr.Usd.Prim, position: pxr.Gf.Vec3d, rotation: pxr.Gf.Quatd, reference_position: Union[pxr.Gf.Vec3d, None] = None, reference_rotation: Union[pxr.Gf.Vec3d, None] = None) -> None:
"""
Teleport the prim specified by the given transformation (position and rotation)
Parameters
----------
prim: pxr.Usd.Prim
Target prim
position: pxr.Gf.Vec3d
Cartesian position (in stage unit) used to transform the prim
rotation: pxr.Gf.Quatd
Rotation (as quaternion) used to transform the prim
reference_position: pxr.Gf.Vec3d or None, optional
Cartesian position (in stage unit) used as reference system (default: None)
reference_rotation: pxr.Gf.Vec3d or None, optional
Rotation (in degress) on each axis used as reference system (default: None)
"""
properties = prim.GetPropertyNames()
# reference position
if reference_position is not None:
if "xformOp:translate" in properties or "xformOp:translation" in properties:
prim.GetAttribute("xformOp:translate").Set(reference_position + position)
else:
print("[INFO] Create UsdGeom.XformOp.TypeTranslate for", prim.GetPath())
UsdGeom.Xformable(prim).AddXformOp(UsdGeom.XformOp.TypeTranslate, UsdGeom.XformOp.PrecisionDouble, "").Set(reference_position + position)
else:
if "xformOp:translate" in properties or "xformOp:translation" in properties:
prim.GetAttribute("xformOp:translate").Set(position)
else:
print("[INFO] Create UsdGeom.XformOp.TypeTranslate for", prim.GetPath())
UsdGeom.Xformable(prim).AddXformOp(UsdGeom.XformOp.TypeTranslate, UsdGeom.XformOp.PrecisionDouble, "").Set(position)
# reference rotation
if reference_rotation is not None:
if "xformOp:rotate" in properties:
prim.GetAttribute("xformOp:rotate").Set(reference_rotation)
elif "xformOp:rotateXYZ" in properties:
try:
prim.GetAttribute("xformOp:rotateXYZ").Set(reference_rotation)
except:
prim.GetAttribute("xformOp:rotateXYZ").Set(Gf.Vec3f(reference_rotation))
else:
print("[INFO] Create UsdGeom.XformOp.TypeRotateXYZ for", prim.GetPath())
UsdGeom.Xformable(prim).AddXformOp(UsdGeom.XformOp.TypeRotateXYZ, UsdGeom.XformOp.PrecisionDouble, "").Set(reference_rotation)
# transform
transform_matrix = Gf.Matrix4d()
transform_matrix.SetIdentity()
# transform_matrix.SetTranslateOnly(position)
transform_matrix.SetRotateOnly(Gf.Rotation(rotation))
if "xformOp:transform" in properties:
prim.GetAttribute("xformOp:transform").Set(transform_matrix)
else:
print("[INFO] Create UsdGeom.XformOp.TypeTransform for", prim.GetPath())
UsdGeom.Xformable(prim).AddXformOp(UsdGeom.XformOp.TypeTransform, UsdGeom.XformOp.PrecisionDouble, "").Set(transform_matrix)
def subscribe_render_event(self, callback=None) -> None:
"""
Subscribe a callback function to the render event
The callback function (a callable object) should have only the following 3 parameters:
- num_views: int
The number of views to render: mono (1), stereo (2)
- views: tuple of XrView structure
A [XrView](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrView) structure contains the view pose and projection state necessary to render a image.
The length of the tuple corresponds to the number of views (if the tuple length is 2, index 0 represents the left eye and index 1 represents the right eye)
- configuration_views: tuple of XrViewConfigurationView structure
A [XrViewConfigurationView](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrViewConfigurationView) structure specifies properties related to rendering of a view (e.g. the optimal width and height to be used when rendering the view).
The length of the tuple corresponds to the number of views (if the tuple length is 2, index 0 represents the left eye and index 1 represents the right eye)
The callback function must call the set_frames function to pass to the selected graphics API the image or images to be rendered
If the callback is None, an internal callback will be used to render the views. This internal callback updates the pose of the cameras according to the specified reference system, gets the images from the previously configured viewports and invokes the set_frames function to render the views.
Parameters
----------
callback: callable object (3 parameters) or None, optional
Callback invoked on each render event (default: None)
"""
def _middle_callback(num_views, views, configuration_views):
_views = []
for v in views:
tmp = XrView()
tmp.type = v["type"]
tmp.next = None
tmp.pose = XrPosef()
tmp.pose.position.x = v["pose"]["position"]["x"]
tmp.pose.position.y = v["pose"]["position"]["y"]
tmp.pose.position.z = v["pose"]["position"]["z"]
tmp.pose.orientation.x = v["pose"]["orientation"]["x"]
tmp.pose.orientation.y = v["pose"]["orientation"]["y"]
tmp.pose.orientation.z = v["pose"]["orientation"]["z"]
tmp.pose.orientation.w = v["pose"]["orientation"]["w"]
tmp.fov = XrFovf()
tmp.fov.angleLeft = v["fov"]["angleLeft"]
tmp.fov.angleRight = v["fov"]["angleRight"]
tmp.fov.angleUp = v["fov"]["angleUp"]
tmp.fov.angleDown = v["fov"]["angleDown"]
_views.append(tmp)
_configuration_views = []
for v in configuration_views:
tmp = XrViewConfigurationView()
tmp.type = v["type"]
tmp.next = None
tmp.recommendedImageRectWidth = v["recommendedImageRectWidth"]
tmp.recommendedImageRectHeight = v["recommendedImageRectHeight"]
tmp.maxImageRectWidth = v["maxImageRectWidth"]
tmp.maxImageRectHeight = v["maxImageRectHeight"]
tmp.recommendedSwapchainSampleCount = v["recommendedSwapchainSampleCount"]
tmp.maxSwapchainSampleCount = v["maxSwapchainSampleCount"]
_configuration_views.append(tmp)
self._callback_render(num_views, _views, _configuration_views)
def _internal_render(num_views, views, configuration_views):
# teleport left camera
position = views[0].pose.position
rotation = views[0].pose.orientation
position = Gf.Vec3d(position.x, -position.z, position.y) / self._meters_per_unit
rotation = Gf.Quatd(rotation.w, rotation.x, rotation.y, rotation.z) * self._rectification_quat_left
self.teleport_prim(self._prim_left, position, rotation, self._reference_position, self._reference_rotation)
# teleport right camera
if num_views == 2:
position = views[1].pose.position
rotation = views[1].pose.orientation
position = Gf.Vec3d(position.x, -position.z, position.y) / self._meters_per_unit
rotation = Gf.Quatd(rotation.w, rotation.x, rotation.y, rotation.z) * self._rectification_quat_right
self.teleport_prim(self._prim_right, position, rotation, self._reference_position, self._reference_rotation)
# set frames
try:
frame_left = sensors.get_rgb(self._viewport_window_left)
frame_right = sensors.get_rgb(self._viewport_window_right) if num_views == 2 else None
self.set_frames(configuration_views, frame_left, frame_right)
except Exception as e:
print("[ERROR]", str(e))
self._callback_render = callback
if callback is None:
self._callback_render = _internal_render
if self._disable_openxr:
return
if self._use_ctypes:
self._callback_middle_render = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.POINTER(XrView), ctypes.POINTER(XrViewConfigurationView))(self._callback_render)
self._lib.setRenderCallback(self._app, self._callback_middle_render)
else:
self._callback_middle_render = _middle_callback
self._app.setRenderCallback(self._callback_middle_render)
def set_frames(self, configuration_views: list, left: numpy.ndarray, right: numpy.ndarray = None) -> bool:
"""
Pass to the selected graphics API the images to be rendered in the views
In the case of stereoscopic devices, the parameters left and right represent the left eye and right eye respectively.
To pass an image to the graphic API of monoscopic devices only the parameter left should be used (the parameter right must be None)
This function will apply to each image the transformations defined by the set_frame_transformations function if they were specified
Parameters
----------
configuration_views: tuple of XrViewConfigurationView structure
A [XrViewConfigurationView](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrViewConfigurationView) structure specifies properties related to rendering of a view (e.g. the optimal width and height to be used when rendering the view)
left: numpy.ndarray
RGB or RGBA image (numpy.uint8)
right: numpy.ndarray or None
RGB or RGBA image (numpy.uint8)
Returns
-------
bool
True if there is no error during the passing to the selected graphics API, otherwise False
"""
use_rgba = True if left.shape[2] == 4 else False
if self._disable_openxr:
return True
if self._use_ctypes:
self._frame_left = self._transform(configuration_views[0], left)
if right is None:
return bool(self._lib.setFrames(self._app,
self._frame_left.shape[1], self._frame_left.shape[0], self._frame_left.ctypes.data_as(ctypes.c_void_p),
0, 0, None,
use_rgba))
else:
self._frame_right = self._transform(configuration_views[1], right)
return bool(self._lib.setFrames(self._app,
self._frame_left.shape[1], self._frame_left.shape[0], self._frame_left.ctypes.data_as(ctypes.c_void_p),
self._frame_right.shape[1], self._frame_right.shape[0], self._frame_right.ctypes.data_as(ctypes.c_void_p),
use_rgba))
else:
self._frame_left = self._transform(configuration_views[0], left)
if right is None:
return self._app.setFrames(self._frame_left, np.array(None), use_rgba)
else:
self._frame_right = self._transform(configuration_views[1], right)
return self._app.setFrames(self._frame_left, self._frame_right, use_rgba)
def _transform(self, configuration_view: XrViewConfigurationView, frame: np.ndarray) -> np.ndarray:
transformed = False
if self._transform_flip is not None:
transformed = True
frame = np.flip(frame, axis=self._transform_flip)
if self._transform_fit:
transformed = True
current_ratio = frame.shape[1] / frame.shape[0]
recommended_ratio = configuration_view.recommendedImageRectWidth / configuration_view.recommendedImageRectHeight
recommended_size = (configuration_view.recommendedImageRectWidth, configuration_view.recommendedImageRectHeight)
if current_ratio > recommended_ratio:
m = int(abs(recommended_ratio * frame.shape[0] - frame.shape[1]) / 2)
frame = cv2.resize(frame[:, m:-m] if m else frame, recommended_size, interpolation=cv2.INTER_LINEAR)
else:
m = int(abs(frame.shape[1] / recommended_ratio - frame.shape[0]) / 2)
frame = cv2.resize(frame[m:-m, :] if m else frame, recommended_size, interpolation=cv2.INTER_LINEAR)
return np.array(frame, copy=True) if transformed else frame
if __name__ == "__main__":
import cv2
import time
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--ctypes', default=False, action="store_true", help='use ctypes instead of pybind11')
args = parser.parse_args()
_xr = acquire_openxr_interface()
_xr.init(use_ctypes=args.ctypes)
ready = False
end = False
def callback_action_pose(path, value):
print(path, value)
return
def callback_action(path, value):
if path in ["/user/hand/left/input/menu/click", "/user/hand/right/input/menu/click"]:
# print(path, value)
print(_xr.apply_haptic_feedback("/user/hand/left/output/haptic", {"duration": 1000000}))
print(_xr.apply_haptic_feedback("/user/hand/right/output/haptic", {"duration": 1000000}))
if _xr.create_instance():
if _xr.get_system():
_xr.subscribe_action_event("/user/head/input/volume_up/click", callback=callback_action)
_xr.subscribe_action_event("/user/head/input/volume_down/click", callback=callback_action)
_xr.subscribe_action_event("/user/head/input/mute_mic/click", callback=callback_action)
_xr.subscribe_action_event("/user/hand/left/input/trigger/value", callback=callback_action)
_xr.subscribe_action_event("/user/hand/right/input/trigger/value", callback=callback_action)
_xr.subscribe_action_event("/user/hand/left/input/menu/click", callback=callback_action)
_xr.subscribe_action_event("/user/hand/right/input/menu/click", callback=callback_action)
_xr.subscribe_action_event("/user/hand/left/input/grip/pose", callback=callback_action_pose, reference_space=XR_REFERENCE_SPACE_TYPE_LOCAL)
_xr.subscribe_action_event("/user/hand/right/input/grip/pose", callback=callback_action_pose, reference_space=XR_REFERENCE_SPACE_TYPE_LOCAL)
_xr.subscribe_action_event("/user/hand/left/output/haptic", callback=callback_action)
_xr.subscribe_action_event("/user/hand/right/output/haptic", callback=callback_action)
if _xr.create_session():
ready = True
else:
print("[ERROR]:", "createSession")
else:
print("[ERROR]:", "getSystem")
else:
print("[ERROR]:", "createInstance")
if ready:
cap = cv2.VideoCapture("/home/argus/Videos/xr/xr/sample.mp4")
def callback_render(num_views, views, configuration_views):
pass
# global end
# ret, frame = cap.read()
# if ret:
# if num_views == 2:
# frame1 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# _xr.set_frames(configuration_views, frame, frame1)
# # show frame
# k = 0.25
# frame = cv2.resize(np.hstack((frame, frame1)), (int(2*k*frame.shape[1]), int(k*frame.shape[0])))
# cv2.imshow('frame', frame)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# exit()
# else:
# end = True
_xr.subscribe_render_event(callback_render)
# while(cap.isOpened() or not end):
for i in range(10000000):
if _xr.poll_events():
if _xr.is_session_running():
if not _xr.poll_actions():
print("[ERROR]:", "pollActions")
break
if not _xr.render_views():
print("[ERROR]:", "renderViews")
break
else:
print("wait for is_session_running()")
time.sleep(0.1)
else:
break
print("END") | 58,615 | Python | 47.928214 | 301 | 0.61387 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/semu/xr/openxr/scripts/extension.py | import gc
import carb
import omni.ext
try:
import cv2
except:
omni.kit.pipapi.install("opencv-python")
try:
from .. import _openxr as _openxr
except:
print(">>>> [DEVELOPMENT] import openxr")
from .. import openxr as _openxr
__all__ = ["Extension", "_openxr"]
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
# get extension settings
self._settings = carb.settings.get_settings()
disable_openxr = self._settings.get("/exts/semu.xr.openxr/disable_openxr")
self._xr = _openxr.acquire_openxr_interface(disable_openxr=disable_openxr)
def on_shutdown(self):
_openxr.release_openxr_interface(self._xr)
gc.collect()
| 703 | Python | 24.142856 | 82 | 0.657183 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/semu/xr/openxr/tests/__init__.py | from .test_openxr import *
| 27 | Python | 12.999994 | 26 | 0.740741 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/semu/xr/openxr/tests/test_openxr.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from semu.xr.openxr import _openxr
import cv2
import time
import numpy as np
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class TestOpenXR(omni.kit.test.AsyncTestCaseFailOnLogError):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
def render(self, num_frames, width, height, color):
self._frame = np.ones((height, width, 3), dtype=np.uint8)
self._frame = cv2.circle(self._frame, (int(width / 2), int(height / 2)),
int(np.min([width, height]) / 4), color, int(0.05 * np.min([width, height])))
self._frame = cv2.circle(self._frame, (int(width / 3), int(height / 3)),
int(0.1 * np.min([width, height])), color, -1)
start_time = time.clock()
for i in range(num_frames):
if self._xr.poll_events():
if self._xr.is_session_running():
if not self._xr.poll_actions():
print("[ERROR]:", "pollActions")
return
if not self._xr.render_views():
print("[ERROR]:", "renderViews")
return
end_time = time.clock()
delta = end_time - start_time
print("----------")
print("FPS: {} ({} frames / {} seconds)".format(num_frames / delta, num_frames, delta))
print("RESOLUTION: {} x {}".format(self._frame.shape[1], self._frame.shape[0]))
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_openxr(self):
self._xr = _openxr.acquire_openxr_interface()
self._xr.init()
ready = False
if self._xr.create_instance():
if self._xr.get_system():
if self._xr.create_action_set():
if self._xr.create_session():
ready = True
else:
print("[ERROR]:", "createSession")
else:
print("[ERROR]:", "createActionSet")
else:
print("[ERROR]:", "getSystem")
else:
print("[ERROR]:", "createInstance")
if ready:
for i in range(1000):
if self._xr.poll_events():
if self._xr.is_session_running():
if not self._xr.poll_actions():
print("[ERROR]:", "pollActions")
break
# if ready:
# def callback_render(num_views, views, configuration_views):
# self._xr.set_frames(configuration_views, self._frame, self._frame, self._transform)
# self._xr.subscribe_render_event(callback_render)
# num_frames = 100
# print("")
# print("transform = True")
# self._transform = True
# self.render(num_frames=num_frames, width=1560, height=1732, color=(255,0,0))
# self.render(num_frames=num_frames, width=1280, height=720, color=(0,255,0))
# self.render(num_frames=num_frames, width=500, height=500, color=(0,0,255))
# print("")
# print("transform = False")
# self._transform = False
# self.render(num_frames=num_frames, width=1560, height=1732, color=(255,0,0))
# self.render(num_frames=num_frames, width=1280, height=720, color=(0,255,0))
# self.render(num_frames=num_frames, width=500, height=500, color=(0,0,255))
# print("")
# _openxr.release_openxr_interface(self._xr)
# self._xr = None
| 4,250 | Python | 40.271844 | 142 | 0.527529 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/semu/xr/openxr_ui/scripts/extension.py | import math
import weakref
import pxr
import omni
import carb
import omni.ext
import omni.ui as ui
from pxr import UsdGeom
from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription
from semu.xr.openxr import _openxr
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
# get extension settings
self._settings = carb.settings.get_settings()
self._disable_openxr = self._settings.get("/exts/semu.xr.openxr/disable_openxr")
self._window = None
self._menu_items = [MenuItemDescription(name="OpenXR UI", onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())]
add_menu_items(self._menu_items, "Add-ons")
self._xr = None
self._ready = False
self._timeline = omni.timeline.get_timeline_interface()
self._physx_subs = omni.physx.get_physx_interface().subscribe_physics_step_events(self._on_simulation_step)
def on_shutdown(self):
self._physx_subs = None
remove_menu_items(self._menu_items, "Add-ons")
self._window = None
def _get_reference_space(self):
reference_space = [_openxr.XR_REFERENCE_SPACE_TYPE_VIEW, _openxr.XR_REFERENCE_SPACE_TYPE_LOCAL, _openxr.XR_REFERENCE_SPACE_TYPE_STAGE]
return reference_space[self._xr_settings_reference_space.model.get_item_value_model().as_int]
def _get_origin_pose(self):
space_origin_position = [self._xr_settings_space_origin_position.model.get_item_value_model(i).as_float for i in self._xr_settings_space_origin_position.model.get_item_children()]
space_origin_rotation = [self._xr_settings_space_origin_rotation.model.get_item_value_model(i).as_int for i in self._xr_settings_space_origin_rotation.model.get_item_children()]
return {"position": pxr.Gf.Vec3d(*space_origin_position), "rotation": pxr.Gf.Vec3d(*space_origin_rotation)}
def _get_frame_transformations(self):
transform_fit = self._xr_settings_transform_fit.model.get_value_as_bool()
transform_flip = [None, 0, 1, (0,1)]
transform_flip = transform_flip[self._xr_settings_transform_flip.model.get_item_value_model().as_int]
return {"fit": transform_fit, "flip": transform_flip}
def _get_stereo_rectification(self):
return [self._xr_settings_stereo_rectification.model.get_item_value_model(i).as_float * math.pi / 180.0 for i in self._xr_settings_stereo_rectification.model.get_item_children()]
def _menu_callback(self):
self._build_ui()
def _on_start_openxr(self):
# get parameters from ui
graphics = [_openxr.XR_KHR_OPENGL_ENABLE_EXTENSION_NAME]
graphics = graphics[self._xr_settings_graphics_api.model.get_item_value_model().as_int]
form_factor = [_openxr.XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY, _openxr.XR_FORM_FACTOR_HANDHELD_DISPLAY]
form_factor = form_factor[self._xr_settings_form_factor.model.get_item_value_model().as_int]
blend_mode = [_openxr.XR_ENVIRONMENT_BLEND_MODE_OPAQUE, _openxr.XR_ENVIRONMENT_BLEND_MODE_ADDITIVE, _openxr.XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND]
blend_mode = blend_mode[self._xr_settings_blend_mode.model.get_item_value_model().as_int]
view_configuration_type = [_openxr.XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO, _openxr.XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO]
view_configuration_type = view_configuration_type[self._xr_settings_view_configuration_type.model.get_item_value_model().as_int]
# disable static parameters ui
self._xr_settings_graphics_api.enabled = False
self._xr_settings_form_factor.enabled = False
self._xr_settings_blend_mode.enabled = False
self._xr_settings_view_configuration_type.enabled = False
if self._xr is None:
self._xr = _openxr.acquire_openxr_interface(disable_openxr=self._disable_openxr)
if not self._xr.init(graphics=graphics, use_ctypes=False):
print("[ERROR] OpenXR.init with graphics: {}".format(graphics))
# set stage unit
stage = omni.usd.get_context().get_stage()
self._xr.set_meters_per_unit(UsdGeom.GetStageMetersPerUnit(stage))
# setup OpenXR application using default and ui parameters
if self._xr.create_instance():
if self._xr.get_system(form_factor=form_factor, blend_mode=blend_mode, view_configuration_type=view_configuration_type):
# create session and define interaction profiles
if self._xr.create_session():
# setup cameras and viewports and prepare rendering using the internal callback
if view_configuration_type == _openxr.XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO:
self._xr.setup_mono_view()
elif view_configuration_type == _openxr.XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO:
self._xr.setup_stereo_view()
# enable/disable buttons
self._ui_start_xr.enabled = False
self._ui_stop_xr.enabled = True
# play
self._timeline.play()
self._ready = True
return
else:
print("[ERROR] OpenXR.create_session")
else:
print("[ERROR] OpenXR.get_system with form_factor: {}, blend_mode: {}, view_configuration_type: {}".format(form_factor, blend_mode, view_configuration_type))
else:
print("[ERROR] OpenXR.create_instance")
self._on_stop_openxr()
def _on_stop_openxr(self):
self._ready = False
_openxr.release_openxr_interface(self._xr)
self._xr = None
# enable static parameters ui
self._xr_settings_graphics_api.enabled = True
self._xr_settings_form_factor.enabled = True
self._xr_settings_blend_mode.enabled = True
self._xr_settings_view_configuration_type.enabled = True
# enable/disable buttons
self._ui_start_xr.enabled = True
self._ui_stop_xr.enabled = False
def _on_simulation_step(self, step):
if self._ready and self._xr is not None:
# origin
self._xr.set_reference_system_pose(**self._get_origin_pose())
# transformation and rectification
self._xr.set_stereo_rectification(*self._get_stereo_rectification())
self._xr.set_frame_transformations(**self._get_frame_transformations())
# action and rendering loop
if not self._xr.poll_events():
self._on_stop_openxr()
return
if self._xr.is_session_running():
if not self._xr.poll_actions():
self._on_stop_openxr()
return
if not self._xr.render_views(self._get_reference_space()):
self._on_stop_openxr()
return
def _build_ui(self):
if not self._window:
self._window = ui.Window(title="OpenXR UI", width=300, height=375, visible=True, dockPreference=ui.DockPreference.LEFT_BOTTOM)
with self._window.frame:
with ui.VStack():
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label("Graphics API:", width=85, tooltip="OpenXR graphics API supported by the runtime")
self._xr_settings_graphics_api = ui.ComboBox(0, "OpenGL")
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label("Form factor:", width=80, tooltip="XrFormFactor enum. HEAD_MOUNTED_DISPLAY: the tracked display is attached to the user's head. HANDHELD_DISPLAY: the tracked display is held in the user's hand, independent from the user's head")
self._xr_settings_form_factor = ui.ComboBox(0, "Head Mounted Display", "Handheld Display")
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label("Blend mode:", width=80, tooltip="XrEnvironmentBlendMode enum. OPAQUE: display the composition layers with no view of the physical world behind them. ADDITIVE: additively blend the composition layers with the real world behind the display. ALPHA BLEND: alpha-blend the composition layers with the real world behind the display")
self._xr_settings_blend_mode = ui.ComboBox(0, "Opaque", "Additive", "Alpha blend")
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label("View configuration type:", width=145, tooltip="XrViewConfigurationType enum. MONO: one primary display (e.g. an AR phone's screen). STEREO: two primary displays, which map to a left-eye and right-eye view")
self._xr_settings_view_configuration_type = ui.ComboBox(1, "Mono", "Stereo")
ui.Spacer(height=5)
ui.Separator(height=1, width=0)
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label("Space origin:", width=85)
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label(" |-- Position (in stage unit):", width=165, tooltip="Cartesian position (in stage unit) used as reference origin")
self._xr_settings_space_origin_position = ui.MultiFloatDragField(0.0, 0.0, 0.0, step=0.1)
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label(" |-- Rotation (XYZ):", width=110, tooltip="Rotation (in degress) on each axis used as reference origin")
self._xr_settings_space_origin_rotation = ui.MultiIntDragField(0, 0, 0, min=-180, max=180)
ui.Spacer(height=5)
with ui.HStack(height=0):
style = {"Tooltip": {"width": 50, "word-wrap": "break-word"}}
ui.Label("Reference space (views):", width=145, tooltip="XrReferenceSpaceType enum. VIEW: track the view origin for the primary viewer. LOCAL: establish a world-locked origin. STAGE: runtime-defined space that can be walked around on", style=style)
self._xr_settings_reference_space = ui.ComboBox(1, "View", "Local", "Stage")
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label("Stereo rectification (x,y,z):", width=150, tooltip="Angle (in degrees) on each rotation axis for stereoscopic rectification")
self._xr_settings_stereo_rectification = ui.MultiFloatDragField(0.0, 0.0, 0.0, min=-10, max=10, step=0.1)
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label("Frame transformations:")
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label(" |-- Fit:", width=45, tooltip="Adjust each rendered image to the recommended resolution of the display device by cropping and scaling the image from its center")
self._xr_settings_transform_fit = ui.CheckBox()
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label(" |-- Flip:", width=45, tooltip="Flip each image with respect to its view")
self._xr_settings_transform_flip = ui.ComboBox(0, "None", "Vertical", "Horizontal", "Both")
ui.Spacer(height=5)
ui.Separator(height=1, width=0)
ui.Spacer(height=5)
with ui.HStack(height=0):
self._ui_start_xr = ui.Button("Start OpenXR", height=0, clicked_fn=self._on_start_openxr)
self._ui_stop_xr = ui.Button("Stop OpenXR", height=0, clicked_fn=self._on_stop_openxr)
self._ui_stop_xr.enabled = False
| 12,268 | Python | 55.800926 | 361 | 0.593332 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "0.0.4-beta"
category = "Other"
feature = false
app = false
title = "OpenXR (compact binding)"
description = "OpenXR compact binding for Omniverse"
authors = ["Toni-SM"]
repository = "https://github.com/Toni-SM/semu.xr.openxr"
keywords = ["OpenXR", "XR", "VR", "AR"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[package.target]
config = ["release"]
platform = ["linux-x86_64"]
python = ["py37", "cp37"]
[dependencies]
"omni.ui" = {}
"omni.physx" = {}
"omni.kit.uiapp" = {}
"omni.kit.pipapi" = {}
"omni.syntheticdata" = {}
"omni.kit.menu.utils" = {}
"omni.kit.window.viewport" = {}
[[python.module]]
name = "semu.xr.openxr"
[[python.module]]
name = "semu.xr.openxr_ui"
[[python.module]]
name = "semu.xr.openxr.tests"
[python.pipapi]
requirements = ["opencv-python"]
use_online_index = true
[settings]
exts."semu.xr.openxr".disable_openxr = false
| 980 | TOML | 19.020408 | 56 | 0.668367 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.0.4-beta] - 2022-09-14
### Added
- Add `set_meters_per_unit` method for specifying the unit factor to be applied to transformations
### Changed
- Use float input field for getting the reference position from UI
## [0.0.3-beta] - 2022-09-09
### Added
- Add `disable_openxr` flag to configuration settings for testing the extension
### Fixed
- Enable RGB sensors when setting up mono/stereo views
## [0.0.2-beta] - 2022-05-22
### Added
- Source code (src folder)
### Changed
- Rename the extension to `semu.xr.openxr`
## [0.0.1-beta] - 2021-10-01
### Added
- Create OpenXR compact binding with OpenGL support
| 716 | Markdown | 23.724137 | 98 | 0.702514 |
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/docs/README.md | # semu.xr.openxr
This extension provides a compact python binding (on top of the open standard OpenXR for augmented reality (AR) and virtual reality (VR)) to create extended reality applications taking advantage of NVIDIA Omniverse rendering capabilities
Visit https://github.com/Toni-SM/semu.xr.openxr to read more about its use
| 333 | Markdown | 46.714279 | 237 | 0.804805 |
WuPingFan/omniverse-exts-sunpath/README.md | # Omniverse SunPath Extension

## Overview
SunPath is the diagram to show the path of the sun, sometimes also called day arc. Accurate location-specific knowledge of sun path is essential for some fields, such as architectural design and landscaping. This extension allows to add the SunPath diagram in the viewport window, and the diagram can be updated by setting it's parameters.
## User Interface
### 1. Display

> This group of widgets allows to control the display of SunPath diagram.
<div>
<img src='./data/show_path.gif' width='360px'>
<img src='./data/show_sun.gif' width='360px'>
<img src='./data/show_info.gif' width='360px'>
</div>
- **Show Path** : Switch on or off the checkbox to control whether the SunPath diagram is displayed or not.
- **Show Sun** : Switch on or off the checkbox to control whether the sunlight and the sphere(sun) is displayed or not.
- **Show Info** : Switch on or off the checkbox to control whether the information of sun direction, sunrise time, sunset time and datetime is displayed or not.
<div>
<img src='./data/path_color.gif' width='360px'>
<img src='./data/path_scale.gif' width='360px'>
<img src='./data/gesture.gif' width='360px'>
</div>
- **Path Color** : Select the color you prefer in the ColorWidget and click the update button to change the color of SunPath diagram.
- **Path scale** : Drag the slider or enter a value to change the size of SunPath diagram.
- **Gesture** : You can drag the block on the North tick-mark to move the SunPath diagram.
### 2. Location

> This group of widgets allows to set location parameters.
<div>
<img src='./data/location_longitude.gif' width='360px'>
<img src='./data/location_latitude.gif' width='360px'>
</div>
- **Longitude** : Allows to set Longitude, the "8" shape loop wire can be updated.
- **Latitude** : Allows to set Latitude, the Path rotation angle can be updated.
### 3. Datetime

> This group of widgets allows to set exact datetime parameters.
<div>
<img src='./data/date.gif' width='360px'>
<img src='./data/hour.gif' width='360px'>
<img src='./data/minite.gif' width='360px'>
</div>
- **Date**: Used to set the date of the year. Drag or enter datetime value will change this datetime's SunPath (the green curve).
- **Hour**: Used to set the specific hour of the day. Drag or enter hour value can change the sun position of specific date, When the sun is below the horizon, the lights turn off.
- **Minite**: Controlling the specific minute in a specific hour can finely control the position of the sun.
## SunPath Diagram Items
> The SunPath diagram is composed of Compass, Path, Sun and Shadow.
<div>
<img src='./data/compass.png' width='215px'>
<img src='./data/sunpath.png' width='360px'>
<img src='./data/light_properties.png' width='173px'>
</div>
- **Compass**:The Compass provides the orientation reference of the scene, includes direcitons and angles.
- **Path**: The Path includes two kinds of Sun Path. First is the day arc of any datetime, SunPath diagram shows this arc of whole year. Second is the "8" shape loop wire, SunPath diagram shows same time Sun positon of whole year.
- **Sun**: Sun orientation will affected by the ocation and datetime. The sun of this Extension is simulated by the distant light. Therefore, some of its properties can be modified in the properties panel.
- **Shadow**: Shadows are generated by the distant light, Therefore, it is still can modified in its property panel.
## Usage
### 1. Install
* **Fork and clone this repo**: For example in `D:\projects\kit-exts-sunpath`
* **Open extension manager**: Go to Menu -> Window -> Extension
* **Add SunPath extension**: Clik the button in the top left bar (gear button), add absolute extension path to Extension Search Paths.
### 2. Notice

- **Utlity**: To make this extension work correctly, you need to open the viewport utlity in the extensions manager first.
- **Package**: This extension relies on the python package(pyephem-SunPath) to generate key Sun data. Therefore, the first use will wait for a short time.
- **Coordinate system**: Coordinate system conversion has not been set in the current version of this extension, it was created based on XZ plane. You need to pay attention to whether the coordinate system of the imported USD is inconsistent.
| 4,506 | Markdown | 45.947916 | 339 | 0.724368 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/gol.py | """Build global dictionary"""
from .sunpath_data import SunpathData
def _init():
global _global_dict
_global_dict = {}
# Pathmodel For draw sphere
_global_dict["pathmodel"] = SunpathData(230, 12, 30, 112.94, 28.12)
# For distant light to determine whether to change the attribute
_global_dict["dome_angle"] = None
# Parameter for DrawSunpath
_global_dict["origin"] = [0, 0, 0]
_global_dict["scale"] = 50
_global_dict["color"] = [255, 255, 255]
_global_dict["length"] = 3.5
# Flag for show sun
_global_dict["sun_state"] = False
# Flag for show info
_global_dict["show_info"] = False
def set_value(key, value):
_global_dict[key] = value
def set_item(key, i, value):
_global_dict[key][i] = value
def get_value(key):
try:
return _global_dict[key]
except:
print("get" + key + "fail\r\n")
| 888 | Python | 20.682926 | 71 | 0.608108 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/gesture.py | from omni.ui import scene as sc
from omni.ui import color as cl
from . import gol
class _ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
window.disable_selection_rect(True)
except Exception:
pass
class MoveGesture(sc.DragGesture):
"""Define the action of gesture"""
def __init__(self, transform: sc.Transform):
super().__init__()
self.__transform = transform
self._previous_ray_point = None
self._pre_origin = None
def on_began(self):
self.sender.color = cl.beige
self.sender.width = gol.get_value("length")
self.disable_selection = _ViewportLegacyDisableSelection()
self._previous_ray_point = self.gesture_payload.ray_closest_point
self._pre_origin = gol.get_value("origin")
def on_changed(self):
translate = self.sender.gesture_payload.moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
object_ray_point = self.gesture_payload.ray_closest_point
# Compute translation vector(point)
moved = [a - b for a, b in zip(object_ray_point, self._previous_ray_point)]
# Compute new origin and save it to dictionary
origin = [a + b for a, b in zip(self._pre_origin, moved)]
gol.set_value("origin", origin)
def on_ended(self):
self.sender.color = cl.documentation_nvidia
self.sender.width = gol.get_value("length") / 2
self.disable_selection = None
| 2,129 | Python | 32.281249 | 83 | 0.608736 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/sunlight_manipulator.py | __all__ = ["SunlightManipulator"]
from .sunpath_data import SunpathData
from pxr import Gf, Sdf
import omni.kit.commands
from . import gol
class SunlightManipulator:
def __init__(self, pathmodel: SunpathData):
self.path = None
# Get origin value from global dictionary
self.origin = gol.get_value("origin")
self.pathmodel = pathmodel
def add_sun(self):
"""
Add distant light to present sunlight
"""
omni.kit.commands.execute("CreatePrim", prim_type="DistantLight", attributes={"angle": 1.0, "intensity": 3000})
self.path = "/World/DistantLight"
def change_sun(self):
"""
Change distant light property(rotation)
"""
xr, yr = self.pathmodel.dome_rotate_angle()
if [xr, yr] != gol.get_value("dome_angle"):
omni.kit.commands.execute(
"TransformPrimSRT",
path=Sdf.Path("/World/DistantLight"),
new_rotation_euler=Gf.Vec3d(xr, yr, 0),
)
x, y, z = self.pathmodel.cur_sun_position()
if y < 0:
omni.kit.commands.execute(
"ChangeProperty", prop_path=Sdf.Path("/World/DistantLight.visibility"), value="invisible", prev=None
)
else:
omni.kit.commands.execute(
"ChangeProperty", prop_path=Sdf.Path("/World/DistantLight.visibility"), value="inherited", prev=None
)
gol.set_value("dome_angle", [xr, yr])
def show_sun(self):
"""
The method to add light and change it's property
"""
if self.path is None:
self.add_sun()
self.change_sun()
def del_sun(self):
"""
the method to delete exisit distant light
"""
if self.path is not None:
omni.kit.commands.execute("DeletePrims", paths=["/World/DistantLight"])
self.path = None
| 1,974 | Python | 30.349206 | 120 | 0.556231 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/style.py | __all__ = ["sunpath_window_style"]
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import omni.kit.app
import omni.ui as ui
import pathlib
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
# Pre-defined constants. It's possible to change them runtime.
cl.slider_bg_color = cl(0.28, 0.28, 0.28, 0.0)
cl.window_bg_color = cl(0.2, 0.2, 0.2, 1.0)
cl.sunpath_window_attribute_bg = cl(0, 0, 0)
cl.sunpath_window_attribute_fg = cl(1.0, 1.0, 1.0, 0.3)
cl.sunpath_window_hovered = cl(0.95, 0.95, 0.95, 1.0)
cl.sunpath_window_item = cl(0.65, 0.65, 0.65, 1.0)
fl.sunpath_window_attr_hspacing = 15
fl.sunpath_window_attr_spacing = 1
fl.sunpath_window_group_spacing = 2
fl.border_radius = 3
fl.outer_frame_padding = 8
url.sunpath_window_icon_closed = f"{EXTENSION_FOLDER_PATH}/icons/closed.svg"
url.sunpath_window_icon_opened = f"{EXTENSION_FOLDER_PATH}/icons/opened.svg"
url.diag_bg_lines_texture = f"{EXTENSION_FOLDER_PATH}/icons/diagonal_texture.png"
url.button_update = f"{EXTENSION_FOLDER_PATH}/icons/update.png"
url.extension_tittle = f"{EXTENSION_FOLDER_PATH}/icons/window_tittle.png"
extension_tittle = f"{EXTENSION_FOLDER_PATH}/icons/test.png"
# The main style dict
sunpath_window_style = {
"CheckBox": {
"background_color": cl.sunpath_window_item,
"selected_color": cl.beige,
},
"CheckBox:hovered": {"background_color": cl.beige},
"Button": {
"background_color": cl.sunpath_window_attribute_fg,
"border_radius": 4,
"margin_height": 2,
"margin_width": 10,
"padding": 2,
},
"Button:hovered": {"background_color": cl.beige},
"Button:pressed": {"background_color": cl.sunpath_window_item},
"Button.Label": {"alignment": ui.Alignment.CENTER_BOTTOM},
"Button.Image::attribute_set": {
"image_url": url.button_update,
},
"Label::attribute_name": {
"font_size": 14,
"color": cl.sunpath_window_item,
"alignment": ui.Alignment.RIGHT_CENTER,
"margin_height": fl.sunpath_window_attr_spacing,
"margin_width": fl.sunpath_window_attr_hspacing,
},
"CollapsableFrame::group": {
"margin_height": 5,
"background_color": cl.slider_bg_color,
},
"ScrollingFrame::window_bg": {
"background_color": cl.window_bg_color,
"padding": fl.outer_frame_padding,
"border_radius": 20,
},
"Label::attribute_name:hovered": {"color": cl.sunpath_window_hovered},
"Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER},
"HeaderLine": {"color": cl(0.5, 0.5, 0.5, 0.5)},
"Slider": {
"background_color": cl.slider_bg_color,
"secondary_color": cl.beige,
"secondary_selected_color": cl.sunpath_window_item,
"color": 0x00000000,
"draw_mode": ui.SliderDrawMode.HANDLE,
"border_radius": fl.border_radius,
"corner_flag": ui.CornerFlag.LEFT,
"margin_height": 4,
},
"Image::slider_bg_texture": {
"image_url": url.diag_bg_lines_texture,
"border_radius": fl.border_radius,
"margin_height": 13,
},
"Field": {
"background_color": 0x00000000,
"color": cl.sunpath_window_item,
"margin_height": 4,
"margin_width": 5,
"border_radius": fl.border_radius,
},
"Image::extension_tittle": {"image_url": url.extension_tittle, "margin": 10},
"Image::collapsable_opened": {"color": cl.sunpath_window_item, "image_url": url.sunpath_window_icon_opened},
"Image::collapsable_closed": {"color": cl.sunpath_window_item, "image_url": url.sunpath_window_icon_closed},
}
| 3,718 | Python | 35.821782 | 112 | 0.640129 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/sunpath_data.py | __all__ = ["SunpathData"]
import omni
# Use this method to import pyephem-sunpath packages
omni.kit.pipapi.install("pyephem-sunpath", None, False, False, None, True, True, None)
import math
from datetime import datetime
from pyephem_sunpath.sunpath import sunpos, sunrise, sunset
class SunpathData:
"""Generate sunpath data"""
def __init__(self, datevalue, hour, min, lon, lat):
self.datevalue = datevalue
self.year = datetime.now().year
self.hour = hour
self.lat = lat
self.lon = lon
self.min = min
# Compute the timezone
self.tz = round(self.lon / 15)
def set_date(self, value):
"""
The method to reset date parameter
"""
self.datevalue = value
def set_hour(self, value):
"""
The method to reset hour parameter
"""
self.hour = value
def set_min(self, value):
"""
The method to reset minite parameter
"""
self.min = value
def set_longitude(self, value):
"""
The method to reset longitude parameter
"""
self.lon = value
def set_latitude(self, value):
"""
The method to reset latitude parameter
"""
self.lat = value
@staticmethod
def calc_xyz(alt, azm):
"""
Convert spherical coordinates to Cartesian coordinates
"""
x_val = math.sin((azm - 180) * math.pi / 180)
y_val = math.cos((azm - 180) * math.pi / 180)
z_val = math.tan(alt * math.pi / 180)
length = (x_val**2 + y_val**2 + z_val**2) ** 0.5
return [-x_val / length, z_val / length, y_val / length]
def dome_rotate_angle(self):
"""
Compute dome rotate angle
"""
month, day = self.slider_to_datetime(self.datevalue)
thetime = datetime(self.year, month, day, self.hour, self.min)
alt, azm = sunpos(thetime, self.lat, self.lon, self.tz, dst=False)
return -alt, 180 - azm
def get_sun_position(self, thetime, lat, lon, tz):
"""
Get sun position of exact time
"""
alt, azm = sunpos(thetime, lat, lon, tz, dst=False)
position = self.calc_xyz(alt, azm)
return position
def cur_sun_position(self):
"""
Get sun position of current time(input)
"""
month, day = self.slider_to_datetime(self.datevalue)
thetime = datetime(self.year, month, day, self.hour, self.min)
return self.get_sun_position(thetime, self.lat, self.lon, self.tz)
def all_day_position(self, datevalue):
"""
Get sun posion of all day(exact date)
"""
points = []
month, day = self.slider_to_datetime(datevalue)
for t in range(24):
for m in range(0, 60, 5):
thetime = datetime(self.year, month, day, t, m)
pos = self.get_sun_position(thetime, self.lat, self.lon, self.tz)
if pos[1] >= 0:
points.append(pos)
return points
def all_year_sametime_position(self, hour):
"""
Get all year sametime position
"""
points = []
for d in range(1, 366, 2):
month, day = self.slider_to_datetime(d)
thetime = datetime(self.year, month, day, hour)
pos = self.get_sun_position(thetime, self.lat, self.lon, self.tz)
if pos[1] >= 0:
points.append(pos)
if len(points) > 0:
points.append(points[0])
return points
def get_cur_time(self):
"""
Get current datetime(input)
"""
month, day = self.slider_to_datetime(self.datevalue)
thetime = datetime(self.year, month, day, self.hour, self.min)
return thetime
def get_sunrise_time(self):
"""
Get sunrise time of exact date
"""
month, day = self.slider_to_datetime(self.datevalue)
thetime = datetime(self.year, month, day, self.hour, self.min)
return sunrise(thetime, self.lat, self.lon, self.tz, dst=False).time()
def get_sunset_time(self):
"""
Get sunset time of exact date
"""
month, day = self.slider_to_datetime(self.datevalue)
thetime = datetime(self.year, month, day, self.hour, self.min)
return sunset(thetime, self.lat, self.lon, self.tz, dst=False).time()
@staticmethod
def slider_to_datetime(datevalue):
"""
Convert slider value to datetime
"""
if datevalue <= 31:
return [1, datevalue]
if datevalue > 31 and datevalue <= 59:
return [2, datevalue - 31]
if datevalue > 59 and datevalue <= 90:
return [3, datevalue - 59]
if datevalue > 90 and datevalue <= 120:
return [4, datevalue - 90]
if datevalue > 120 and datevalue <= 151:
return [5, datevalue - 120]
if datevalue > 151 and datevalue <= 181:
return [6, datevalue - 151]
if datevalue > 181 and datevalue <= 212:
return [7, datevalue - 181]
if datevalue > 212 and datevalue <= 243:
return [8, datevalue - 212]
if datevalue > 243 and datevalue <= 273:
return [9, datevalue - 243]
if datevalue > 273 and datevalue <= 304:
return [10, datevalue - 273]
if datevalue > 304 and datevalue <= 334:
return [11, datevalue - 304]
if datevalue > 334 and datevalue <= 365:
return [12, datevalue - 334]
| 5,595 | Python | 30.795454 | 86 | 0.55353 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/extension.py | __all__ = ["SunpathExtension"]
from .window import SunpathWindow
from functools import partial
import asyncio
import omni.ext
import omni.kit.ui
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportScene
from .sunlight_manipulator import SunlightManipulator
# Import global dictionary
from . import gol
# Initialize dictionary
gol._init()
class SunpathExtension(omni.ext.IExt):
WINDOW_NAME = "sunpath extension".upper()
MENU_PATH = f"Window/{WINDOW_NAME}"
def __init__(self):
self._window = None
# Get acive viewport window
self.viewport_window = get_active_viewport_window()
self._viewport_scene = None
# Preset display toggle
self._show_path = False
self._show_sun = False
# Preset path model and sunlight model
self.pathmodel = gol.get_value("pathmodel")
self.sunlightmodel = SunlightManipulator(self.pathmodel)
def on_startup(self, ext_id):
# Add ext_id key value
self.ext_id = ext_id
# The ability to show up the window if the system requires it. We use it
# in QuickLayout.
ui.Workspace.set_show_window_fn(SunpathExtension.WINDOW_NAME, partial(self.show_window, None))
# Put the new menu
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(SunpathExtension.MENU_PATH, self.show_window, toggle=True, value=True)
# Show the window. It will call `self.show_window`
ui.Workspace.show_window(SunpathExtension.WINDOW_NAME)
def on_shutdown(self):
"""
Destroy viewport scene and window
"""
if self._viewport_scene:
self._viewport_scene.destroy()
self._viewport_scene = None
self._menu = None
if self._window:
self._window.destroy()
self._window = None
# Deregister the function that shows the window from omni.ui
ui.Workspace.set_show_window_fn(SunpathExtension.WINDOW_NAME, None)
def sunpath_toggle(self, value):
"""
The method to change the toggle, this dropped into the window
"""
if value:
self._show_path = value
self._viewport_scene = ViewportScene(self.viewport_window, self.ext_id, self.pathmodel)
else:
self._show_path = value
self._viewport_scene.destroy()
self._viewport_scene = None
def sunlight_toggle(self, value):
"""
The method to change the toggle, this dropped into the window file
"""
if value:
self._show_sun = value
self.sunlightmodel.show_sun()
else:
self._show_sun = value
self.sunlightmodel.del_sun()
gol.set_value("sun_state", value)
def update_viewport_scene(self):
"""
The method to upadate viewport scene
"""
if self._show_sun:
self.sunlightmodel = SunlightManipulator(self.pathmodel)
self.sunlightmodel.path = "/World/DistantLight"
self.sunlightmodel.show_sun()
if self._show_path:
if self._viewport_scene is not None:
self._viewport_scene.destroy()
self._viewport_scene = ViewportScene(self.viewport_window, self.ext_id, self.pathmodel)
def update_parameter(self, valtype, val):
"""
The method to change parameters and update viewport scene, this dropped into window file
"""
if valtype is None:
pass
if valtype == "show_info":
gol.set_value("show_info", val)
if valtype == 0:
gol.set_value("color_r", val * 255)
if valtype == 1:
gol.set_value("color_g", val * 255)
if valtype == 2:
gol.set_value("color_b", val * 255)
if valtype == "scale":
gol.set_value("scale", val)
if valtype == "longitude":
self.pathmodel.set_longitude(val)
if valtype == "latitude":
self.pathmodel.set_latitude(val)
if valtype == "date":
self.pathmodel.set_date(val)
if valtype == "hour":
self.pathmodel.set_hour(val)
# Save pathmodel to dictionary
gol.set_value("pathmodel", self.pathmodel)
if valtype == "minite":
self.pathmodel.set_min(val)
self.update_viewport_scene()
def _set_menu(self, value):
"""
Set the menu to create this window on and off
"""
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(SunpathExtension.MENU_PATH, value)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._window:
self._window.destroy()
self._window = None
def _visiblity_changed_fn(self, visible):
# Called when the user pressed "X"
self._set_menu(visible)
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def show_window(self, menu, value):
"""
Show window and deliver some method to it
"""
if value:
self._window = SunpathWindow(
SunpathExtension.WINDOW_NAME,
delegate_1=self.update_parameter,
delegate_2=self.sunpath_toggle,
delegate_3=self.sunlight_toggle,
delegate_4=self.update_viewport_scene,
width=360,
height=590,
)
self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
elif self._window:
self._window.visible = False
| 6,004 | Python | 32.547486 | 116 | 0.590273 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/viewport_scene.py | __all__ = ["ViewportScene"]
from omni.ui import scene as sc
import omni.ui as ui
from .sunpath_data import SunpathData
from .draw_sunpath import DrawSunpath
from .draw_sphere import draw_movable_sphere
from .gesture import MoveGesture
from . import gol
class ViewportScene:
def __init__(self, viewport_window: ui.Window, ext_id: str, pathmodel: SunpathData) -> None:
self._scene_view = None
self._viewport_window = viewport_window
with self._viewport_window.get_frame(ext_id):
self._scene_view = sc.SceneView()
with self._scene_view.scene:
transform = sc.Transform()
move_ges = MoveGesture(transform)
with transform:
DrawSunpath(pathmodel, move_ges)
if gol.get_value("sun_state"):
draw_movable_sphere()
self._viewport_window.viewport_api.add_scene_view(self._scene_view)
def __del__(self):
self.destroy()
def destroy(self):
if self._scene_view:
self._scene_view.scene.clear()
if self._viewport_window:
self._viewport_window.viewport_api.remove_scene_view(self._scene_view)
self._viewport_window = None
self._scene_view = None
| 1,289 | Python | 32.076922 | 96 | 0.60512 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/draw_sphere.py | import math
from math import sin, cos
import numpy as np
from omni.ui import scene as sc
from omni.ui import color as cl
from . import gol
def rotate_matrix_z(angle):
"""
Build Z-axis rotation matrix
"""
sep = 2 * math.pi / 360
Rz = [
[cos(sep * angle), -sin(sep * angle), 0],
[sin(sep * angle), cos(sep * angle), 0],
[0, 0, 1],
]
return np.array(Rz)
def rotate_points(points, angle):
"""
rotate a point list
"""
rotated_pts = []
for pt in points:
pt_arr = np.array(pt)
Rz = rotate_matrix_z(angle)
rotated_pt = list(np.dot(Rz, pt_arr))
rotated_pts.append(rotated_pt)
return rotated_pts
def generate_circle_pts(offset, step, scale):
"""
Generate the points that make up the circle
"""
points = []
sep = 2 * math.pi / 360
for angle in range(0, 361, step):
x = scale * math.cos(sep * angle) * offset
z = scale * math.sin(sep * angle) * offset
points.append([round(x, 3), 0, round(z, 3)])
return points
def draw_base_sphere():
"""
Draw a shpere base on [0,0,0]
"""
scale = gol.get_value("scale") * 200
points = generate_circle_pts(0.1, 5, scale)
sc.Curve(points, thicknesses=[1], colors=[cl.beige], curve_type=sc.Curve.CurveType.LINEAR)
for angle in range(0, 361, 4):
r_pts = rotate_points(points, angle)
sc.Curve(r_pts, thicknesses=[1], colors=[cl.beige], curve_type=sc.Curve.CurveType.LINEAR)
def points_modify(points):
"""
Change the coordinates of the point based on the origin and scale
"""
scale = gol.get_value("scale") * 200
origin = gol.get_value("origin")
s_points = []
for pt in points:
x = pt[0] * scale + origin[0]
y = pt[1] * scale + origin[1]
z = pt[2] * scale + origin[2]
newpt = [x, y, z]
s_points.append(newpt)
return s_points
def draw_movable_sphere():
"""
According parametes to move sphere positon
"""
pathmodel = gol.get_value("pathmodel")
sun_pos = pathmodel.cur_sun_position()
x, y, z = points_modify([sun_pos])[0]
if y > 0:
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(x, y, z)):
draw_base_sphere()
| 2,278 | Python | 24.322222 | 97 | 0.579017 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/draw_sunpath.py | __all__ = ["DrawSunpath"]
import math
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
from .sunpath_data import SunpathData
from . import gol
class DrawSunpath:
def __init__(self, pathmodel: SunpathData, move_ges):
self.move_ges = move_ges
self.pathmodel = pathmodel
self.origin = gol.get_value("origin")
self.scale = gol.get_value("scale") * 200
self.color = cl(*gol.get_value("color"))
# Draw sunpath
self.draw_anydate_path(self.pathmodel, self.pathmodel.datevalue, cl.documentation_nvidia, 1.5)
self.draw_paths()
self.draw_compass()
if gol.get_value("show_info"):
self.show_info()
def sort_points(self, points):
"""
Resort the points to make sure they connect to a reasonable curve
"""
x_points = list(filter(lambda p: p[0] < 0, points))
if len(x_points) != 0:
y_min = min(x_points, key=lambda p: p[1])
id = points.index(y_min) + 1
return points[id:] + points[:id]
return points
def points_modify(self, points):
"""
Change the coordinates of the point based on the origin
"""
s_points = []
for pt in points:
x = pt[0] * self.scale + self.origin[0]
y = pt[1] * self.scale + self.origin[1]
z = pt[2] * self.scale + self.origin[2]
newpt = [x, y, z]
s_points.append(newpt)
return s_points
def generate_circle_pts(self, offset, step):
"""
Generate the points that make up the circle or present anchor point
"""
points = []
sep = 2 * math.pi / 360
for angle in range(0, 361, step):
x = self.origin[0] + self.scale * math.cos(sep * angle) * offset
z = self.origin[2] + self.scale * math.sin(sep * angle) * offset
points.append([round(x, 3), 0, round(z, 3)])
return points
def draw_circle(self, offset, step, color, thickness):
"""
Connet points to draw a circle
"""
points = self.generate_circle_pts(offset, step)
sc.Curve(points, thicknesses=[thickness], colors=[color], curve_type=sc.Curve.CurveType.LINEAR)
def draw_drections(self):
"""
Draw cross line and mark main directions
"""
# Generate anchor point
points_a = self.generate_circle_pts(1.15, 90)
points_b = self.generate_circle_pts(1.25, 90)
points_c = self.generate_circle_pts(1.15, 2)
points_t = self.generate_circle_pts(1.33, 90)
for pt in points_b:
sc.Curve([pt, self.origin], thicknesses=[1.0], colors=[cl.gray], curve_type=sc.Curve.CurveType.LINEAR)
arrow = []
for i in range(1, 181, 45):
arrow.append(points_c[i])
# Draw arrow
for p_a, p_b, p_c in zip(points_a, points_b, arrow):
sc.Curve(
[p_b, p_c, p_a, p_b],
thicknesses=[1.5],
colors=[cl.documentation_nvidia],
curve_type=sc.Curve.CurveType.LINEAR,
)
# Draw diretions label
text = ["E", "S", "W", "N"]
for i in range(4):
x, y, z = points_t[i]
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(x, y, z)):
sc.Label(text[i], alignment=ui.Alignment.CENTER, color=cl.documentation_nvidia, size=20)
def draw_drection_mark(self):
"""
Draw degrees directions and add a move gesture
"""
points_a = self.generate_circle_pts(1, 30)
points_b = self.generate_circle_pts(1.06, 30)
points_g = self.generate_circle_pts(1.03, 90)
points_t = self.generate_circle_pts(1.1, 30)
# Compute length of tick-mark line
length = points_b[3][2] - points_a[3][2]
gol.set_value("length", length)
# Add move gesture block
x, y, z = points_g[3]
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(x, y, z)):
sc.Rectangle(
axis=ui.Axis.X,
color=cl.documentation_nvidia,
width=length / 2,
height=length,
gesture=self.move_ges,
)
# Add tick-mark line
for p1, p2 in zip(points_a, points_b):
sc.Curve(
[p1, p2], thicknesses=[1.5], colors=[cl.documentation_nvidia], curve_type=sc.Curve.CurveType.LINEAR
)
# Add degree label
text = [f"{d}" for d in list(range(0, 361, 30))]
text = text[3:12] + text[:3]
for i in range(12):
x, y, z = points_t[i]
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(x, y, z)):
sc.Label(text[i], alignment=ui.Alignment.CENTER, color=cl.documentation_nvidia, size=12)
def draw_anydate_path(self, pathmodel: SunpathData, datevalue: int, color, thickness):
"""
The method to draw the path of sun on exact date
"""
points = pathmodel.all_day_position(datevalue)
sort_pts = self.sort_points(points)
scale_pts = self.points_modify(sort_pts)
if len(scale_pts) > 0:
sc.Curve(scale_pts, thicknesses=[thickness], colors=[color], curve_type=sc.Curve.CurveType.LINEAR)
def draw_sametime_position(self, pathmodel: SunpathData, hour, color, thickness):
"""
The method to draw the path of sun on diffrent date but in same time,'8' shape curve
"""
points = pathmodel.all_year_sametime_position(hour)
sort_pts = self.sort_points(points)
scale_pts = self.points_modify(sort_pts)
if len(scale_pts) > 0:
sc.Curve(scale_pts, thicknesses=[thickness], colors=[color], curve_type=sc.Curve.CurveType.LINEAR)
def draw_multi_sametime_position(self, pathmodel: SunpathData, color, thickness):
"""
Draw twenty four '8' shape curves
"""
for h in range(0, 24, 1):
self.draw_sametime_position(pathmodel, h, color, thickness)
def draw_paths(self):
"""
Draw diffrent path
"""
self.draw_anydate_path(self.pathmodel, 172, self.color, 1.3)
self.draw_anydate_path(self.pathmodel, 355, self.color, 1.3)
self.draw_anydate_path(self.pathmodel, 80, self.color, 1.3)
self.draw_anydate_path(self.pathmodel, 110, cl.grey, 1.0)
self.draw_anydate_path(self.pathmodel, 295, cl.grey, 1.0)
self.draw_multi_sametime_position(self.pathmodel, self.color, 0.5)
def draw_compass(self):
"""
Draw entire compass
"""
self.draw_circle(1, 1, self.color, 1.1)
self.draw_circle(1.04, 1, self.color, 1.1)
self.draw_drections()
self.draw_drection_mark()
def show_info(self):
"""
Draw information label
"""
anchor = self.generate_circle_pts(1.5, 90)
anchor_e = anchor[0]
anchor_w = anchor[2]
anchor_n = anchor[3]
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*anchor_e)):
sc.Label(
f"sunrise: {self.pathmodel.get_sunrise_time()}".upper(),
alignment=ui.Alignment.RIGHT_CENTER,
color=cl.beige,
size=16,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*anchor_w)):
sc.Label(
f"sunset: {self.pathmodel.get_sunset_time()}".upper(),
alignment=ui.Alignment.LEFT_CENTER,
color=cl.beige,
size=16,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*anchor_n)):
sc.Label(
f"datetime: {self.pathmodel.get_cur_time()}".upper(),
alignment=ui.Alignment.LEFT_CENTER,
color=cl.beige,
size=16,
)
| 7,998 | Python | 36.55399 | 115 | 0.56064 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/window.py | __all__ = ["SunpathWindow"]
import omni.ui as ui
from functools import partial
from .style import sunpath_window_style
from . import gol
LABEL_WIDTH = 120
SPACING = 4
class SunpathWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate_1=None, delegate_2=None, delegate_3=None, delegate_4=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = sunpath_window_style
# Set the function that is called to build widgets when the window is visible
self.frame.set_build_fn(self._build_fn)
# Methods to change parameters and update viewport secene
self.update = delegate_1
self.show_path = delegate_2
self.show_sun = delegate_3
self.update_scene = delegate_4
def destroy(self):
# It will destroy all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
def _build_collapsable_header(self, collapsed, title):
"""Build a custom title of CollapsableFrame"""
with ui.VStack():
ui.Spacer(height=8)
with ui.HStack():
ui.Label(title, name="collapsable_name")
if collapsed:
image_name = "collapsable_opened"
else:
image_name = "collapsable_closed"
ui.Image(name=image_name, width=10, height=10)
ui.Spacer(height=8)
ui.Line(style_type_name_override="HeaderLine")
def _build_display(self):
"""Build the widgets of the "display" group"""
with ui.CollapsableFrame("display".upper(), name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=8)
with ui.HStack():
with ui.VStack():
with ui.HStack():
ui.Label("Show Path", name="attribute_name", width=self.label_width)
sp = ui.CheckBox(name="attribute_bool").model
sp.add_value_changed_fn(lambda m: self.show_path(m.get_value_as_bool()))
ui.Spacer(height=8)
with ui.HStack():
ui.Label("Show Sun", name="attribute_name", width=self.label_width)
ss = ui.CheckBox(name="attribute_bool").model
ss.add_value_changed_fn(lambda m: self.show_sun(m.get_value_as_bool()))
ss.add_value_changed_fn(lambda m: self.update_scene())
ui.Spacer(height=8)
with ui.HStack():
ui.Label("Show Info", name="attribute_name", width=self.label_width)
si = ui.CheckBox(name="attribute_bool").model
si.add_value_changed_fn(lambda m: self.update("show_info", m.get_value_as_bool()))
with ui.ZStack():
ui.Image(
name="extension_tittle",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
width=ui.Percent(100),
)
ui.Spacer(height=8)
with ui.HStack():
ui.Label("Path Color", name="attribute_name", width=self.label_width)
color_model = ui.ColorWidget(1, 1, 1, width=0, height=0).model
r_model = color_model.get_item_children()[0]
r_component = color_model.get_item_value_model(r_model)
r_component.add_value_changed_fn(lambda m: gol.set_item("color", 0, m.get_value_as_float()))
g_model = color_model.get_item_children()[1]
g_component = color_model.get_item_value_model(g_model)
g_component.add_value_changed_fn(lambda m: gol.set_item("color", 1, m.get_value_as_float()))
b_model = color_model.get_item_children()[2]
b_component = color_model.get_item_value_model(b_model)
b_component.add_value_changed_fn(lambda m: gol.set_item("color", 2, m.get_value_as_float()))
ui.Spacer()
ui.Button(
name="attribute_set",
tooltip="update color or update scene",
width=60,
clicked_fn=partial(self.update, None, None),
)
ui.Spacer(height=4)
with ui.HStack():
ui.Label("Path Scale", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(name="slider_bg_texture", fill_policy=ui.FillPolicy.STRETCH, width=ui.Percent(100))
ps_slider = ui.FloatSlider(name="attribute_slider", min=1, max=100, setp=1).model
ps_slider.set_value(50)
ps_slider.add_value_changed_fn(lambda m: self.update("scale", m.get_value_as_float()))
ui.FloatField(model=ps_slider, width=60)
def _build_location(self):
"""Build the widgets of the "location" group"""
with ui.CollapsableFrame("location".upper(), name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=8)
with ui.HStack():
ui.Label("Longitude", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(name="slider_bg_texture", fill_policy=ui.FillPolicy.STRETCH, width=ui.Percent(100))
lon_slider = ui.FloatSlider(name="attribute_slider", min=-180, max=180, setp=0.01).model
lon_slider.set_value(112.22)
lon_slider.add_value_changed_fn(lambda m: self.update("longitude", m.get_value_as_float()))
ui.FloatField(model=lon_slider, width=60)
ui.Spacer(height=2)
with ui.HStack():
ui.Label("Latitude", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(
name="slider_bg_texture",
fill_policy=ui.FillPolicy.STRETCH,
width=ui.Percent(100),
)
lat_slider = ui.FloatSlider(name="attribute_slider", min=-90, max=90, step=0.01).model
lat_slider.set_value(22.22)
lat_slider.add_value_changed_fn(lambda m: self.update("latitude", m.get_value_as_float()))
ui.FloatField(model=lat_slider, width=60)
def _build_datetime(self):
"""Build the widgets of the "datetime" group"""
with ui.CollapsableFrame("datetime".upper(), name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=8)
with ui.HStack():
ui.Label("Date", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(
name="slider_bg_texture",
fill_policy=ui.FillPolicy.STRETCH,
width=ui.Percent(100),
)
dt_slider = ui.IntSlider(
name="attribute_slider",
min=1,
max=365,
).model
dt_slider.set_value(175)
dt_slider.add_value_changed_fn(lambda m: self.update("date", m.get_value_as_int()))
ui.IntField(model=dt_slider, width=60)
ui.Spacer(height=2)
with ui.HStack():
ui.Label("Hour", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(
name="slider_bg_texture",
fill_policy=ui.FillPolicy.STRETCH,
width=ui.Percent(100),
)
hr_slider = ui.IntSlider(name="attribute_slider", min=0, max=23).model
hr_slider.set_value(12)
hr_slider.add_value_changed_fn(lambda m: self.update("hour", m.get_value_as_int()))
ui.IntField(model=hr_slider, width=60)
ui.Spacer(height=2)
with ui.HStack():
ui.Label("Minite", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(
name="slider_bg_texture",
fill_policy=ui.FillPolicy.STRETCH,
width=ui.Percent(100),
)
mt_slider = ui.IntSlider(name="attribute_slider", min=0, max=59).model
mt_slider.set_value(30)
mt_slider.add_value_changed_fn(lambda m: self.update("minite", m.get_value_as_int()))
ui.IntField(model=mt_slider, width=60)
def _build_fn(self):
"""
The method that is called to build all the UI once the window is visible.
"""
with ui.ScrollingFrame(name="window_bg", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF):
with ui.ScrollingFrame():
with ui.VStack(height=0):
self._build_display()
self._build_location()
self._build_datetime()
| 10,277 | Python | 48.893204 | 118 | 0.504427 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/config/extension.toml | [package]
version = "2.0.0"
authors = ["HNADI-Link"]
title = "SunPath Extension"
description="The Extension simulate the sunlight and draw the precise SunPath diagram."
readme = "docs/README.md"
repository = ""
category = "Scene"
keywords = ["kit", "scene", "SunPath"]
changelog = "docs/CHANGELOG.md"
preview_image = "icons/preview.png"
icon = "icons/icon.png"
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.viewport.utility" = {}
"omni.ui.scene" = {}
"omni.usd" = {}
[[python.module]]
name = "hnadi.tools.sunpath" | 517 | TOML | 23.666666 | 87 | 0.686654 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/docs/CHANGELOG.md | # [1.0.0] - 2022-8-18
## Added
* The initial version
# [2.0.0] - 2022-9-7
## Added
* Add Gesture to move SunPath
* Add ColorWidget to change Path color
## Adjusted
* Addjust file structure
* Rebuild UI
* Build a Sphere to represent the Sun
## Optimizated
* Secne update speed
* Repair some bug | 298 | Markdown | 16.588234 | 38 | 0.691275 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/docs/README.md | # Omniverse SunPath Extension
This extension allows to add the SunPath diagram in the viewport window, and the diagram can be updated by setting it's parameters. | 163 | Markdown | 53.666649 | 132 | 0.809816 |
USwampertor/OmniverseJS/README.md | # OmniverseJS
Omniverse Javascript wrapper for public and external purposes
## Overview
The objective of this module is simply to wrap all of the omniverse functionalities in javascript to be used in more platforms than the ones available (python and C/C++)
A lot of applications from the game development industry work in javascript, and with this we can take advantage of the omniverse platform even more.
| 410 | Markdown | 50.374994 | 169 | 0.809756 |
USwampertor/OmniverseJS/ov/bindings-python/omni/usd_resolver/__init__.py | import os
from typing import Tuple, List, Callable
if hasattr(os, "add_dll_directory"):
scriptdir = os.path.dirname(os.path.realpath(__file__))
dlldir = os.path.abspath(os.path.join(scriptdir, "../../.."))
with os.add_dll_directory(dlldir):
from ._omni_usd_resolver import *
else:
from ._omni_usd_resolver import *
| 341 | Python | 27.499998 | 65 | 0.662757 |
USwampertor/OmniverseJS/ov/bindings-python/omni/client/__init__.py | # fmt: off
import os
import platform
import sys
import asyncio
import concurrent.futures
from typing import Tuple, List, Callable
if hasattr(os, "add_dll_directory"):
scriptdir = os.path.dirname(os.path.realpath(__file__))
dlldir = os.path.abspath(os.path.join(scriptdir, "../../.."))
with os.add_dll_directory(dlldir):
from ._omniclient import *
else:
from ._omniclient import *
def get_server_info(url: str) -> Tuple[Result, ServerInfo]:
"""Deprecated: Use :py:func:`omni.client.get_server_info_async` or :py:func:`omni.client.get_server_info_with_callback` instead.
"""
ret = None
def get_server_info_cb(result, info):
nonlocal ret
ret = (result, info)
get_server_info_with_callback(url=url, callback=get_server_info_cb).wait()
return ret
async def get_server_info_async(url: str) -> Tuple[Result, ServerInfo]:
"""Asynchronously Get Server Info
See: :py:func:`omni.client.get_server_info_with_callback`
"""
f = concurrent.futures.Future()
def get_server_info_cb(result, info):
if not f.done():
f.set_result((result, info))
get_server_info_with_callback(url=url, callback=get_server_info_cb)
return await asyncio.wrap_future(f)
def list(url: str) -> Tuple[Result, Tuple[ListEntry]]:
"""Deprecated: Use :py:func:`omni.client.list_async` or :py:func:`omni.client.list_with_callback` instead.
"""
ret = None
def list_cb(result, entries):
nonlocal ret
ret = (result, entries)
list_with_callback(url=url, callback=list_cb).wait()
return ret
async def list_async(url: str) -> Tuple[Result, Tuple[ListEntry]]:
"""Asynchronously List contents of a folder
See: :py:func:`omni.client.list_with_callback`
"""
f = concurrent.futures.Future()
def list_cb(result, entries):
if not f.done():
f.set_result((result, entries))
list_with_callback(url=url, callback=list_cb)
return await asyncio.wrap_future(f)
def stat(url: str) -> Tuple[Result, ListEntry]:
"""Deprecated: Use :py:func:`omni.client.stat_async` or :py:func:`omni.client.stat_with_callback` instead.
"""
ret = None
def stat_cb(result, entry):
nonlocal ret
ret = (result, entry)
stat_with_callback(url=url, callback=stat_cb).wait()
return ret
async def stat_async(url: str) -> Tuple[Result, ListEntry]:
"""Asynchronously Retrieve information about a single item
See: :py:func:`omni.client.stat_with_callback`
"""
f = concurrent.futures.Future()
def stat_cb(result, entry):
if not f.done():
f.set_result((result, entry))
stat_with_callback(url=url, callback=stat_cb)
return await asyncio.wrap_future(f)
def delete(url: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.delete_async` or :py:func:`omni.client.delete_with_callback` instead.
"""
ret = None
def delete_cb(result):
nonlocal ret
ret = result
delete_with_callback(url=url, callback=delete_cb).wait()
return ret
async def delete_async(url: str) -> Result:
"""Asynchronously Delete an item
See: :py:func:`omni.client.delete_with_callback`
"""
f = concurrent.futures.Future()
def delete_cb(result):
if not f.done():
f.set_result(result)
delete_with_callback(url=url, callback=delete_cb)
return await asyncio.wrap_future(f)
def create_folder(url: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.create_folder_async` or :py:func:`omni.client.create_folder_with_callback` instead.
"""
ret = None
def create_folder_cb(result):
nonlocal ret
ret = result
create_folder_with_callback(url=url, callback=create_folder_cb).wait()
return ret
async def create_folder_async(url: str) -> Result:
"""Asynchronously Create a folder
See: :py:func:`omni.client.create_folder_with_callback`
"""
f = concurrent.futures.Future()
def create_folder_cb(result):
if not f.done():
f.set_result(result)
create_folder_with_callback(url=url, callback=create_folder_cb)
return await asyncio.wrap_future(f)
def copy(src_url: str, dst_url: str, behavior: CopyBehavior = CopyBehavior.ERROR_IF_EXISTS, message: str = "") -> Result:
"""Deprecated: Use :py:func:`omni.client.copy_async` or :py:func:`omni.client.copy_with_callback` instead.
"""
ret = None
def copy_cb(result):
nonlocal ret
ret = result
copy_with_callback(src_url=src_url, dst_url=dst_url, behavior=behavior, message=message, callback=copy_cb).wait()
return ret
async def copy_async(src_url: str, dst_url: str, behavior: CopyBehavior = CopyBehavior.ERROR_IF_EXISTS, message: str = "") -> Result:
"""Asynchronously Copy an item from ``src_url`` to ``dst_url``
See: :py:func:`omni.client.copy_with_callback`
"""
f = concurrent.futures.Future()
def copy_cb(result):
if not f.done():
f.set_result(result)
copy_with_callback(src_url=src_url, dst_url=dst_url, behavior=behavior, message=message, callback=copy_cb)
return await asyncio.wrap_future(f)
def move(src_url: str, dst_url: str, behavior: CopyBehavior = CopyBehavior.ERROR_IF_EXISTS, message: str = "") -> Tuple[Result, bool]:
"""Deprecated: Use :py:func:`omni.client.move_async` or :py:func:`omni.client.move_with_callback` instead.
"""
ret = None
def move_cb(result, copied):
nonlocal ret
ret = (result, copied)
move_with_callback(src_url=src_url, dst_url=dst_url, behavior=behavior, message=message, callback=move_cb).wait()
return ret
async def move_async(src_url: str, dst_url: str, behavior: CopyBehavior = CopyBehavior.ERROR_IF_EXISTS, message: str = "") -> Tuple[Result, bool]:
"""Asynchronously Move an item from ``src_url`` to ``dst_url``
See: :py:func:`omni.client.move_with_callback`
"""
f = concurrent.futures.Future()
def move_cb(result, copied):
if not f.done():
f.set_result((result, copied))
move_with_callback(src_url=src_url, dst_url=dst_url, behavior=behavior, message=message, callback=move_cb)
return await asyncio.wrap_future(f)
def get_local_file(url: str) -> Tuple[Result, str]:
"""Deprecated: Use :py:func:`omni.client.get_local_file_async` or :py:func:`omni.client.get_local_file_with_callback` instead.
"""
ret = None
def get_local_file_cb(result, local_file_path):
nonlocal ret
ret = (result, local_file_path)
get_local_file_with_callback(url=url, callback=get_local_file_cb).wait()
return ret
async def get_local_file_async(url: str) -> Tuple[Result, str]:
"""Asynchronously Get local file path from a URL
See: :py:func:`omni.client.get_local_file_with_callback`
"""
f = concurrent.futures.Future()
def get_local_file_cb(result, local_file_path):
if not f.done():
f.set_result((result, local_file_path))
get_local_file_with_callback(url=url, callback=get_local_file_cb)
return await asyncio.wrap_future(f)
def read_file(url: str) -> Tuple[Result, str, Content]:
"""Deprecated: Use :py:func:`omni.client.read_file_async` or :py:func:`omni.client.read_file_with_callback` instead.
"""
ret = None
def read_file_cb(result, version, content):
nonlocal ret
ret = (result, version, content)
read_file_with_callback(url=url, callback=read_file_cb).wait()
return ret
async def read_file_async(url: str) -> Tuple[Result, str, Content]:
"""Asynchronously Read a file
See: :py:func:`omni.client.read_file_with_callback`
"""
f = concurrent.futures.Future()
def read_file_cb(result, version, content):
if not f.done():
f.set_result((result, version, content))
read_file_with_callback(url=url, callback=read_file_cb)
return await asyncio.wrap_future(f)
def write_file(url: str, content: bytes, message: str = "") -> Result:
"""Deprecated: Use :py:func:`omni.client.write_file_async` or :py:func:`omni.client.write_file_with_callback` instead.
"""
ret = None
def write_file_cb(result):
nonlocal ret
ret = result
write_file_with_callback(url=url, content=content, message=message, callback=write_file_cb).wait()
return ret
async def write_file_async(url: str, content: bytes, message: str = "") -> Result:
"""Asynchronously Write a file
See: :py:func:`omni.client.write_file_with_callback`
"""
f = concurrent.futures.Future()
def write_file_cb(result):
if not f.done():
f.set_result(result)
write_file_with_callback(url=url, content=content, message=message, callback=write_file_cb)
return await asyncio.wrap_future(f)
def get_acls(url: str) -> Tuple[Result, List[AclEntry]]:
"""Deprecated: Use :py:func:`omni.client.get_acls_async` or :py:func:`omni.client.get_acls_with_callback` instead.
"""
ret = None
def get_acls_cb(result, acls):
nonlocal ret
ret = (result, acls)
get_acls_with_callback(url=url, callback=get_acls_cb).wait()
return ret
async def get_acls_async(url: str) -> Tuple[Result, List[AclEntry]]:
"""Asynchronously Get the ACLs for an item
See: :py:func:`omni.client.get_acls_with_callback`
"""
f = concurrent.futures.Future()
def get_acls_cb(result, acls):
if not f.done():
f.set_result((result, acls))
get_acls_with_callback(url=url, callback=get_acls_cb)
return await asyncio.wrap_future(f)
def set_acls(url: str, acls: List[AclEntry]) -> Result:
"""Deprecated: Use :py:func:`omni.client.set_acls_async` or :py:func:`omni.client.set_acls_with_callback` instead.
"""
ret = None
def set_acls_cb(result):
nonlocal ret
ret = result
set_acls_with_callback(url=url, acls=acls, callback=set_acls_cb).wait()
return ret
async def set_acls_async(url: str, acls: List[AclEntry]) -> Result:
"""Asynchronously Set the ACLs for an item
See: :py:func:`omni.client.set_acls_with_callback`
"""
f = concurrent.futures.Future()
def set_acls_cb(result):
if not f.done():
f.set_result(result)
set_acls_with_callback(url=url, acls=acls, callback=set_acls_cb)
return await asyncio.wrap_future(f)
def send_message(join_request_id: int, content: bytes) -> Result:
"""Deprecated: Use :py:func:`omni.client.send_message_async` or :py:func:`omni.client.send_message_with_callback` instead.
"""
ret = None
def send_message_cb(result):
nonlocal ret
ret = result
send_message_with_callback(join_request_id=join_request_id, content=content, callback=send_message_cb).wait()
return ret
async def send_message_async(join_request_id: int, content: bytes) -> Result:
"""Asynchronously Send a message to a channel
See: :py:func:`omni.client.send_message_with_callback`
"""
f = concurrent.futures.Future()
def send_message_cb(result):
if not f.done():
f.set_result(result)
send_message_with_callback(join_request_id=join_request_id, content=content, callback=send_message_cb)
return await asyncio.wrap_future(f)
def list_checkpoints(url: str) -> Tuple[Result, Tuple[ListEntry]]:
"""Deprecated: Use :py:func:`omni.client.list_checkpoints_async` or :py:func:`omni.client.list_checkpoints_with_callback` instead.
"""
ret = None
def list_checkpoints_cb(result, entries):
nonlocal ret
ret = (result, entries)
list_checkpoints_with_callback(url=url, callback=list_checkpoints_cb).wait()
return ret
async def list_checkpoints_async(url: str) -> Tuple[Result, Tuple[ListEntry]]:
"""Asynchronously List the checkpoints of an item
See: :py:func:`omni.client.list_checkpoints_with_callback`
"""
f = concurrent.futures.Future()
def list_checkpoints_cb(result, entries):
if not f.done():
f.set_result((result, entries))
list_checkpoints_with_callback(url=url, callback=list_checkpoints_cb)
return await asyncio.wrap_future(f)
def create_checkpoint(url: str, comment: str, force: bool = False) -> Tuple[Result, str]:
"""Deprecated: Use :py:func:`omni.client.create_checkpoint_async` or :py:func:`omni.client.create_checkpoint_with_callback` instead.
"""
ret = None
def create_checkpoint_cb(result, query):
nonlocal ret
ret = (result, query)
create_checkpoint_with_callback(url=url, comment=comment, force=force, callback=create_checkpoint_cb).wait()
return ret
async def create_checkpoint_async(url: str, comment: str, force: bool = False) -> Tuple[Result, str]:
"""Asynchronously Create a checkpoint of an item
See: :py:func:`omni.client.create_checkpoint_with_callback`
"""
f = concurrent.futures.Future()
def create_checkpoint_cb(result, query):
if not f.done():
f.set_result((result, query))
create_checkpoint_with_callback(url=url, comment=comment, force=force, callback=create_checkpoint_cb)
return await asyncio.wrap_future(f)
def get_groups(url: str) -> Tuple[Result, List[str]]:
"""Deprecated: Use :py:func:`omni.client.get_groups_async` or :py:func:`omni.client.get_groups_with_callback` instead.
"""
ret = None
def get_groups_cb(result, groups):
nonlocal ret
ret = (result, groups)
get_groups_with_callback(url=url, callback=get_groups_cb).wait()
return ret
async def get_groups_async(url: str) -> Tuple[Result, List[str]]:
"""Asynchronously Get a list of all groups
See: :py:func:`omni.client.get_groups_with_callback`
"""
f = concurrent.futures.Future()
def get_groups_cb(result, groups):
if not f.done():
f.set_result((result, groups))
get_groups_with_callback(url=url, callback=get_groups_cb)
return await asyncio.wrap_future(f)
def get_group_users(url: str, group: str) -> Tuple[Result, List[str]]:
"""Deprecated: Use :py:func:`omni.client.get_group_users_async` or :py:func:`omni.client.get_group_users_with_callback` instead.
"""
ret = None
def get_group_users_cb(result, users):
nonlocal ret
ret = (result, users)
get_group_users_with_callback(url=url, group=group, callback=get_group_users_cb).wait()
return ret
async def get_group_users_async(url: str, group: str) -> Tuple[Result, List[str]]:
"""Asynchronously Get a list of all users in a group
See: :py:func:`omni.client.get_group_users_with_callback`
"""
f = concurrent.futures.Future()
def get_group_users_cb(result, users):
if not f.done():
f.set_result((result, users))
get_group_users_with_callback(url=url, group=group, callback=get_group_users_cb)
return await asyncio.wrap_future(f)
def create_group(url: str, group: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.create_group_async` or :py:func:`omni.client.create_group_with_callback` instead.
"""
ret = None
def create_group_cb(result):
nonlocal ret
ret = result
create_group_with_callback(url=url, group=group, callback=create_group_cb).wait()
return ret
async def create_group_async(url: str, group: str) -> Result:
"""Asynchronously Create a group
See: :py:func:`omni.client.create_group_with_callback`
"""
f = concurrent.futures.Future()
def create_group_cb(result):
if not f.done():
f.set_result(result)
create_group_with_callback(url=url, group=group, callback=create_group_cb)
return await asyncio.wrap_future(f)
def rename_group(url: str, group: str, new_group: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.rename_group_async` or :py:func:`omni.client.rename_group_with_callback` instead.
"""
ret = None
def rename_group_cb(result):
nonlocal ret
ret = result
rename_group_with_callback(url=url, group=group, new_group=new_group, callback=rename_group_cb).wait()
return ret
async def rename_group_async(url: str, group: str, new_group: str) -> Result:
"""Asynchronously Rename a group
See: :py:func:`omni.client.rename_group_with_callback`
"""
f = concurrent.futures.Future()
def rename_group_cb(result):
if not f.done():
f.set_result(result)
rename_group_with_callback(url=url, group=group, new_group=new_group, callback=rename_group_cb)
return await asyncio.wrap_future(f)
def remove_group(url: str, group: str) -> Tuple[Result, int]:
"""Deprecated: Use :py:func:`omni.client.remove_group_async` or :py:func:`omni.client.remove_group_with_callback` instead.
"""
ret = None
def remove_group_cb(result, change_count):
nonlocal ret
ret = (result, change_count)
remove_group_with_callback(url=url, group=group, callback=remove_group_cb).wait()
return ret
async def remove_group_async(url: str, group: str) -> Tuple[Result, int]:
"""Asynchronously Remove a group
See: :py:func:`omni.client.remove_group_with_callback`
"""
f = concurrent.futures.Future()
def remove_group_cb(result, change_count):
if not f.done():
f.set_result((result, change_count))
remove_group_with_callback(url=url, group=group, callback=remove_group_cb)
return await asyncio.wrap_future(f)
def get_users(url: str) -> Tuple[Result, List[str]]:
"""Deprecated: Use :py:func:`omni.client.get_users_async` or :py:func:`omni.client.get_users_with_callback` instead.
"""
ret = None
def get_users_cb(result, users):
nonlocal ret
ret = (result, users)
get_users_with_callback(url=url, callback=get_users_cb).wait()
return ret
async def get_users_async(url: str) -> Tuple[Result, List[str]]:
"""Asynchronously Get a list of all users
See: :py:func:`omni.client.get_users_with_callback`
"""
f = concurrent.futures.Future()
def get_users_cb(result, users):
if not f.done():
f.set_result((result, users))
get_users_with_callback(url=url, callback=get_users_cb)
return await asyncio.wrap_future(f)
def get_user_groups(url: str, user: str) -> Tuple[Result, List[str]]:
"""Deprecated: Use :py:func:`omni.client.get_user_groups_async` or :py:func:`omni.client.get_user_groups_with_callback` instead.
"""
ret = None
def get_user_groups_cb(result, groups):
nonlocal ret
ret = (result, groups)
get_user_groups_with_callback(url=url, user=user, callback=get_user_groups_cb).wait()
return ret
async def get_user_groups_async(url: str, user: str) -> Tuple[Result, List[str]]:
"""Asynchronously Get a list of groups the user is in
See: :py:func:`omni.client.get_user_groups_with_callback`
"""
f = concurrent.futures.Future()
def get_user_groups_cb(result, groups):
if not f.done():
f.set_result((result, groups))
get_user_groups_with_callback(url=url, user=user, callback=get_user_groups_cb)
return await asyncio.wrap_future(f)
def add_user_to_group(url: str, user: str, group: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.add_user_to_group_async` or :py:func:`omni.client.add_user_to_group_with_callback` instead.
"""
ret = None
def add_user_to_group_cb(result):
nonlocal ret
ret = result
add_user_to_group_with_callback(url=url, user=user, group=group, callback=add_user_to_group_cb).wait()
return ret
async def add_user_to_group_async(url: str, user: str, group: str) -> Result:
"""Asynchronously Add a user to a group
See: :py:func:`omni.client.add_user_to_group_with_callback`
"""
f = concurrent.futures.Future()
def add_user_to_group_cb(result):
if not f.done():
f.set_result(result)
add_user_to_group_with_callback(url=url, user=user, group=group, callback=add_user_to_group_cb)
return await asyncio.wrap_future(f)
def remove_user_from_group(url: str, user: str, group: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.remove_user_from_group_async` or :py:func:`omni.client.remove_user_from_group_with_callback` instead.
"""
ret = None
def remove_user_from_group_cb(result):
nonlocal ret
ret = result
remove_user_from_group_with_callback(url=url, user=user, group=group, callback=remove_user_from_group_cb).wait()
return ret
async def remove_user_from_group_async(url: str, user: str, group: str) -> Result:
"""Asynchronously Remove a user from a group
See: :py:func:`omni.client.remove_user_from_group_with_callback`
"""
f = concurrent.futures.Future()
def remove_user_from_group_cb(result):
if not f.done():
f.set_result(result)
remove_user_from_group_with_callback(url=url, user=user, group=group, callback=remove_user_from_group_cb)
return await asyncio.wrap_future(f)
| 21,138 | Python | 25.96301 | 146 | 0.652805 |
USwampertor/OmniverseJS/ov/python/pxr/Sdf/__init__.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from . import _sdf
from pxr import Tf
Tf.PrepareModule(_sdf, locals())
del _sdf, Tf
def Find(layerFileName, scenePath=None):
'''Find(layerFileName, scenePath) -> object
layerFileName: string
scenePath: Path
If given a single string argument, returns the menv layer with
the given filename. If given two arguments (a string and a Path), finds
the menv layer with the given filename and returns the scene object
within it at the given path.'''
layer = Layer.Find(layerFileName)
if (scenePath is None): return layer
return layer.GetObjectAtPath(scenePath)
# Test utilities
def _PathElemsToPrefixes(absolute, elements):
if absolute:
string = "/"
else:
string = ""
lastElemWasDotDot = False
didFirst = False
for elem in elements:
if elem == Path.parentPathElement:
# dotdot
if didFirst:
string = string + "/"
else:
didFirst = True
string = string + elem
lastElemWasDotDot = True
elif elem[0] == ".":
# property
if lastElemWasDotDot:
string = string + "/"
string = string + elem
lastElemWasDotDot = False
elif elem[0] == "[":
# rel attr or sub-attr indices, don't care which
string = string + elem
lastElemWasDotDot = False
else:
if didFirst:
string = string + "/"
else:
didFirst = True
string = string + elem
lastElemWasDotDot = False
if not string:
return []
path = Path(string)
return path.GetPrefixes()
try:
from . import __DOC
__DOC.Execute(locals())
del __DOC
except Exception:
pass
| 2,854 | Python | 30.373626 | 74 | 0.643308 |
USwampertor/OmniverseJS/ov/python/pxr/UsdUI/__init__.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from . import _usdUI
from pxr import Tf
Tf.PrepareModule(_usdUI, locals())
del Tf
try:
from . import __DOC
__DOC.Execute(locals())
del __DOC
except Exception:
pass
| 1,240 | Python | 34.457142 | 74 | 0.748387 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/common.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from .qt import QtCore, QtGui, QtWidgets
import os, time, sys, platform, math
from pxr import Ar, Tf, Sdf, Kind, Usd, UsdGeom, UsdShade
from .customAttributes import CustomAttribute
from .constantGroup import ConstantGroup
DEBUG_CLIPPING = "USDVIEWQ_DEBUG_CLIPPING"
class ClearColors(ConstantGroup):
"""Names of available background colors."""
BLACK = "Black"
DARK_GREY = "Grey (Dark)"
LIGHT_GREY = "Grey (Light)"
WHITE = "White"
class HighlightColors(ConstantGroup):
"""Names of available highlight colors for selected objects."""
WHITE = "White"
YELLOW = "Yellow"
CYAN = "Cyan"
class UIBaseColors(ConstantGroup):
RED = QtGui.QBrush(QtGui.QColor(230, 132, 131))
LIGHT_SKY_BLUE = QtGui.QBrush(QtGui.QColor(135, 206, 250))
DARK_YELLOW = QtGui.QBrush(QtGui.QColor(222, 158, 46))
class UIPrimTypeColors(ConstantGroup):
HAS_ARCS = UIBaseColors.DARK_YELLOW
NORMAL = QtGui.QBrush(QtGui.QColor(227, 227, 227))
INSTANCE = UIBaseColors.LIGHT_SKY_BLUE
MASTER = QtGui.QBrush(QtGui.QColor(118, 136, 217))
class UIPrimTreeColors(ConstantGroup):
SELECTED = QtGui.QBrush(QtGui.QColor(189, 155, 84))
SELECTED_HOVER = QtGui.QBrush(QtGui.QColor(227, 186, 101))
ANCESTOR_OF_SELECTED = QtGui.QBrush(QtGui.QColor(189, 155, 84, 50))
ANCESTOR_OF_SELECTED_HOVER = QtGui.QBrush(QtGui.QColor(189, 155, 84, 100))
UNSELECTED_HOVER = QtGui.QBrush(QtGui.QColor(70, 70, 70))
class UIPropertyValueSourceColors(ConstantGroup):
FALLBACK = UIBaseColors.DARK_YELLOW
TIME_SAMPLE = QtGui.QBrush(QtGui.QColor(177, 207, 153))
DEFAULT = UIBaseColors.LIGHT_SKY_BLUE
NONE = QtGui.QBrush(QtGui.QColor(140, 140, 140))
VALUE_CLIPS = QtGui.QBrush(QtGui.QColor(230, 150, 230))
class UIFonts(ConstantGroup):
# Font constants. We use font in the prim browser to distinguish
# "resolved" prim specifier
# XXX - the use of weight here may need to be revised depending on font family
BASE_POINT_SIZE = 10
ITALIC = QtGui.QFont()
ITALIC.setWeight(QtGui.QFont.Light)
ITALIC.setItalic(True)
NORMAL = QtGui.QFont()
NORMAL.setWeight(QtGui.QFont.Normal)
BOLD = QtGui.QFont()
BOLD.setWeight(QtGui.QFont.Bold)
BOLD_ITALIC = QtGui.QFont()
BOLD_ITALIC.setWeight(QtGui.QFont.Bold)
BOLD_ITALIC.setItalic(True)
OVER_PRIM = ITALIC
DEFINED_PRIM = BOLD
ABSTRACT_PRIM = NORMAL
INHERITED = QtGui.QFont()
INHERITED.setPointSize(BASE_POINT_SIZE * 0.8)
INHERITED.setWeight(QtGui.QFont.Normal)
INHERITED.setItalic(True)
class KeyboardShortcuts(ConstantGroup):
FramingKey = QtCore.Qt.Key_F
class PropertyViewIndex(ConstantGroup):
TYPE, NAME, VALUE = range(3)
ICON_DIR_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'icons')
# We use deferred loading because icons can't be constructed before
# application initialization time.
_icons = {}
def _DeferredIconLoad(path):
fullPath = os.path.join(ICON_DIR_ROOT, path)
try:
icon = _icons[fullPath]
except KeyError:
icon = QtGui.QIcon(fullPath)
_icons[fullPath] = icon
return icon
class PropertyViewIcons(ConstantGroup):
ATTRIBUTE = lambda: _DeferredIconLoad('usd-attr-plain-icon.png')
ATTRIBUTE_WITH_CONNECTIONS = lambda: _DeferredIconLoad('usd-attr-with-conn-icon.png')
RELATIONSHIP = lambda: _DeferredIconLoad('usd-rel-plain-icon.png')
RELATIONSHIP_WITH_TARGETS = lambda: _DeferredIconLoad('usd-rel-with-target-icon.png')
TARGET = lambda: _DeferredIconLoad('usd-target-icon.png')
CONNECTION = lambda: _DeferredIconLoad('usd-conn-icon.png')
COMPOSED = lambda: _DeferredIconLoad('usd-cmp-icon.png')
class PropertyViewDataRoles(ConstantGroup):
ATTRIBUTE = "Attr"
RELATIONSHIP = "Rel"
ATTRIBUTE_WITH_CONNNECTIONS = "Attr_"
RELATIONSHIP_WITH_TARGETS = "Rel_"
TARGET = "Tgt"
CONNECTION = "Conn"
COMPOSED = "Cmp"
class RenderModes(ConstantGroup):
# Render modes
WIREFRAME = "Wireframe"
WIREFRAME_ON_SURFACE = "WireframeOnSurface"
SMOOTH_SHADED = "Smooth Shaded"
FLAT_SHADED = "Flat Shaded"
POINTS = "Points"
GEOM_ONLY = "Geom Only"
GEOM_FLAT = "Geom Flat"
GEOM_SMOOTH = "Geom Smooth"
HIDDEN_SURFACE_WIREFRAME = "Hidden Surface Wireframe"
class ShadedRenderModes(ConstantGroup):
# Render modes which use shading
SMOOTH_SHADED = RenderModes.SMOOTH_SHADED
FLAT_SHADED = RenderModes.FLAT_SHADED
WIREFRAME_ON_SURFACE = RenderModes.WIREFRAME_ON_SURFACE
GEOM_FLAT = RenderModes.GEOM_FLAT
GEOM_SMOOTH = RenderModes.GEOM_SMOOTH
class ColorCorrectionModes(ConstantGroup):
# Color correction used when render is presented to screen
# These strings should match HdxColorCorrectionTokens
DISABLED = "disabled"
SRGB = "sRGB"
OPENCOLORIO = "openColorIO"
class PickModes(ConstantGroup):
# Pick modes
PRIMS = "Prims"
MODELS = "Models"
INSTANCES = "Instances"
PROTOTYPES = "Prototypes"
class SelectionHighlightModes(ConstantGroup):
# Selection highlight modes
NEVER = "Never"
ONLY_WHEN_PAUSED = "Only when paused"
ALWAYS = "Always"
class CameraMaskModes(ConstantGroup):
NONE = "none"
PARTIAL = "partial"
FULL = "full"
class IncludedPurposes(ConstantGroup):
DEFAULT = UsdGeom.Tokens.default_
PROXY = UsdGeom.Tokens.proxy
GUIDE = UsdGeom.Tokens.guide
RENDER = UsdGeom.Tokens.render
def _PropTreeWidgetGetRole(tw):
return tw.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
def PropTreeWidgetTypeIsRel(tw):
role = _PropTreeWidgetGetRole(tw)
return role in (PropertyViewDataRoles.RELATIONSHIP,
PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS)
def _UpdateLabelText(text, substring, mode):
return text.replace(substring, '<'+mode+'>'+substring+'</'+mode+'>')
def ItalicizeLabelText(text, substring):
return _UpdateLabelText(text, substring, 'i')
def BoldenLabelText(text, substring):
return _UpdateLabelText(text, substring, 'b')
def ColorizeLabelText(text, substring, r, g, b):
return _UpdateLabelText(text, substring,
"span style=\"color:rgb(%d, %d, %d);\"" % (r, g, b))
def PrintWarning(title, description):
msg = sys.stderr
print("------------------------------------------------------------", file=msg)
print("WARNING: %s" % title, file=msg)
print(description, file=msg)
print("------------------------------------------------------------", file=msg)
def GetValueAndDisplayString(prop, time):
"""If `prop` is a timeSampled Sdf.AttributeSpec, compute a string specifying
how many timeSamples it possesses. Otherwise, compute the single default
value, or targets for a relationship, or value at 'time' for a
Usd.Attribute. Return a tuple of a parameterless function that returns the
resolved value at 'time', and the computed brief string for display. We
return a value-producing function rather than the value itself because for
an Sdf.AttributeSpec with multiple timeSamples, the resolved value is
*all* of the timeSamples, which can be expensive to compute, and is
rarely needed.
"""
def _ValAndStr(val):
return (lambda: val, GetShortStringForValue(prop, val))
if isinstance(prop, Usd.Relationship):
return _ValAndStr(prop.GetTargets())
elif isinstance(prop, (Usd.Attribute, CustomAttribute)):
return _ValAndStr(prop.Get(time))
elif isinstance(prop, Sdf.AttributeSpec):
if time == Usd.TimeCode.Default():
return _ValAndStr(prop.default)
else:
numTimeSamples = prop.layer.GetNumTimeSamplesForPath(prop.path)
if numTimeSamples == 0:
return _ValAndStr(prop.default)
else:
def _GetAllTimeSamples(attrSpec):
l = attrSpec.layer
p = attrSpec.path
ordinates = l.ListTimeSamplesForPath(p)
return [(o, l.QueryTimeSample(p, o)) for o in ordinates]
if numTimeSamples == 1:
valStr = "1 time sample"
else:
valStr = str(numTimeSamples) + " time samples"
return (lambda prop=prop: _GetAllTimeSamples(prop), valStr)
elif isinstance(prop, Sdf.RelationshipSpec):
return _ValAndStr(prop.targetPathList)
return (lambda: None, "unrecognized property type")
def GetShortStringForValue(prop, val):
if isinstance(prop, Usd.Relationship):
val = ", ".join(str(p) for p in val)
elif isinstance(prop, Sdf.RelationshipSpec):
return str(prop.targetPathList)
# If there is no value opinion, we do not want to display anything,
# since python 'None' has a different meaning than usda-authored None,
# which is how we encode attribute value blocks (which evaluate to
# Sdf.ValueBlock)
if val is None:
return ''
from .scalarTypes import GetScalarTypeFromAttr
scalarType, isArray = GetScalarTypeFromAttr(prop)
result = ''
if isArray and not isinstance(val, Sdf.ValueBlock):
def arrayToStr(a):
from itertools import chain
elems = a if len(a) <= 6 else chain(a[:3], ['...'], a[-3:])
return '[' + ', '.join(map(str, elems)) + ']'
if val is not None and len(val):
result = "%s[%d]: %s" % (scalarType, len(val), arrayToStr(val))
else:
result = "%s[]" % scalarType
else:
result = str(val)
return result[:500]
# Return a string that reports size in metric units (units of 1000, not 1024).
def ReportMetricSize(sizeInBytes):
if sizeInBytes == 0:
return "0 B"
sizeSuffixes = ("B", "KB", "MB", "GB", "TB", "PB", "EB")
i = int(math.floor(math.log(sizeInBytes, 1000)))
if i >= len(sizeSuffixes):
i = len(sizeSuffixes) - 1
p = math.pow(1000, i)
s = round(sizeInBytes / p, 2)
return "%s %s" % (s, sizeSuffixes[i])
# Return attribute status at a certian frame (is it using the default, or the
# fallback? Is it authored at this frame? etc.
def _GetAttributeStatus(attribute, frame):
return attribute.GetResolveInfo(frame).GetSource()
# Return a Font corresponding to certain attribute properties.
# Currently this only applies italicization on interpolated time samples.
def GetPropertyTextFont(prop, frame):
if not isinstance(prop, Usd.Attribute):
# Early-out for non-attribute properties.
return None
frameVal = frame.GetValue()
bracketing = prop.GetBracketingTimeSamples(frameVal)
# Note that some attributes return an empty tuple, some None, from
# GetBracketingTimeSamples(), but all will be fed into this function.
if bracketing and (len(bracketing) == 2) and (bracketing[0] != frameVal):
return UIFonts.ITALIC
return None
# Helper function that takes attribute status and returns the display color
def GetPropertyColor(prop, frame, hasValue=None, hasAuthoredValue=None,
valueIsDefault=None):
if not isinstance(prop, Usd.Attribute):
# Early-out for non-attribute properties.
return UIBaseColors.RED.color()
statusToColor = {Usd.ResolveInfoSourceFallback : UIPropertyValueSourceColors.FALLBACK,
Usd.ResolveInfoSourceDefault : UIPropertyValueSourceColors.DEFAULT,
Usd.ResolveInfoSourceValueClips : UIPropertyValueSourceColors.VALUE_CLIPS,
Usd.ResolveInfoSourceTimeSamples: UIPropertyValueSourceColors.TIME_SAMPLE,
Usd.ResolveInfoSourceNone : UIPropertyValueSourceColors.NONE}
valueSource = _GetAttributeStatus(prop, frame)
return statusToColor[valueSource].color()
# Gathers information about a layer used as a subLayer, including its
# position in the layerStack hierarchy.
class SubLayerInfo(object):
def __init__(self, sublayer, offset, containingLayer, prefix):
self.layer = sublayer
self.offset = offset
self.parentLayer = containingLayer
self._prefix = prefix
def GetOffsetString(self):
o = self.offset.offset
s = self.offset.scale
if o == 0:
if s == 1:
return ""
else:
return str.format("(scale = {})", s)
elif s == 1:
return str.format("(offset = {})", o)
else:
return str.format("(offset = {0}; scale = {1})", o, s)
def GetHierarchicalDisplayString(self):
return self._prefix + self.layer.GetDisplayName()
def _AddSubLayers(layer, layerOffset, prefix, parentLayer, layers):
offsets = layer.subLayerOffsets
layers.append(SubLayerInfo(layer, layerOffset, parentLayer, prefix))
for i, l in enumerate(layer.subLayerPaths):
offset = offsets[i] if offsets is not None and len(offsets) > i else Sdf.LayerOffset()
subLayer = Sdf.Layer.FindRelativeToLayer(layer, l)
# Due to an unfortunate behavior of the Pixar studio resolver,
# FindRelativeToLayer() may fail to resolve certain paths. We will
# remove this extra Find() call as soon as we can retire the behavior;
# in the meantime, the extra call does not hurt (but should not, in
# general, be necessary)
if not subLayer:
subLayer = Sdf.Layer.Find(l)
if subLayer:
# This gives a 'tree'-ish presentation, but it looks sad in
# a QTableWidget. Just use spaces for now
# addedPrefix = "|-- " if parentLayer is None else "| "
addedPrefix = " "
_AddSubLayers(subLayer, offset, addedPrefix + prefix, layer, layers)
else:
print("Could not find layer " + l)
def GetRootLayerStackInfo(layer):
layers = []
_AddSubLayers(layer, Sdf.LayerOffset(), "", None, layers)
return layers
def PrettyFormatSize(sz):
k = 1024
meg = k * 1024
gig = meg * 1024
ter = gig * 1024
sz = float(sz)
if sz > ter:
return "%.1fT" % (sz/float(ter))
elif sz > gig:
return "%.1fG" % (sz/float(gig))
elif sz > meg:
return "%.1fM" % (sz/float(meg))
elif sz > k:
return "%.1fK" % (sz/float(k))
else:
return "%db" % sz
class Timer(object):
"""Use as a context object with python's "with" statement, like so:
with Timer() as t:
doSomeStuff()
t.PrintTime("did some stuff")
"""
def __enter__(self):
self._start = time.time()
self.interval = 0
return self
def __exit__(self, *args):
self._end = time.time()
self.interval = self._end - self._start
def PrintTime(self, action):
print("Time to %s: %2.3fs" % (action, self.interval))
class BusyContext(object):
"""When used as a context object with python's "with" statement,
will set Qt's busy cursor upon entry and pop it on exit.
"""
def __enter__(self):
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
def __exit__(self, *args):
QtWidgets.QApplication.restoreOverrideCursor()
def InvisRootPrims(stage):
"""Make all defined root prims of stage be invisible,
at Usd.TimeCode.Default()"""
for p in stage.GetPseudoRoot().GetChildren():
UsdGeom.Imageable(p).MakeInvisible()
def _RemoveVisibilityRecursive(primSpec):
try:
primSpec.RemoveProperty(primSpec.attributes[UsdGeom.Tokens.visibility])
except IndexError:
pass
for child in primSpec.nameChildren:
_RemoveVisibilityRecursive(child)
def ResetSessionVisibility(stage):
session = stage.GetSessionLayer()
with Sdf.ChangeBlock():
_RemoveVisibilityRecursive(session.pseudoRoot)
# This is unfortunate.. but until UsdAttribute will return you a ResolveInfo,
# we have little alternative, other than manually walking prim's PcpPrimIndex
def HasSessionVis(prim):
"""Is there a session-layer override for visibility for 'prim'?"""
session = prim.GetStage().GetSessionLayer()
primSpec = session.GetPrimAtPath(prim.GetPath())
return bool(primSpec and UsdGeom.Tokens.visibility in primSpec.attributes)
# This should be codified on UsdModelAPI, but maybe after 117137 is addressed...
def GetEnclosingModelPrim(prim):
"""If 'prim' is inside/under a model of any kind, return the closest
such ancestor prim - If 'prim' has no model ancestor, return None"""
if prim:
prim = prim.GetParent()
while prim:
# We use Kind here instead of prim.IsModel because point instancer
# prototypes currently don't register as models in IsModel. See
# bug: http://bugzilla.pixar.com/show_bug.cgi?id=117137
if Kind.Registry.IsA(Usd.ModelAPI(prim).GetKind(), Kind.Tokens.model):
break
prim = prim.GetParent()
return prim
def GetPrimLoadability(prim):
"""Return a tuple of (isLoadable, isLoaded) for 'prim', according to
the following rules:
A prim is loadable if it is active, and either of the following are true:
* prim has a payload
* prim is a model group
The latter is useful because loading is recursive on a UsdStage, and it
is convenient to be able to (e.g.) load everything loadable in a set.
A prim 'isLoaded' only if there are no unloaded prims beneath it, i.e.
it is stating whether the prim is "fully loaded". This
is a debatable definition, but seems useful for usdview's purposes."""
if not (prim.IsActive() and (prim.IsGroup() or prim.HasAuthoredPayloads())):
return (False, True)
# XXX Note that we are potentially traversing the entire stage here.
# If this becomes a performance issue, we can cast this query into C++,
# cache results, etc.
for p in Usd.PrimRange(prim, Usd.PrimIsActive):
if not p.IsLoaded():
return (True, False)
return (True, True)
def GetPrimsLoadability(prims):
"""Follow the logic of GetPrimLoadability for each prim, combining
results so that isLoadable is the disjunction of all prims, and
isLoaded is the conjunction."""
isLoadable = False
isLoaded = True
for prim in prims:
loadable, loaded = GetPrimLoadability(prim)
isLoadable = isLoadable or loadable
isLoaded = isLoaded and loaded
return (isLoadable, isLoaded)
def GetFileOwner(path):
try:
if platform.system() == 'Windows':
# This only works if pywin32 is installed.
# Try "pip install pypiwin32".
import win32security as w32s
fs = w32s.GetFileSecurity(path, w32s.OWNER_SECURITY_INFORMATION)
sdo = fs.GetSecurityDescriptorOwner()
name, domain, use = w32.LookupAccountSid(None, sdo)
return "%s\\%s" % (domain, name)
else:
import pwd
return pwd.getpwuid(os.stat(path).st_uid).pw_name
except:
return "<unknown>"
# In future when we have better introspection abilities in Usd core API,
# we will change this function to accept a prim rather than a primStack.
def GetAssetCreationTime(primStack, assetIdentifier):
"""Finds the weakest layer in which assetInfo.identifier is set to
'assetIdentifier', and considers that an "asset-defining layer". We then
retrieve the creation time for the asset by stat'ing the layer's
real path.
Returns a triple of strings: (fileDisplayName, creationTime, owner)"""
definingLayer = None
for spec in reversed(primStack):
if spec.HasInfo('assetInfo'):
identifier = spec.GetInfo('assetInfo')['identifier']
if identifier.path == assetIdentifier.path:
definingLayer = spec.layer
break
if definingLayer:
definingFile = definingLayer.realPath
else:
definingFile = primStack[-1].layer.realPath
print("Warning: Could not find expected asset-defining layer for %s" %
assetIdentifier)
if Ar.IsPackageRelativePath(definingFile):
definingFile = Ar.SplitPackageRelativePathOuter(definingFile)[0]
if not definingFile:
displayName = (definingLayer.GetDisplayName()
if definingLayer and definingLayer.anonymous else
"<in-memory layer>")
creationTime = "<unknown>"
owner = "<unknown>"
else:
displayName = definingFile.split('/')[-1]
try:
creationTime = time.ctime(os.stat(definingFile).st_ctime)
except:
creationTime = "<unknown>"
owner = GetFileOwner(definingFile)
return (displayName, creationTime, owner)
def DumpMallocTags(stage, contextStr):
if Tf.MallocTag.IsInitialized():
callTree = Tf.MallocTag.GetCallTree()
memInMb = Tf.MallocTag.GetTotalBytes() / (1024.0 * 1024.0)
import os.path as path
import tempfile
layerName = path.basename(stage.GetRootLayer().identifier)
# CallTree.Report() gives us the most informative (and processable)
# form of output, but it only accepts a fileName argument. So we
# use NamedTemporaryFile just to get a filename.
statsFile = tempfile.NamedTemporaryFile(prefix=layerName+'.',
suffix='.mallocTag',
delete=False)
statsFile.close()
reportName = statsFile.name
callTree.Report(reportName)
print("Memory consumption of %s for %s is %d Mb" % (contextStr,
layerName,
memInMb))
print("For detailed analysis, see " + reportName)
else:
print("Unable to accumulate memory usage since the Pxr MallocTag system was not initialized")
def GetInstanceIdForIndex(prim, instanceIndex, time):
'''Attempt to find an authored Id value for the instance at index
'instanceIndex' at time 'time', on the given prim 'prim', which we access
as a UsdGeom.PointInstancer (whether it actually is or not, to provide
some dynamic duck-typing for custom instancer types that support Ids.
Returns 'None' if no ids attribute was found, or if instanceIndex is
outside the bounds of the ids array.'''
if not prim or instanceIndex < 0:
return None
ids = UsdGeom.PointInstancer(prim).GetIdsAttr().Get(time)
if not ids or instanceIndex >= len(ids):
return None
return ids[instanceIndex]
def GetInstanceIndicesForIds(prim, instanceIds, time):
'''Attempt to find the instance indices of a list of authored instance IDs
for prim 'prim' at time 'time'. If the prim is not a PointInstancer or does
not have authored IDs, returns None. If any ID from 'instanceIds' does not
exist at the given time, its index is not added to the list (because it does
not have an index).'''
ids = UsdGeom.PointInstancer(prim).GetIdsAttr().Get(time)
if ids:
return [instanceIndex for instanceIndex, instanceId in enumerate(ids)
if instanceId in instanceIds]
else:
return None
def Drange(start, stop, step):
'''Return a list whose first element is 'start' and the following elements
(if any) are 'start' plus increasing whole multiples of 'step', up to but
not greater than 'stop'. For example:
Drange(1, 3, 0.3) -> [1, 1.3, 1.6, 1.9, 2.2, 2.5, 2.8]'''
lst = [start]
n = 1
while start + n * step <= stop:
lst.append(start + n * step)
n += 1
return lst
class PrimNotFoundException(Exception):
"""Raised when a prim does not exist at a valid path."""
def __init__(self, path):
super(PrimNotFoundException, self).__init__(
"Prim not found at path in stage: %s" % str(path))
class PropertyNotFoundException(Exception):
"""Raised when a property does not exist at a valid path."""
def __init__(self, path):
super(PropertyNotFoundException, self).__init__(
"Property not found at path in stage: %s" % str(path))
class FixableDoubleValidator(QtGui.QDoubleValidator):
"""This class implements a fixup() method for QDoubleValidator
(see method for specific behavior). To work around the brokenness
of Pyside's fixup() wrapping, we allow the validator to directly
update its parent if it is a QLineEdit, from within fixup(). Thus
every QLineEdit must possess its own unique FixableDoubleValidator.
The fixup method we supply (which can be usefully called directly)
applies clamping and rounding to enforce the QDoubleValidator's
range and decimals settings."""
def __init__(self, parent):
super(FixableDoubleValidator, self).__init__(parent)
self._lineEdit = parent if isinstance(parent, QtWidgets.QLineEdit) else None
def fixup(self, valStr):
# We implement this to fulfill the virtual for internal QLineEdit
# behavior, hoping that PySide will do the right thing, but it is
# useless to call from Python directly due to string immutability
try:
val = float(valStr)
val = max(val, self.bottom())
val = min(val, self.top())
val = round(val)
valStr = str(val)
if self._lineEdit:
self._lineEdit.setText(valStr)
except ValueError:
pass
| 26,669 | Python | 37.708273 | 101 | 0.656718 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/attributeViewContextMenu.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtGui, QtWidgets, QtCore
from pxr import Sdf
from .usdviewContextMenuItem import UsdviewContextMenuItem
from .common import (PropertyViewIndex, PropertyViewDataRoles,
PrimNotFoundException, PropertyNotFoundException)
#
# Specialized context menu for running commands in the attribute viewer.
#
class AttributeViewContextMenu(QtWidgets.QMenu):
def __init__(self, parent, item, dataModel):
QtWidgets.QMenu.__init__(self, parent)
self._menuItems = _GetContextMenuItems(item, dataModel)
for menuItem in self._menuItems:
# create menu actions
if menuItem.isValid() and menuItem.ShouldDisplay():
action = self.addAction(menuItem.GetText(), menuItem.RunCommand)
# set enabled
if not menuItem.IsEnabled():
action.setEnabled(False)
def _GetContextMenuItems(item, dataModel):
return [ # Root selection methods
CopyAttributeNameMenuItem(dataModel, item),
CopyAttributeValueMenuItem(dataModel, item),
CopyAllTargetPathsMenuItem(dataModel, item),
SelectAllTargetPathsMenuItem(dataModel, item),
# Individual/multi target selection menus
CopyTargetPathMenuItem(dataModel, item),
SelectTargetPathMenuItem(dataModel, item)]
def _selectPrimsAndProps(dataModel, paths):
prims = []
props = []
for path in paths:
primPath = path.GetAbsoluteRootOrPrimPath()
prim = dataModel.stage.GetPrimAtPath(primPath)
if not prim:
raise PrimNotFoundException(primPath)
prims.append(prim)
if path.IsPropertyPath():
prop = prim.GetProperty(path.name)
if not prop:
raise PropertyNotFoundException(path)
props.append(prop)
with dataModel.selection.batchPrimChanges:
dataModel.selection.clearPrims()
for prim in prims:
dataModel.selection.addPrim(prim)
with dataModel.selection.batchPropChanges:
dataModel.selection.clearProps()
for prop in props:
dataModel.selection.addProp(prop)
dataModel.selection.clearComputedProps()
#
# The base class for propertyview context menu items.
#
class AttributeViewContextMenuItem(UsdviewContextMenuItem):
def __init__(self, dataModel, item):
self._dataModel = dataModel
self._item = item
self._role = self._item.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
self._name = self._item.text(PropertyViewIndex.NAME) if self._item else ""
self._value = self._item.text(PropertyViewIndex.VALUE) if self._item else ""
def IsEnabled(self):
return True
def ShouldDisplay(self):
return True
def GetText(self):
return ""
def RunCommand(self):
pass
#
# Copy the attribute's name to clipboard.
#
class CopyAttributeNameMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return self._role not in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)
def GetText(self):
return "Copy Property Name"
def RunCommand(self):
if self._name == "":
return
cb = QtWidgets.QApplication.clipboard()
cb.setText(self._name, QtGui.QClipboard.Selection)
cb.setText(self._name, QtGui.QClipboard.Clipboard)
#
# Copy the attribute's value to clipboard.
#
class CopyAttributeValueMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return self._role not in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)
def GetText(self):
return "Copy Property Value"
def RunCommand(self):
# We display relationships targets as:
# /f, /g/a ...
# But when we ask to copy the value, we'd like to get back:
# [Sdf.Path('/f'), Sdf.Path('/g/a')]
# Which is useful for pasting into a python interpreter.
if self._role == PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS:
valueStr = str([Sdf.Path("".join(p.split())) \
for p in self._value.split(",")])
else:
valueStr = self._value
if self._item:
rawVal = self._item.rawValue
if rawVal is not None:
valueStr = str(rawVal)
cb = QtWidgets.QApplication.clipboard()
cb.setText(valueStr, QtGui.QClipboard.Selection)
cb.setText(valueStr, QtGui.QClipboard.Clipboard)
# --------------------------------------------------------------------
# Individual target selection menus
# --------------------------------------------------------------------
#
# Copy the target path to clipboard.
#
class CopyTargetPathMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return self._role in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)
def GetText(self):
return "Copy Target Path As Text"
def GetSelectedOfType(self):
getRole = lambda s: s.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
return [s for s in self._item.treeWidget().selectedItems() \
if getRole(s) in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)]
def RunCommand(self):
if not self._item:
return
value = ", ".join([s.text(PropertyViewIndex.NAME) for s in self.GetSelectedOfType()])
cb = QtWidgets.QApplication.clipboard()
cb.setText(value, QtGui.QClipboard.Selection)
cb.setText(value, QtGui.QClipboard.Clipboard)
#
# Jump to the target path in the prim browser
# This will include all other highlighted paths of this type, if any.
#
class SelectTargetPathMenuItem(CopyTargetPathMenuItem):
def GetText(self):
return "Select Target Path"
def RunCommand(self):
paths = [Sdf.Path(s.text(PropertyViewIndex.NAME))
for s in self.GetSelectedOfType()]
_selectPrimsAndProps(self._dataModel, paths)
# --------------------------------------------------------------------
# Target owning property selection menus
# --------------------------------------------------------------------
def _GetTargetPathsForItem(item):
paths = [Sdf.Path(item.child(i).text(PropertyViewIndex.NAME)) for
i in range (0, item.childCount())]
# If there are no children, the value column must hold a valid path
# (since the command is enabled).
if len(paths) == 0:
itemText = item.text(PropertyViewIndex.VALUE)
if len(itemText) > 0:
paths.append(Sdf.Path(itemText))
return paths
#
# Select all target paths under the selected attribute
#
class SelectAllTargetPathsMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return (self._role == PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS
or self._role == PropertyViewDataRoles.ATTRIBUTE_WITH_CONNNECTIONS)
def IsEnabled(self):
if not self._item:
return False
# Enable the menu item if there are one or more targets for this
# rel/attribute connection
if self._item.childCount() > 0:
return True
# Enable the menu if the item holds a valid SdfPath.
itemText = self._item.text(2)
return Sdf.Path.IsValidPathString(itemText)
def GetText(self):
return "Select Target Path(s)"
def RunCommand(self):
if not self._item:
return
_selectPrimsAndProps(self._dataModel,
_GetTargetPathsForItem(self._item))
#
# Copy all target paths under the currently selected relationship to the clipboard
#
class CopyAllTargetPathsMenuItem(SelectAllTargetPathsMenuItem):
def GetText(self):
return "Copy Target Path(s) As Text"
def RunCommand(self):
if not self._item:
return
value = ", ".join(_GetTargetPathsForItem(self._item))
cb = QtWidgets.QApplication.clipboard()
cb.setText(value, QtGui.QClipboard.Selection)
cb.setText(value, QtGui.QClipboard.Clipboard)
| 9,265 | Python | 33.966038 | 102 | 0.649217 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/usdviewApi.py | #!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to # it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) # of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY
# KIND, either express or implied. See the Apache License for the # specific
# language governing permissions and limitations under the Apache # License.
import types
from pxr import Gf
from .qt import QtCore
class UsdviewApi(object):
"""This class is an interface that provides access to Usdview context for
Usdview plugins and other clients. It abstracts away the implementation of
Usdview so that the core can change without affecting clients.
"""
def __init__(self, appController):
self.__appController = appController
@property
def dataModel(self):
"""Usdview's active data model object."""
return self.__appController._dataModel
@property
def stage(self):
"""The current Usd.Stage."""
return self.__appController._dataModel.stage
@property
def frame(self):
"""The current frame."""
return self.__appController._dataModel.currentFrame
@property
def prim(self):
"""The focus prim from the prim selection."""
return self.__appController._dataModel.selection.getFocusPrim()
@property
def selectedPoint(self):
"""The currently selected world space point."""
return self.__appController._dataModel.selection.getPoint()
@property
def selectedPrims(self):
"""A list of all currently selected prims."""
return self.__appController._dataModel.selection.getPrims()
@property
def selectedPaths(self):
"""A list of the paths of all currently selected prims."""
return self.__appController._dataModel.selection.getPrimPaths()
@property
def selectedInstances(self):
"""The current prim instance selection. This is a dictionary where each
key is a prim and each value is a set of instance ids selected from that
prim.
"""
return self.__appController._dataModel.selection.getPrimInstances()
@property
def spec(self):
"""The currently selected Sdf.Spec from the Composition tab."""
return self.__appController._currentSpec
@property
def layer(self):
"""The currently selected Sdf.Layer in the Composition tab."""
return self.__appController._currentLayer
@property
def cameraPrim(self):
"""The current camera prim."""
return self.__appController._dataModel.viewSettings.cameraPrim
@property
def currentGfCamera(self):
"""A copy of the last computed Gf Camera."""
if self.__appController._stageView:
return Gf.Camera(self.__appController._stageView.gfCamera)
else:
return None
@property
def viewportSize(self):
"""The width and height of the viewport in pixels."""
stageView = self.__appController._stageView
if stageView is not None:
return stageView.width(), stageView.height()
else:
return 0, 0
@property
def configDir(self):
"""The config dir, typically ~/.usdview/."""
return self.__appController._outputBaseDirectory()
@property
def stageIdentifier(self):
"""The identifier of the open Usd.Stage's root layer."""
return self.__appController._dataModel.stage.GetRootLayer().identifier
@property
def qMainWindow(self):
"""A QWidget object that other widgets can use as a parent."""
return self.__appController._mainWindow
# This needs to be the last property added because otherwise the @property
# decorator will call this method rather than the actual property decorator.
@property
def property(self):
"""The focus property from the property selection."""
return self.__appController._dataModel.selection.getFocusProp()
def ComputeModelsFromSelection(self):
"""Returns selected models. this will walk up to find the nearest model.
Note, this may return "group"'s if they are selected.
"""
models = []
items = self.__appController.getSelectedItems()
for item in items:
currItem = item
while currItem and not currItem.prim.IsModel():
currItem = currItem.parent()
if currItem:
models.append(currItem.prim)
return models
def ComputeSelectedPrimsOfType(self, schemaType):
"""Returns selected prims of the provided schemaType (TfType)."""
prims = []
items = self.__appController.getSelectedItems()
for item in items:
if item.prim.IsA(schemaType):
prims.append(item.prim)
return prims
def UpdateGUI(self):
"""Updates the main UI views"""
self.__appController.updateGUI()
def PrintStatus(self, msg):
"""Prints a status message."""
self.__appController.statusMessage(msg)
def GetSettings(self):
"""DEPRECATED Returns the old settings object."""
return self.__appController._settings
def ClearPrimSelection(self):
self.__appController._dataModel.selection.clearPrims()
def AddPrimToSelection(self, prim):
self.__appController._dataModel.selection.addPrim(prim)
# Screen capture functionality.
def GrabWindowShot(self):
"""Returns a QImage of the full usdview window."""
return self.__appController.GrabWindowShot()
def GrabViewportShot(self):
"""Returns a QImage of the current stage view in usdview."""
return self.__appController.GrabViewportShot()
def _ExportSession(self, stagePath, defcamName='usdviewCam', imgWidth=None,
imgHeight=None):
"""Export the free camera (if currently active) and session layer to a
USD file at the specified stagePath that references the current-viewed
stage.
"""
stageView = self.__appController._stageView
if stageView is not None:
stageView.ExportSession(stagePath, defcamName='usdviewCam',
imgWidth=None, imgHeight=None)
| 6,994 | Python | 30.367713 | 81 | 0.660709 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/overridableLineEdit.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtWidgets
# simple class to have a "clear" button on a line edit when the line edit
# contains an override. Clicking the clear button returns to the default value.
class OverridableLineEdit(QtWidgets.QLineEdit):
def __init__(self, parent):
QtWidgets.QLineEdit.__init__(self, parent)
# create the clear button.
self._clearButton = QtWidgets.QToolButton(self)
self._clearButton.setText('x')
self._clearButton.setCursor(QtCore.Qt.ArrowCursor)
self._clearButton.setFixedSize(16, 16)
self._clearButton.hide()
self._defaultText = '' # default value holder
self._clearButton.clicked.connect(self._resetDefault)
self.textEdited.connect(self._overrideSet)
# properly place the button
def resizeEvent(self, event):
sz = QtCore.QSize(self._clearButton.size())
frameWidth = self.style().pixelMetric(QtWidgets.QStyle.PM_DefaultFrameWidth)
self._clearButton.move(self.rect().right() - frameWidth - sz.width(),
(self.rect().bottom() + 1 - sz.height())/2)
# called when the user types an override
def _overrideSet(self, text):
self._clearButton.setVisible(True)
# called programatically to reset the default text
def setText(self, text):
QtWidgets.QLineEdit.setText(self, text)
self._defaultText = text
self._clearButton.setVisible(False)
# called when the clear button is clicked
def _resetDefault(self):
self.setText(self._defaultText)
| 2,628 | Python | 38.238805 | 84 | 0.705099 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/attributeValueEditorUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'attributeValueEditorUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_AttributeValueEditor(object):
def setupUi(self, AttributeValueEditor):
if not AttributeValueEditor.objectName():
AttributeValueEditor.setObjectName(u"AttributeValueEditor")
AttributeValueEditor.resize(400, 300)
self.verticalLayout = QVBoxLayout(AttributeValueEditor)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName(u"verticalLayout")
self.stackedWidget = QStackedWidget(AttributeValueEditor)
self.stackedWidget.setObjectName(u"stackedWidget")
self.stackedWidget.setLineWidth(0)
self.valueViewer = QTextBrowser()
self.valueViewer.setObjectName(u"valueViewer")
self.stackedWidget.addWidget(self.valueViewer)
self.verticalLayout.addWidget(self.stackedWidget)
self.retranslateUi(AttributeValueEditor)
self.stackedWidget.setCurrentIndex(0)
QMetaObject.connectSlotsByName(AttributeValueEditor)
# setupUi
def retranslateUi(self, AttributeValueEditor):
AttributeValueEditor.setWindowTitle(QCoreApplication.translate("AttributeValueEditor", u"Form", None))
AttributeValueEditor.setProperty("comment", QCoreApplication.translate("AttributeValueEditor", u"\n"
" Copyright 2016 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
# retranslateUi
| 3,830 | Python | 53.728571 | 110 | 0.529243 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/constantGroup.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
"""A module for creating groups of constants. This is similar to the enum
module, but enum is not available in Python 2's standard library.
"""
import sys
import types
class _MetaConstantGroup(type):
"""A meta-class which handles the creation and behavior of ConstantGroups.
"""
def __new__(metacls, cls, bases, classdict):
"""Discover constants and create a new ConstantGroup class."""
# If this is just the base ConstantGroup class, simply create it and do
# not search for constants.
if cls == "ConstantGroup":
return super(_MetaConstantGroup, metacls).__new__(metacls, cls, bases, classdict)
# Search through the class-level properties and convert them into
# constants.
allConstants = list()
for key, value in classdict.items():
if (key.startswith("_") or isinstance(value, classmethod) or
isinstance(value, staticmethod)):
# Ignore variables which start with an underscore, and
# static/class methods.
pass
else:
# Found a new constant.
allConstants.append(value)
# If the constant is a function/lambda, ensure that it is not
# converted into a method.
if isinstance(value, types.FunctionType):
classdict[key] = staticmethod(value)
# All constants discovered, now create the `_all` property.
classdict["_all"] = tuple(allConstants)
# Finally, create the new ConstantGroup class.
return super(_MetaConstantGroup, metacls).__new__(metacls, cls, bases, classdict)
def __setattr__(cls, name, value):
"""Prevent modification of properties after a group is created."""
raise AttributeError("Constant groups cannot be modified.")
def __delattr__(cls, name):
"""Prevent deletion of properties after a group is created."""
raise AttributeError("Constant groups cannot be modified.")
def __len__(self):
"""Get the number of constants in the group."""
return len(self._all)
def __contains__(self, value):
"""Check if a constant exists in the group."""
return (value in self._all)
def __iter__(self):
"""Iterate over each constant in the group."""
return iter(self._all)
# We want to define a ConstantGroup class that uses _MetaConstantGroup
# as its metaclass. The syntax for doing so in Python 3 is not backwards
# compatible for Python 2, so we cannot just conditionally define one
# form or the other because that will cause syntax errors when compiling
# this file. To avoid this we add a layer of indirection through exec().
if sys.version_info.major >= 3:
defineConstantGroup = '''
class ConstantGroup(object, metaclass=_MetaConstantGroup):
"""The base constant group class, intended to be inherited by actual groups
of constants.
"""
def __new__(cls, *args, **kwargs):
raise TypeError("ConstantGroup objects cannot be created.")
'''
else:
defineConstantGroup = '''
class ConstantGroup(object):
"""The base constant group class, intended to be inherited by actual groups
of constants.
"""
__metaclass__ = _MetaConstantGroup
def __new__(cls, *args, **kwargs):
raise TypeError("ConstantGroup objects cannot be created.")
'''
exec(defineConstantGroup)
| 4,498 | Python | 38.121739 | 93 | 0.672743 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/prettyPrint.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
'''
Hopefully we can deprecate this since most of the array stuff is handled by the
arrayAttributeView
'''
from .qt import QtWidgets
def progressDialog(title, value):
dialog = QtWidgets.QProgressDialog(title, "Cancel", 0, value)
dialog.setModal(True)
dialog.setMinimumDuration(500)
return dialog
def prettyPrint(v):
"""Returns a string representing a "detailed view" of the value v.
This string is used in the watch window"""
# Pretty-print a dictionary
if isinstance(v, dict):
result = "Dictionary contents:\n"
for pair in v.items():
keystring = str(pair[0])
valstring = prettyPrint(pair[1])
result += "------\n%s:\n%s\n" % (keystring, valstring)
# Pretty-print list
elif isinstance(v, list):
dialog = progressDialog("Pretty-printing list...", len(v))
result = "[\n"
for i in range(len(v)):
dialog.setValue(i)
result += str(i) + ": " + prettyPrint(v[i]) + "\n"
if (dialog.wasCanceled()):
return "Pretty-printing canceled"
result += "]\n"
dialog.done(0)
# Pretty-print tuple
elif isinstance(v, tuple):
dialog = progressDialog("Pretty-printing tuple...", len(v))
result = "(\n"
for i in range(len(v)):
dialog.setValue(i)
result += str(i) + ": " + prettyPrint(v[i]) + "\n"
if (dialog.wasCanceled()):
return "Pretty-printing canceled"
result += ")\n"
dialog.done(0)
else:
from .scalarTypes import ToString
result = ToString(v)
return result
| 2,714 | Python | 33.367088 | 79 | 0.648121 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/selectionDataModel.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from collections import OrderedDict
from pxr import Sdf, Gf
from .qt import QtCore
from .customAttributes import (ComputedPropertyNames, BoundingBoxAttribute,
LocalToWorldXformAttribute, ComputedPropertyFactory)
# Indicates that all instances of a prim are selected.
ALL_INSTANCES = -1
class Blocker:
"""Object which can be used to temporarily block the execution of a body of
code. This object is a context manager, and enters a 'blocked' state when
used in a 'with' statement. The 'blocked()' method can be used to find if
the Blocker is in this 'blocked' state.
"""
def __init__(self, exitCallback=lambda: None):
# A count is used rather than a 'blocked' flag to allow for nested
# blocking.
self._count = 0
# Fired when the Blocker's context is exited.
self._exitCallback = exitCallback
def __enter__(self):
"""Enter the 'blocked' state until the context is exited."""
self._count += 1
def __exit__(self, *args):
"""Exit the 'blocked' state."""
self._count -= 1
if not self.blocked():
self._exitCallback()
def blocked(self):
"""Returns True if in the 'blocked' state, and False otherwise."""
return self._count > 0
class _PrimSelection(object):
"""This class keeps track of the core data for prim selection: paths and
instances. The methods here can be called in any order required without
corrupting the path selection state.
"""
def __init__(self):
# The order of paths selected needs to be maintained so we can track the
# focus path. An OrderedDict is more efficient than a list here since it
# supports efficient removal of arbitrary paths but still maintains the
# path order. Sdf.Path objects are the keys in the OrderedDict, and a
# set of selected instances are the values. If all instances are
# selected, None is the value rather than a set.
self._selection = OrderedDict()
self._added = set()
self._removed = set()
def _clearPrimPath(self, path):
"""Clears a path from the selection and updates the diff."""
if path in self._added:
# Path was added in this diff, but we are removing it again. Since
# there is no net change, it shouldn't be in _added or _removed.
self._added.discard(path)
else:
self._removed.add(path)
del self._selection[path]
def _discardInstance(self, path, instance):
"""Discards an instance from the selection, then deletes the path from
the selection if it has no more instances.
"""
instances = self._selection[path]
instances.discard(instance)
if len(instances) == 0:
# Last instance deselected, so path should be deselected.
self._clearPrimPath(path)
def _allInstancesSelected(self, path):
"""Returns True if all instances of a specified path are selected and
False otherwise.
"""
if path in self._selection:
return self._selection[path] == ALL_INSTANCES
else:
return False
def _noInstancesSelected(self, path):
"""Returns True if all instances of a specified path are selected and
False otherwise.
"""
return path not in self._selection
def clear(self):
"""Clear the path selection."""
# _clearPrimPath modifies self._selection, so make a copy of keys
# before mutating it.
for path in list(self._selection.keys()):
self._clearPrimPath(path)
def removeMatchingPaths(self, matches):
"""Remove any paths that pass the given predicate"""
# _clearPrimPath modifies self._selection, so make a copy of keys
# before mutating it.
for path in list(self._selection.keys()):
if matches(path):
self._clearPrimPath(path)
def addPrimPath(self, path, instance=ALL_INSTANCES):
"""Add a path to the selection. If an instance is given, then only add
that instance. If all instances are selected when this happens then the
single instance will become the only selected one.
"""
# If the path is not already in the selection, update the diff.
if path not in self._selection:
if path in self._removed:
# Path was removed in this diff, but is back now. Since there is
# no net change, it shouldn't be in _added or _removed.
self._removed.discard(path)
else:
self._added.add(path)
if instance == ALL_INSTANCES:
# Trying to add all instances, make sure all instances are selected.
self._selection[path] = ALL_INSTANCES
else:
# Trying to add a single instance.
if self._allInstancesSelected(path) or self._noInstancesSelected(path):
# Either all instances selected or none selected. Create an
# empty set of instances then add the target instance.
self._selection[path] = set()
self._selection[path].add(instance)
def removePrimPath(self, path, instance=ALL_INSTANCES):
"""Remove a path from the selection. If an instance is given, then only
remove that instance. If all instances are selected when this happens,
deselect all instances. If the target does not exist in the selection,
do nothing.
"""
if path in self._selection:
if instance == ALL_INSTANCES or self._allInstancesSelected(path):
# Want to deselect all instances or all instances are selected.
# Either way, deselect all.
self._clearPrimPath(path)
else:
# Some instances selected and want to deselect one of them.
self._discardInstance(path, instance)
def togglePrimPath(self, path, instance=ALL_INSTANCES):
"""Toggle the selection of a path. If an instance is given, only toggle
that instance's selection.
"""
if path not in self._selection:
self.addPrimPath(path, instance)
return
# Path is at least partially selected.
if instance == ALL_INSTANCES:
# Trying to toggle all instances.
if self._allInstancesSelected(path):
# All instances are already selected, so deselect the path.
self._clearPrimPath(path)
else:
# Only some instances are selected, select all all of them.
self._selection[path] = ALL_INSTANCES
else:
# Trying to toggle a single instance.
if self._allInstancesSelected(path):
# Currently all instances are selected. Switch selection to
# only the new instance.
self._selection[path] = set([instance])
else:
# Some instances already selected. Toggle the new instance
# in the selection.
instances = self._selection[path]
if instance in instances:
self._discardInstance(path, instance)
else:
instances.add(instance)
def getPrimPaths(self):
"""Get a list of paths that are at least partially selected."""
return list(self._selection.keys())
def getPrimPathInstances(self):
"""Get the full selection of paths and their corresponding selected
instances.
"""
return OrderedDict(
(path, set(instances)) if isinstance(instances, set) else (path, instances)
for path, instances in self._selection.items())
def getDiff(self):
"""Get the prims added to or removed from the selection since the last
time getDiff() was called.
"""
diff = (self._added, self._removed)
self._added = set()
self._removed = set()
return diff
class _PropSelection(object):
"""This class keeps track of the state of property selection."""
def __init__(self):
self._selection = OrderedDict()
def clear(self):
"""Clears the property selection."""
self._selection = OrderedDict()
def addPropPath(self, primPath, propName):
"""Add a property to the selection."""
propTuple = (primPath, propName)
# If this property is already selected, remove it from the selection and
# re-add it so it becomes the focus property.
if propTuple in self._selection:
targets = self._selection[propTuple]
del self._selection[propTuple]
self._selection[propTuple] = targets
else:
self._selection[propTuple] = set()
def removePropPath(self, primPath, propName):
"""Remove a property from the selection."""
propTuple = (primPath, propName)
if propTuple in self._selection:
del self._selection[propTuple]
def addTarget(self, primPath, propName, target):
"""Add a target to the selection. Also add the target's property if it
is not already in the selection.
"""
propTuple = (primPath, propName)
# If this property is already selected, remove it from the selection and
# re-add it so it becomes the focus property.
if propTuple in self._selection:
targets = self._selection[propTuple]
del self._selection[propTuple]
self._selection[propTuple] = targets
else:
targets = self._selection.setdefault(propTuple, set())
targets.add(target)
def removeTarget(self, primPath, propName, target):
"""Remove a target from the selection. If the target or its property are
not already in the selection, nothing is changed.
"""
propTuple = (primPath, propName)
if propTuple in self._selection:
self._selection[propTuple].discard(target)
def getPropPaths(self):
"""Get the list of properties."""
return list(self._selection.keys())
def getTargets(self):
"""Get a dictionary which maps selected properties to a set of their
selected targets or connections.
"""
propTargets = OrderedDict()
for propTuple, targets in self._selection.items():
propTargets[propTuple] = set(targets)
return propTargets
class SelectionDataModel(QtCore.QObject):
"""Data model managing the current selection of prims and properties.
Please note that the owner of an instance of this class is
responsible for calling SelectionDataModel.removeUnpopulatedPrims() when
appropriate, lest methods like getPrims() return invalid prims."""
# Signals must be declared in the class, but each instance of the selection
# data model has its own unique signal instances.
# When emitted, includes two sets: one of newly selected prims, and one of
# newly deselected prims.
signalPrimSelectionChanged = QtCore.Signal(set, set)
signalPropSelectionChanged = QtCore.Signal()
signalComputedPropSelectionChanged = QtCore.Signal()
def __init__(self, rootDataModel, _computedPropFactory=None):
QtCore.QObject.__init__(self)
self._rootDataModel = rootDataModel
# _computedPropFactory may be passed explicitly for unit testing.
if _computedPropFactory is None:
self._computedPropFactory = ComputedPropertyFactory(
self._rootDataModel)
else:
self._computedPropFactory = _computedPropFactory
self.batchPrimChanges = Blocker(
exitCallback=self._primSelectionChanged)
self.batchPropChanges = Blocker(
exitCallback=self._propSelectionChanged)
self.batchComputedPropChanges = Blocker(
exitCallback=self._computedPropSelectionChanged)
self._pointSelection = Gf.Vec3f(0.0, 0.0, 0.0)
self._primSelection = _PrimSelection()
# The path selection should never be empty. If it ever is, we
# immediately add the root path before returning to user control (see
# _primSelectionChanged).
self._primSelection.addPrimPath(Sdf.Path.absoluteRootPath)
# Clear the prim selection diff so we don't get the absolute root in the
# first signal from signalPrimSelectionChanged.
self._primSelection.getDiff()
self._lcdPathSelection = [Sdf.Path.absoluteRootPath]
self._propSelection = _PropSelection()
self._computedPropSelection = _PropSelection()
### Internal Operations ###
def _primSelectionChanged(self, emitSelChangedSignal=True):
"""Should be called whenever a change is made to _primSelection. Some
final work is done then the prim selection changed signal is emitted.
"""
# If updates are suppressed, do not emit a signal or do any
# pre-processing.
if self.batchPrimChanges.blocked():
return
# Make sure there is always at least one path selected.
if len(self.getPrimPaths()) == 0:
self._primSelection.addPrimPath(Sdf.Path.absoluteRootPath)
# Recalculate the LCD prims whenever the path selection changes.
paths = self._primSelection.getPrimPaths()
if len(paths) > 1:
paths = [path for path in paths
if path != Sdf.Path.absoluteRootPath]
self._lcdPathSelection = Sdf.Path.RemoveDescendentPaths(paths)
# Finally, emit the changed signal.
added, removed = self._primSelection.getDiff()
if emitSelChangedSignal:
self.signalPrimSelectionChanged.emit(added, removed)
def _propSelectionChanged(self):
"""Should be called whenever a change is made to _propSelection."""
# If updates are suppressed, do not emit a signal or do any
# pre-processing.
if self.batchPropChanges.blocked():
return
self.signalPropSelectionChanged.emit()
def _computedPropSelectionChanged(self):
"""Should be called whenever a change is made to _computedPropSelection.
"""
# If updates are suppressed, do not emit a signal or do any
# pre-processing.
if self.batchComputedPropChanges.blocked():
return
self.signalComputedPropSelectionChanged.emit()
def _ensureValidPrimPath(self, path):
"""Validate an input path. If it is a string path, convert it to an
Sdf.Path object.
"""
sdfPath = Sdf.Path(str(path))
if not sdfPath.IsAbsoluteRootOrPrimPath():
raise ValueError("Path must be a prim path, got: {}".format(
repr(sdfPath)))
return sdfPath
def _validateInstanceIndexParameter(self, instance):
"""Validate an instance used as a parameter. This can be any positive
int or ALL_INSTANCES."""
validIndex = False
if isinstance(instance, int):
if instance >= 0 or instance == ALL_INSTANCES:
validIndex = True
if not validIndex:
raise ValueError(
"Instance must be a positive int or ALL_INSTANCES"
", got: {}".format(repr(instance)))
def _ensureValidPropPath(self, prop):
"""Validate a property."""
sdfPath = Sdf.Path(str(prop))
if not sdfPath.IsPropertyPath():
raise ValueError("Path must be a property path, got: {}".format(
repr(sdfPath)))
return sdfPath
def _ensureValidTargetPath(self, target):
"""Validate a property target or connection."""
return Sdf.Path(str(target))
def _getPropFromPath(self, path):
"""Get a Usd property object from a property path."""
prim = self._rootDataModel.stage.GetPrimAtPath(path.GetPrimPath())
return prim.GetProperty(path.name)
def _getTargetFromPath(self, path):
"""Get the Usd object from a target path. It can be either a Usd prim or
Usd property.
"""
if path.IsPropertyPath():
return self._getPropFromPath(path)
else:
return self._rootDataModel.stage.GetPrimAtPath(path)
def _requireNotBatchingPrims(self):
"""Raise an error if we are currently batching prim selection changes.
We don't want to allow reading prim selection state in the middle of a
batch.
"""
if self.batchPrimChanges.blocked():
raise RuntimeError(
"Cannot get prim selection state while batching changes.")
def _requireNotBatchingProps(self):
"""Raise an error if we are currently batching prop selection changes.
We don't want to allow reading prop selection state in the middle of a
batch.
"""
if self.batchPropChanges.blocked():
raise RuntimeError(
"Cannot get property selection state while batching changes.")
def _getComputedPropFromPath(self, primPath, propName):
"""Get a CustomAttribute object from a prim path and property name.
Raise an error if the property name does not match any known
CustomAttribute.
"""
prim = self._rootDataModel.stage.GetPrimAtPath(primPath)
return self._computedPropFactory.getComputedProperty(prim, propName)
def _requireNotBatchingComputedProps(self):
"""Raise an error if we are currently batching prop selection changes.
We don't want to allow reading prop selection state in the middle of a
batch.
"""
if self.batchComputedPropChanges.blocked():
raise RuntimeError("Cannot get computed property selection state "
"while batching changes.")
def _buildPropPath(self, primPath, propName):
"""Build a new property path from a prim path and a property name."""
return Sdf.Path(str(primPath) + "." + propName)
def _validateComputedPropName(self, propName):
"""Validate a computed property name."""
if propName not in ComputedPropertyNames:
raise ValueError("Invalid computed property name: {}".format(
repr(propName)))
def _switchProps(self, fromPrimPath, toPrimPath):
"""Switch all selected properties from one prim to another. Only do this
if all properties currently belong to the "from" prim.
"""
propTargets = self.getPropTargetPaths()
computedProps = self.getComputedPropPaths()
# Check that all properties belong to the "from" prim.
for propPath in propTargets:
if propPath.GetPrimPath() != fromPrimPath:
return
for propPrimPath, propName in computedProps:
if propPrimPath != fromPrimPath:
return
# Switch all properties to the "to" prim.
with self.batchPropChanges:
self.clearProps()
# Root prim cannot have non-computed properties. The property paths
# in this case are invalid.
if str(toPrimPath) != "/":
for propPath, targets in propTargets.items():
newPropPath = self._buildPropPath(toPrimPath, propPath.name)
self.addPropPath(newPropPath)
for target in targets:
self.addPropTargetPath(newPropPath, target)
with self.batchComputedPropChanges:
self.clearComputedProps()
for primPath, propName in computedProps:
self.addComputedPropPath(toPrimPath, propName)
### General Operations ###
def clear(self):
"""Clear all selections."""
self.clearPoint()
self.clearPrims()
self.clearProps()
def clearPoint(self):
self.setPoint(Gf.Vec3f(0.0, 0.0, 0.0))
def setPoint(self, point):
self._pointSelection = point
def getPoint(self):
return self._pointSelection
### Prim Path Operations ###
def clearPrims(self):
"""Clear the prim selection (same as path selection)."""
self._primSelection.clear()
self._primSelectionChanged()
def addPrimPath(self, path, instance=ALL_INSTANCES):
"""Add a path to the path selection. If an instance is given, only add
that instance.
"""
path = self._ensureValidPrimPath(path)
self._validateInstanceIndexParameter(instance)
self._primSelection.addPrimPath(path, instance)
self._primSelectionChanged()
def removePrimPath(self, path, instance=ALL_INSTANCES):
"""Remove a path from the path selection. If an instance is given, only
remove that instance. If the target does not exist in the selection, do
nothing.
"""
path = self._ensureValidPrimPath(path)
self._validateInstanceIndexParameter(instance)
self._primSelection.removePrimPath(path, instance)
self._primSelectionChanged()
def togglePrimPath(self, path, instance=ALL_INSTANCES):
"""Toggle a path in the path selection. If an instance is given, only
that instance is toggled.
"""
path = self._ensureValidPrimPath(path)
self._validateInstanceIndexParameter(instance)
self._primSelection.togglePrimPath(path, instance)
self._primSelectionChanged()
def setPrimPath(self, path, instance=ALL_INSTANCES):
"""Clear the prim selection then add a single prim path back to the
selection. If an instance is given, only add that instance.
"""
with self.batchPrimChanges:
self.clearPrims()
self.addPrimPath(path, instance)
def getFocusPrimPath(self):
"""Get the path currently in focus."""
self._requireNotBatchingPrims()
return self._primSelection.getPrimPaths()[0]
def getPrimPaths(self):
"""Get a list of all selected paths."""
self._requireNotBatchingPrims()
return self._primSelection.getPrimPaths()
def getLCDPaths(self):
"""Get a list of paths from the selection who do not have an ancestor
that is also in the selection. The "Least Common Denominator" paths.
"""
self._requireNotBatchingPrims()
return list(self._lcdPathSelection)
def getPrimPathInstances(self):
"""Get a dictionary which maps each selected prim to a set of its
selected instances. If all of a path's instances are selected, the value
is ALL_INSTANCES rather than a set.
"""
self._requireNotBatchingPrims()
return self._primSelection.getPrimPathInstances()
def switchToPrimPath(self, path, instance=ALL_INSTANCES):
"""Select only the given prim path. If only a single prim was selected
before and all selected properties belong to this prim, select the
corresponding properties on the new prim instead. If an instance is
given, only select that instance.
"""
path = self._ensureValidPrimPath(path)
oldPrimPaths = self.getPrimPaths()
with self.batchPrimChanges:
self.clearPrims()
self.addPrimPath(path, instance)
if len(oldPrimPaths) == 1:
self._switchProps(oldPrimPaths[0], path)
### Prim Operations ###
# These are all convenience methods which just call their respective path
# operations.
def addPrim(self, prim, instance=ALL_INSTANCES):
"""Add a prim's path to the path selection. If an instance is given,
only add that instance.
"""
self.addPrimPath(prim.GetPath(), instance)
def removePrim(self, prim, instance=ALL_INSTANCES):
"""Remove a prim from the prim selection. If an instance is given, only
remove that instance. If the target does not exist in the selection, do
nothing.
"""
self.removePrimPath(prim.GetPath(), instance)
def togglePrim(self, prim, instance=ALL_INSTANCES):
"""Toggle a prim's path in the path selection. If an instance is given,
only that instance is toggled.
"""
self.togglePrimPath(prim.GetPath(), instance)
def setPrim(self, prim, instance=ALL_INSTANCES):
"""Clear the prim selection then add a single prim back to the
selection. If an instance is given, only add that instance.
"""
self.setPrimPath(prim.GetPath(), instance)
def getFocusPrim(self):
"""Get the prim whose path is currently in focus."""
return self._rootDataModel.stage.GetPrimAtPath(self.getFocusPrimPath())
def getPrims(self):
"""Get a list of all prims whose paths are selected."""
return [self._rootDataModel.stage.GetPrimAtPath(path)
for path in self.getPrimPaths()]
def getLCDPrims(self):
"""Get a list of prims whose paths are both selected and do not have an
ancestor that is also in the selection. The "Least Common Denominator"
prims.
"""
return [self._rootDataModel.stage.GetPrimAtPath(path)
for path in self.getLCDPaths()]
def getPrimInstances(self):
"""Get a dictionary which maps each prim whose path is selected to a set
of its selected instances. If all of a path's instances are selected,
the value is ALL_INSTANCES rather than a set.
"""
return OrderedDict(
(self._rootDataModel.stage.GetPrimAtPath(path), instance)
for path, instance in self.getPrimPathInstances().items())
def switchToPrim(self, prim, instance=ALL_INSTANCES):
"""Select only the given prim. If only a single prim was selected before
and all selected properties belong to this prim, select the
corresponding properties on the new prim instead.
"""
self.switchToPrimPath(prim.GetPath(), instance)
### Prim Group Removal Operations ###
# Convenience methods for removing groups of prims
def removeInactivePrims(self):
"""Remove all inactive prims"""
for prim in self.getPrims():
if not prim.IsActive():
self.removePrim(prim)
def removeMasterPrims(self):
"""Remove all master prims"""
for prim in self.getPrims():
if prim.IsMaster() or prim.IsInMaster():
self.removePrim(prim)
def removeAbstractPrims(self):
"""Remove all abstract prims"""
for prim in self.getPrims():
if prim.IsAbstract():
self.removePrim(prim)
def removeUndefinedPrims(self):
"""Remove all undefined prims"""
for prim in self.getPrims():
if not prim.IsDefined():
self.removePrim(prim)
def removeUnpopulatedPrims(self):
"""Remove all prim paths whose corresponding prims do not currently
exist on the stage. It is the application's responsibility to
call this method while it is processing changes to the stage,
*before* querying this object for selections. Because this is a
synchronization operation rather than an expression of GUI state
change, it does *not* perform any notifications/signals, which could
cause reentrant application change processing."""
stage = self._rootDataModel.stage
self._primSelection.removeMatchingPaths(lambda path: not stage.GetPrimAtPath(path))
self._primSelectionChanged(emitSelChangedSignal=False)
### Property Path Operations ###
def clearProps(self):
"""Clear the property selection."""
self._propSelection.clear()
self._propSelectionChanged()
def addPropPath(self, path):
"""Add a property to the selection."""
path = self._ensureValidPropPath(path)
primPath = path.GetPrimPath()
propName = path.name
self._propSelection.addPropPath(primPath, propName)
self._propSelectionChanged()
def removePropPath(self, path):
"""Remove a property from the selection."""
path = self._ensureValidPropPath(path)
primPath = path.GetPrimPath()
propName = path.name
self._propSelection.removePropPath(primPath, propName)
self._propSelectionChanged()
def setPropPath(self, path):
"""Clear the property selection, then add a single property path back to
the selection.
"""
path = self._ensureValidPropPath(path)
with self.batchPropChanges:
self.clearProps()
self.addPropPath(path)
def addPropTargetPath(self, path, targetPath):
"""Select a property's target or connection."""
path = self._ensureValidPropPath(path)
targetPath = self._ensureValidTargetPath(targetPath)
primPath = path.GetPrimPath()
propName = path.name
self._propSelection.addTarget(primPath, propName, targetPath)
self._propSelectionChanged()
def removePropTargetPath(self, path, targetPath):
"""Deselect a property's target or connection."""
path = self._ensureValidPropPath(path)
targetPath = self._ensureValidTargetPath(targetPath)
primPath = path.GetPrimPath()
propName = path.name
self._propSelection.removeTarget(primPath, propName, targetPath)
self._propSelectionChanged()
def setPropTargetPath(self, path, targetPath):
"""Clear the property selection, then add a single property path back to
the selection with a target.
"""
with self.batchPropChanges:
self.clearProps()
self.addPropTargetPath(path, targetPath)
def getFocusPropPath(self):
"""Get the focus property from the property selection."""
self._requireNotBatchingProps()
propPaths = [self._buildPropPath(*propTuple)
for propTuple in self._propSelection.getPropPaths()]
if len(propPaths) > 0:
return propPaths[-1]
else:
return None
def getPropPaths(self):
"""Get a list of all selected properties."""
self._requireNotBatchingProps()
propPaths = [self._buildPropPath(*propTuple)
for propTuple in self._propSelection.getPropPaths()]
return propPaths
def getPropTargetPaths(self):
"""Get a dictionary which maps selected properties to a set of their
selected targets or connections.
"""
self._requireNotBatchingProps()
return OrderedDict((self._buildPropPath(*propTuple), set(targets))
for propTuple, targets in self._propSelection.getTargets().items())
### Property Operations ###
def addProp(self, prop):
"""Add a property to the selection."""
self.addPropPath(prop.GetPath())
def removeProp(self, prop):
"""Remove a property from the selection."""
self.removePropPath(prop.GetPath())
def setProp(self, prop):
"""Clear the property selection, then add a single property back to the
selection.
"""
self.setPropPath(prop.GetPath())
def addPropTarget(self, prop, target):
"""Select a property's target or connection."""
self.addPropTargetPath(prop.GetPath(), target.GetPath())
def removePropTarget(self, prop, target):
"""Deselect a property's target or connection."""
self.removePropTargetPath(prop.GetPath(), target.GetPath())
def setPropTarget(self, prop, target):
"""Clear the property selection, then add a single property back to the
selection with a target.
"""
self.removePropTargetPath(prop.GetPath(), target.GetPath())
def getFocusProp(self):
"""Get the focus property from the property selection."""
focusPath = self.getFocusPropPath()
if focusPath is None:
return None
return self._getPropFromPath(focusPath)
def getProps(self):
"""Get a list of all selected properties."""
return [self._getPropFromPath(path)
for path in self.getPropPaths()]
def getPropTargets(self):
"""Get a dictionary which maps selected properties to a set of their
selected targets or connections.
"""
propTargets = OrderedDict()
for propPath, targetPaths in self.getPropTargetPaths().items():
prop = self._getPropFromPath(propPath)
targets = {self._getTargetFromPath(target)
for target in targetPaths}
propTargets[prop] = targets
return propTargets
### Computed Property Path Operations ###
def clearComputedProps(self):
"""Clear the computed property selection."""
self._computedPropSelection.clear()
self._computedPropSelectionChanged()
def addComputedPropPath(self, primPath, propName):
"""Add a computed property to the selection."""
primPath = self._ensureValidPrimPath(primPath)
self._validateComputedPropName(propName)
self._computedPropSelection.addPropPath(primPath, propName)
self._computedPropSelectionChanged()
def removeComputedPropPath(self, primPath, propName):
"""Remove a computed property from the selection."""
primPath = self._ensureValidPrimPath(primPath)
self._validateComputedPropName(propName)
self._computedPropSelection.removePropPath(primPath, propName)
self._computedPropSelectionChanged()
def setComputedPropPath(self, primPath, propName):
"""Clear the computed property selection, then add a single computed
property path back to the selection.
"""
primPath = self._ensureValidPrimPath(primPath)
self._validateComputedPropName(propName)
with self.batchComputedPropChanges:
self.clearComputedProps()
self.addComputedPropPath(primPath, propName)
def getFocusComputedPropPath(self):
"""Get the focus computed property from the property selection."""
self._requireNotBatchingComputedProps()
propPaths = self._computedPropSelection.getPropPaths()
if len(propPaths) > 0:
return propPaths[-1]
else:
return (None, None)
def getComputedPropPaths(self):
"""Get a list of all selected computed properties."""
self._requireNotBatchingComputedProps()
return self._computedPropSelection.getPropPaths()
### Computed Property Operations ###
def addComputedProp(self, prop):
"""Add a computed property to the selection."""
self.addComputedPropPath(prop.GetPrimPath(), prop.GetName())
def removeComputedProp(self, prop):
"""Remove a computed property from the selection."""
self.removeComputedPropPath(prop.GetPrimPath(), prop.GetName())
def setComputedProp(self, prop):
"""Clear the computed property selection, then add a single computed
property back to the selection.
"""
self.setComputedPropPath(prop.GetPrimPath(), prop.GetName())
def getFocusComputedProp(self):
"""Get the focus computed property from the property selection."""
focusPath = self.getFocusComputedPropPath()
if focusPath == (None, None):
return None
return self._getComputedPropFromPath(*focusPath)
def getComputedProps(self):
"""Get a list of all selected computed properties."""
return [self._getComputedPropFromPath(*path)
for path in self.getComputedPropPaths()]
| 36,931 | Python | 34.039848 | 91 | 0.638461 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/propertyLegendUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'propertyLegendUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_PropertyLegend(object):
def setupUi(self, PropertyLegend):
if not PropertyLegend.objectName():
PropertyLegend.setObjectName(u"PropertyLegend")
PropertyLegend.setWindowModality(Qt.NonModal)
PropertyLegend.resize(654, 151)
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(PropertyLegend.sizePolicy().hasHeightForWidth())
PropertyLegend.setSizePolicy(sizePolicy)
self.gridLayout = QGridLayout(PropertyLegend)
self.gridLayout.setObjectName(u"gridLayout")
self.gridLayout_2 = QGridLayout()
self.gridLayout_2.setSpacing(3)
self.gridLayout_2.setObjectName(u"gridLayout_2")
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.propertyLegendColorNoValue = QGraphicsView(PropertyLegend)
self.propertyLegendColorNoValue.setObjectName(u"propertyLegendColorNoValue")
self.propertyLegendColorNoValue.setMaximumSize(QSize(20, 15))
self.horizontalLayout.addWidget(self.propertyLegendColorNoValue)
self.propertyLegendLabelNoValue = QLabel(PropertyLegend)
self.propertyLegendLabelNoValue.setObjectName(u"propertyLegendLabelNoValue")
font = QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.propertyLegendLabelNoValue.setFont(font)
self.horizontalLayout.addWidget(self.propertyLegendLabelNoValue)
self.horizontalSpacer_8 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout.addItem(self.horizontalSpacer_8)
self.gridLayout_2.addLayout(self.horizontalLayout, 0, 0, 1, 1)
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.propertyLegendColorDefault = QGraphicsView(PropertyLegend)
self.propertyLegendColorDefault.setObjectName(u"propertyLegendColorDefault")
self.propertyLegendColorDefault.setMaximumSize(QSize(20, 15))
self.horizontalLayout_2.addWidget(self.propertyLegendColorDefault)
self.propertyLegendLabelDefault = QLabel(PropertyLegend)
self.propertyLegendLabelDefault.setObjectName(u"propertyLegendLabelDefault")
self.propertyLegendLabelDefault.setFont(font)
self.horizontalLayout_2.addWidget(self.propertyLegendLabelDefault)
self.horizontalSpacer_10 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(self.horizontalSpacer_10)
self.gridLayout_2.addLayout(self.horizontalLayout_2, 0, 1, 1, 1)
self.horizontalLayout_5 = QHBoxLayout()
self.horizontalLayout_5.setObjectName(u"horizontalLayout_5")
self.propertyLegendColorTimeSample = QGraphicsView(PropertyLegend)
self.propertyLegendColorTimeSample.setObjectName(u"propertyLegendColorTimeSample")
self.propertyLegendColorTimeSample.setMaximumSize(QSize(20, 15))
self.horizontalLayout_5.addWidget(self.propertyLegendColorTimeSample)
self.propertyLegendLabelTimeSample = QLabel(PropertyLegend)
self.propertyLegendLabelTimeSample.setObjectName(u"propertyLegendLabelTimeSample")
self.propertyLegendLabelTimeSample.setFont(font)
self.horizontalLayout_5.addWidget(self.propertyLegendLabelTimeSample)
self.horizontalSpacer_12 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(self.horizontalSpacer_12)
self.gridLayout_2.addLayout(self.horizontalLayout_5, 0, 2, 1, 1)
self.horizontalLayout_3 = QHBoxLayout()
self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
self.propertyLegendColorFallback = QGraphicsView(PropertyLegend)
self.propertyLegendColorFallback.setObjectName(u"propertyLegendColorFallback")
self.propertyLegendColorFallback.setMaximumSize(QSize(20, 15))
self.horizontalLayout_3.addWidget(self.propertyLegendColorFallback)
self.propertyLegendLabelFallback = QLabel(PropertyLegend)
self.propertyLegendLabelFallback.setObjectName(u"propertyLegendLabelFallback")
self.propertyLegendLabelFallback.setFont(font)
self.horizontalLayout_3.addWidget(self.propertyLegendLabelFallback)
self.horizontalSpacer_9 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(self.horizontalSpacer_9)
self.gridLayout_2.addLayout(self.horizontalLayout_3, 1, 0, 1, 1)
self.horizontalLayout_4 = QHBoxLayout()
self.horizontalLayout_4.setObjectName(u"horizontalLayout_4")
self.propertyLegendColorCustom = QGraphicsView(PropertyLegend)
self.propertyLegendColorCustom.setObjectName(u"propertyLegendColorCustom")
self.propertyLegendColorCustom.setMaximumSize(QSize(20, 15))
self.horizontalLayout_4.addWidget(self.propertyLegendColorCustom)
self.propertyLegendLabelCustom = QLabel(PropertyLegend)
self.propertyLegendLabelCustom.setObjectName(u"propertyLegendLabelCustom")
self.horizontalLayout_4.addWidget(self.propertyLegendLabelCustom)
self.horizontalSpacer_11 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(self.horizontalSpacer_11)
self.gridLayout_2.addLayout(self.horizontalLayout_4, 1, 1, 1, 1)
self.horizontalLayout_6 = QHBoxLayout()
self.horizontalLayout_6.setObjectName(u"horizontalLayout_6")
self.propertyLegendColorValueClips = QGraphicsView(PropertyLegend)
self.propertyLegendColorValueClips.setObjectName(u"propertyLegendColorValueClips")
self.propertyLegendColorValueClips.setMaximumSize(QSize(20, 15))
self.horizontalLayout_6.addWidget(self.propertyLegendColorValueClips)
self.propertyLegendLabelValueClips = QLabel(PropertyLegend)
self.propertyLegendLabelValueClips.setObjectName(u"propertyLegendLabelValueClips")
self.propertyLegendLabelValueClips.setFont(font)
self.horizontalLayout_6.addWidget(self.propertyLegendLabelValueClips)
self.horizontalSpacer_13 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(self.horizontalSpacer_13)
self.gridLayout_2.addLayout(self.horizontalLayout_6, 1, 2, 1, 1)
self.gridLayout.addLayout(self.gridLayout_2, 0, 0, 1, 3)
self.verticalLayout = QVBoxLayout()
self.verticalLayout.setSpacing(3)
self.verticalLayout.setObjectName(u"verticalLayout")
self.horizontalLayout_9 = QHBoxLayout()
self.horizontalLayout_9.setSpacing(3)
self.horizontalLayout_9.setObjectName(u"horizontalLayout_9")
self.propertyLegendAttrPlainIcon = QLabel(PropertyLegend)
self.propertyLegendAttrPlainIcon.setObjectName(u"propertyLegendAttrPlainIcon")
self.horizontalLayout_9.addWidget(self.propertyLegendAttrPlainIcon)
self.propertyLegendAttrPlainDesc = QLabel(PropertyLegend)
self.propertyLegendAttrPlainDesc.setObjectName(u"propertyLegendAttrPlainDesc")
self.propertyLegendAttrPlainDesc.setFont(font)
self.horizontalLayout_9.addWidget(self.propertyLegendAttrPlainDesc)
self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_9.addItem(self.horizontalSpacer)
self.verticalLayout.addLayout(self.horizontalLayout_9)
self.horizontalLayout_10 = QHBoxLayout()
self.horizontalLayout_10.setSpacing(3)
self.horizontalLayout_10.setObjectName(u"horizontalLayout_10")
self.propertyLegendRelPlainIcon = QLabel(PropertyLegend)
self.propertyLegendRelPlainIcon.setObjectName(u"propertyLegendRelPlainIcon")
self.horizontalLayout_10.addWidget(self.propertyLegendRelPlainIcon)
self.propertyLegendRelPlainDesc = QLabel(PropertyLegend)
self.propertyLegendRelPlainDesc.setObjectName(u"propertyLegendRelPlainDesc")
self.propertyLegendRelPlainDesc.setFont(font)
self.horizontalLayout_10.addWidget(self.propertyLegendRelPlainDesc)
self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_10.addItem(self.horizontalSpacer_2)
self.verticalLayout.addLayout(self.horizontalLayout_10)
self.horizontalLayout_11 = QHBoxLayout()
self.horizontalLayout_11.setSpacing(3)
self.horizontalLayout_11.setObjectName(u"horizontalLayout_11")
self.propertyLegendCompIcon = QLabel(PropertyLegend)
self.propertyLegendCompIcon.setObjectName(u"propertyLegendCompIcon")
self.horizontalLayout_11.addWidget(self.propertyLegendCompIcon)
self.propertyLegendCompDesc = QLabel(PropertyLegend)
self.propertyLegendCompDesc.setObjectName(u"propertyLegendCompDesc")
self.propertyLegendCompDesc.setFont(font)
self.horizontalLayout_11.addWidget(self.propertyLegendCompDesc)
self.horizontalSpacer_3 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_11.addItem(self.horizontalSpacer_3)
self.verticalLayout.addLayout(self.horizontalLayout_11)
self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 1)
self.verticalLayout_2 = QVBoxLayout()
self.verticalLayout_2.setObjectName(u"verticalLayout_2")
self.horizontalLayout_12 = QHBoxLayout()
self.horizontalLayout_12.setSpacing(3)
self.horizontalLayout_12.setObjectName(u"horizontalLayout_12")
self.propertyLegendConnIcon = QLabel(PropertyLegend)
self.propertyLegendConnIcon.setObjectName(u"propertyLegendConnIcon")
self.horizontalLayout_12.addWidget(self.propertyLegendConnIcon)
self.propertyLegendConnDesc = QLabel(PropertyLegend)
self.propertyLegendConnDesc.setObjectName(u"propertyLegendConnDesc")
self.propertyLegendConnDesc.setFont(font)
self.horizontalLayout_12.addWidget(self.propertyLegendConnDesc)
self.horizontalSpacer_4 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_12.addItem(self.horizontalSpacer_4)
self.verticalLayout_2.addLayout(self.horizontalLayout_12)
self.horizontalLayout_13 = QHBoxLayout()
self.horizontalLayout_13.setSpacing(3)
self.horizontalLayout_13.setObjectName(u"horizontalLayout_13")
self.propertyLegendTargetIcon = QLabel(PropertyLegend)
self.propertyLegendTargetIcon.setObjectName(u"propertyLegendTargetIcon")
self.horizontalLayout_13.addWidget(self.propertyLegendTargetIcon)
self.propertyLegendTargetDesc = QLabel(PropertyLegend)
self.propertyLegendTargetDesc.setObjectName(u"propertyLegendTargetDesc")
self.propertyLegendTargetDesc.setMinimumSize(QSize(20, 20))
self.propertyLegendTargetDesc.setFont(font)
self.horizontalLayout_13.addWidget(self.propertyLegendTargetDesc)
self.horizontalSpacer_5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_13.addItem(self.horizontalSpacer_5)
self.verticalLayout_2.addLayout(self.horizontalLayout_13)
self.horizontalLayout_14 = QHBoxLayout()
self.horizontalLayout_14.setObjectName(u"horizontalLayout_14")
self.inheritedPropertyIcon = QLabel(PropertyLegend)
self.inheritedPropertyIcon.setObjectName(u"inheritedPropertyIcon")
self.inheritedPropertyIcon.setTextFormat(Qt.RichText)
self.horizontalLayout_14.addWidget(self.inheritedPropertyIcon)
self.inheritedPropertyText = QLabel(PropertyLegend)
self.inheritedPropertyText.setObjectName(u"inheritedPropertyText")
font1 = QFont()
font1.setItalic(False)
self.inheritedPropertyText.setFont(font1)
self.inheritedPropertyText.setFrameShape(QFrame.NoFrame)
self.inheritedPropertyText.setTextFormat(Qt.RichText)
self.inheritedPropertyText.setAlignment(Qt.AlignCenter)
self.inheritedPropertyText.setWordWrap(False)
self.horizontalLayout_14.addWidget(self.inheritedPropertyText)
self.horizontalSpacer_14 = QSpacerItem(13, 13, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_14.addItem(self.horizontalSpacer_14)
self.verticalLayout_2.addLayout(self.horizontalLayout_14)
self.gridLayout.addLayout(self.verticalLayout_2, 1, 1, 1, 1)
self.verticalLayout_3 = QVBoxLayout()
self.verticalLayout_3.setObjectName(u"verticalLayout_3")
self.horizontalLayout_8 = QHBoxLayout()
self.horizontalLayout_8.setSpacing(3)
self.horizontalLayout_8.setObjectName(u"horizontalLayout_8")
self.propertyLegendAttrWithConnIcon = QLabel(PropertyLegend)
self.propertyLegendAttrWithConnIcon.setObjectName(u"propertyLegendAttrWithConnIcon")
self.horizontalLayout_8.addWidget(self.propertyLegendAttrWithConnIcon)
self.propertyLegendAttrWithConnDesc = QLabel(PropertyLegend)
self.propertyLegendAttrWithConnDesc.setObjectName(u"propertyLegendAttrWithConnDesc")
self.propertyLegendAttrWithConnDesc.setFont(font)
self.horizontalLayout_8.addWidget(self.propertyLegendAttrWithConnDesc)
self.horizontalSpacer_6 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_8.addItem(self.horizontalSpacer_6)
self.verticalLayout_3.addLayout(self.horizontalLayout_8)
self.horizontalLayout_7 = QHBoxLayout()
self.horizontalLayout_7.setSpacing(3)
self.horizontalLayout_7.setObjectName(u"horizontalLayout_7")
self.propertyLegendRelWithTargetIcon = QLabel(PropertyLegend)
self.propertyLegendRelWithTargetIcon.setObjectName(u"propertyLegendRelWithTargetIcon")
self.horizontalLayout_7.addWidget(self.propertyLegendRelWithTargetIcon)
self.propertyLegendRelWithTargetDesc = QLabel(PropertyLegend)
self.propertyLegendRelWithTargetDesc.setObjectName(u"propertyLegendRelWithTargetDesc")
self.propertyLegendRelWithTargetDesc.setFont(font)
self.horizontalLayout_7.addWidget(self.propertyLegendRelWithTargetDesc)
self.horizontalSpacer_7 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_7.addItem(self.horizontalSpacer_7)
self.verticalLayout_3.addLayout(self.horizontalLayout_7)
self.horizontalSpacer_15 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.verticalLayout_3.addItem(self.horizontalSpacer_15)
self.gridLayout.addLayout(self.verticalLayout_3, 1, 2, 1, 1)
self.retranslateUi(PropertyLegend)
QMetaObject.connectSlotsByName(PropertyLegend)
# setupUi
def retranslateUi(self, PropertyLegend):
PropertyLegend.setProperty("comment", QCoreApplication.translate("PropertyLegend", u"\n"
" Copyright 2017 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
self.propertyLegendLabelNoValue.setText(QCoreApplication.translate("PropertyLegend", u"No Value", None))
self.propertyLegendLabelDefault.setText(QCoreApplication.translate("PropertyLegend", u"Default", None))
self.propertyLegendLabelTimeSample.setText(QCoreApplication.translate("PropertyLegend", u"Time Samples (Interpolated) ", None))
self.propertyLegendLabelFallback.setText(QCoreApplication.translate("PropertyLegend", u"Fallback", None))
self.propertyLegendLabelCustom.setText(QCoreApplication.translate("PropertyLegend", u"Custom", None))
self.propertyLegendLabelValueClips.setText(QCoreApplication.translate("PropertyLegend", u"Value Clips (Interpolated)", None))
self.propertyLegendAttrPlainDesc.setText(QCoreApplication.translate("PropertyLegend", u"Attribute", None))
self.propertyLegendRelPlainDesc.setText(QCoreApplication.translate("PropertyLegend", u"Relationship", None))
self.propertyLegendCompDesc.setText(QCoreApplication.translate("PropertyLegend", u"Computed Value", None))
self.propertyLegendConnDesc.setText(QCoreApplication.translate("PropertyLegend", u"Connection", None))
self.propertyLegendTargetDesc.setText(QCoreApplication.translate("PropertyLegend", u"Target", None))
self.inheritedPropertyIcon.setText(QCoreApplication.translate("PropertyLegend", u"<small><i>(i)</i></small>", None))
self.inheritedPropertyText.setText(QCoreApplication.translate("PropertyLegend", u"Inherited Property", None))
self.propertyLegendAttrWithConnDesc.setText(QCoreApplication.translate("PropertyLegend", u"Attribute w/Connection(s)", None))
self.propertyLegendRelWithTargetDesc.setText(QCoreApplication.translate("PropertyLegend", u"Relationship w/Target(s)", None))
# retranslateUi
| 19,598 | Python | 47.154791 | 135 | 0.714155 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primTreeWidget.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from .constantGroup import ConstantGroup
from pxr import Sdf, Usd, UsdGeom
from .primViewItem import PrimViewItem
from .common import PrintWarning, Timer, UIPrimTreeColors, KeyboardShortcuts
def _GetPropertySpecInSessionLayer(usdAttribute):
propertyStack = usdAttribute.GetPropertyStack(Usd.TimeCode.Default())
if len(propertyStack) > 0:
stageSessionLayer = usdAttribute.GetStage().GetSessionLayer()
return stageSessionLayer.GetPropertyAtPath(usdAttribute.GetPath())
return None
# Function for getting the background color of the item for the delegates.
# Returns none if we only want the default paint method.
def _GetBackgroundColor(item, option):
mouseOver = option.state & QtWidgets.QStyle.State_MouseOver
selected = option.state & QtWidgets.QStyle.State_Selected
pressed = option.state & QtWidgets.QStyle.State_Sunken
background = None
if item.ancestorOfSelected:
background = UIPrimTreeColors.ANCESTOR_OF_SELECTED
if mouseOver:
background = UIPrimTreeColors.ANCESTOR_OF_SELECTED_HOVER
if selected:
background = UIPrimTreeColors.SELECTED
if mouseOver:
background = UIPrimTreeColors.SELECTED_HOVER
else:
if not selected and not pressed and mouseOver:
background = UIPrimTreeColors.UNSELECTED_HOVER
if selected:
background = UIPrimTreeColors.SELECTED
if mouseOver:
background = UIPrimTreeColors.SELECTED_HOVER
return background
class PrimViewColumnIndex(ConstantGroup):
NAME, TYPE, VIS, DRAWMODE = range(4)
class DrawModes(ConstantGroup):
DEFAULT = "default"
CARDS = "cards"
BOUNDS = "bounds"
ORIGIN = "origin"
class DrawModeComboBox(QtWidgets.QComboBox):
""" Specialize from QComboBox, so that we can send a signal when the pop-up
is hidden.
"""
signalPopupHidden = QtCore.Signal()
def __init__(self, parent=None):
QtWidgets.QComboBox.__init__(self, parent)
def hidePopup(self):
QtWidgets.QComboBox.hidePopup(self)
self.signalPopupHidden.emit()
class DrawModeWidget(QtWidgets.QWidget):
""" This widget contains a combobox for selecting the draw mode and a
clear ('x') button for clearing an authored drawMode override in the
session layer.
"""
def __init__(self, primViewItem, refreshFunc, printTiming=False,
parent=None):
QtWidgets.QWidget.__init__(self, parent)
self._primViewItem = primViewItem
self._layout = QtWidgets.QHBoxLayout()
self._layout.setSpacing(0)
self._layout.setContentsMargins(0,0,0,0)
self.setLayout(self._layout)
self._comboBox = DrawModeComboBox(self)
self._modelAPI = UsdGeom.ModelAPI(self._primViewItem.prim)
# Reducing the width further causes the pop-up dialog to be trimmed
# and option text to be pruned.
self._comboBox.setFixedWidth(100)
self._comboBox.addItem(DrawModes.DEFAULT)
self._comboBox.addItem(DrawModes.CARDS)
self._comboBox.addItem(DrawModes.BOUNDS)
self._comboBox.addItem(DrawModes.ORIGIN)
self._layout.addWidget(self._comboBox)
self._clearButton = QtWidgets.QToolButton(self)
self._clearButton.setText('X')
self._clearButton.setFixedSize(16, 16)
retainSizePolicy = self._clearButton.sizePolicy()
retainSizePolicy.setRetainSizeWhenHidden(True)
self._clearButton.setSizePolicy(retainSizePolicy)
self._layout.addWidget(self._clearButton)
self._currentDrawMode = None
self.RefreshDrawMode()
self._firstPaint = True
self._refreshFunc = refreshFunc
self._printTiming = printTiming
self._comboBox.signalPopupHidden.connect(self._PopupHidden)
self._comboBox.activated.connect(self._UpdateDrawMode)
self._clearButton.clicked.connect(self._ClearDrawMode)
def paintEvent(self, event):
# Virtual override of the paintEvent method on QWidget.
# Popup the combo box the first time the widget is drawn, since
# mouse-down in the column makes the widget appear.
#
# An alternative approach would be to set a timer in a constructor to
# pop open the combo box at the end of the event loop, but it causes a
# noticeable flicker in the UI.
if self._firstPaint:
self._comboBox.showPopup()
self._firstPaint = False
# Invoke paintEvent on super class to do the actual painting of the
# widget.
super(DrawModeWidget, self).paintEvent(event)
def _ShouldHideClearButton(self):
# Check if there's an authored value in the session layer.
drawModeAttr = self._modelAPI.GetModelDrawModeAttr()
if drawModeAttr:
sessionSpec = _GetPropertySpecInSessionLayer(drawModeAttr)
if sessionSpec and sessionSpec.HasDefaultValue():
return False
return True
def RefreshDrawMode(self, currentDrawMode=None):
self._currentDrawMode = currentDrawMode if currentDrawMode else \
self._modelAPI.ComputeModelDrawMode()
self._comboBox.setCurrentText(self._currentDrawMode)
clearButtonIsHidden = self._clearButton.isHidden()
if self._ShouldHideClearButton():
if not clearButtonIsHidden:
self._clearButton.hide()
self.update()
else:
if clearButtonIsHidden:
self._clearButton.show()
self.update()
def _UpdateDrawMode(self):
newDrawModeSelection = str(self._comboBox.currentText())
currentDrawMode = self._modelAPI.ComputeModelDrawMode()
if currentDrawMode != newDrawModeSelection:
with Timer() as t:
self._modelAPI.CreateModelDrawModeAttr().Set(
newDrawModeSelection)
self.RefreshDrawMode(currentDrawMode=newDrawModeSelection)
# We need to redraw the scene to pick up updates to draw mode.
self._refreshFunc(self._primViewItem)
if self._printTiming:
t.PrintTime("change model:drawMode on <%s> to %s" %
(self._modelAPI.GetPath(), newDrawModeSelection))
self._CloseEditorIfNoEdit()
def _ClearDrawMode(self):
with Timer() as t:
drawModeAttr = self._modelAPI.GetModelDrawModeAttr()
if drawModeAttr:
sessionSpec = _GetPropertySpecInSessionLayer(drawModeAttr)
if sessionSpec:
self._primViewItem.drawModeWidget = None
self._primViewItem.treeWidget().closePersistentEditor(
self._primViewItem, PrimViewColumnIndex.DRAWMODE)
sessionSpec.ClearDefaultValue()
sessionSpec.layer.ScheduleRemoveIfInert(sessionSpec)
self._refreshFunc(self._primViewItem)
else:
PrintWarning(self._modelAPI.GetPath(), "Failed to get "
"session layer spec for the model:drawMode attribute")
return
else:
PrintWarning(self._modelAPI.GetPath(), "Failed to get "
"model:drawMode attribute")
return
if self._printTiming:
t.PrintTime("clear model:drawMode on <%s> to %s" %
(self._modelAPI.GetPath(),
self._comboBox.currentText()))
def _CloseEditorIfNoEdit(self):
# If the clear button isn't present, then there's no edit.
if self._clearButton.isHidden():
self._primViewItem.drawModeWidget = None
self._primViewItem.treeWidget().closePersistentEditor(
self._primViewItem, PrimViewColumnIndex.DRAWMODE)
def _PopupHidden(self):
# Schedule closing the editor if no edit was made.
QtCore.QTimer.singleShot(0, self._CloseEditorIfNoEdit)
class DrawModeItemDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, printTiming, parent=None):
QtWidgets.QStyledItemDelegate.__init__(self, parent=parent)
self._treeWidget = parent
self._printTiming = printTiming
# We need to override paint in this delegate as well so that the
# Draw Mode column will match with the behavior of the other
# items in the treeview.
def paint(self, painter, option, index):
primViewItem = self._treeWidget.itemFromIndex(index)
background = _GetBackgroundColor(primViewItem, option)
if background:
painter.fillRect(option.rect, background)
super(DrawModeItemDelegate, self).paint(painter, option, index)
def createEditor(self, parent, option, index):
primViewItem = self._treeWidget.itemFromIndex(index)
if not primViewItem.supportsDrawMode:
return None
drawModeWidget = DrawModeWidget(primViewItem,
refreshFunc=self._treeWidget.UpdatePrimViewDrawMode,
printTiming=self._printTiming,
parent=parent)
# Store a copy of the widget in the primViewItem, for use when
# propagating changes to draw mode down a prim hierarchy.
primViewItem.drawModeWidget = drawModeWidget
return drawModeWidget
class SelectedAncestorItemDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, parent=None):
QtWidgets.QStyledItemDelegate.__init__(self, parent=parent)
self._treeWidget = parent
# In order to highlight the ancestors of selected prims, we require
# a new delegate to be created to override the paint function.
# Because the stylesheet will override styling when items are hovered
# over, the hovering styling logic is moved to this delegate, and
# primTreeWidget is excluded from the selectors for hovering
# in the stylesheet.
def paint(self, painter, option, index):
primViewItem = self._treeWidget.itemFromIndex(index)
originalPosition = option.rect.left()
offsetPosition = self._treeWidget.header().offset()
# In order to fill in the entire cell for Prim Name, we must update the
# dimensions of the rectangle painted. If the column is for Prim Name,
# we set the left side of the rectangle to be equal to the offset of the
# tree widget's header.
background = _GetBackgroundColor(primViewItem, option)
if primViewItem.ancestorOfSelected:
if index.column() == PrimViewColumnIndex.NAME:
option.rect.setLeft(offsetPosition)
if background:
painter.fillRect(option.rect, background)
# resetting the dimensions of the rectangle so that we paint the correct
# content in the cells on top of the colors we previously painted.
option.rect.setLeft(originalPosition)
super(SelectedAncestorItemDelegate, self).paint(painter, option, index)
class PrimItemSelectionModel(QtCore.QItemSelectionModel):
"""Standard QItemSelectionModel does not allow one to have full-item
selection while exlcuding some columns in the view from activating
selection. Since that's exactly the behavior we want, we derive our
own class that we can force to ignore selection requests except when we
really want it to."""
def __init__(self, model):
super(PrimItemSelectionModel, self).__init__(model)
self._processSelections = True
@property
def processSelections(self):
"""If True, calls to clear(), reset(), and select() will function
as normal. If False, such calls will be ignored."""
return self._processSelections
@processSelections.setter
def processSelections(self, doProcess):
self._processSelections = doProcess
def clear(self):
if self.processSelections:
super(PrimItemSelectionModel, self).clear()
def reset(self):
if self.processSelections:
super(PrimItemSelectionModel, self).reset()
def select(self, indexOrSelection, command):
if self.processSelections:
super(PrimItemSelectionModel, self).select(indexOrSelection, command)
class SelectionEnabler(object):
def __init__(self, selectionModel):
self._selectionModel = selectionModel
self._selectionWasEnabled = False
def __enter__(self):
self._selectionWasEnabled = self._selectionModel.processSelections
self._selectionModel.processSelections = True
return self
def __exit__(self, *args):
self._selectionModel.processSelections = self._selectionWasEnabled
# This class extends QTreeWidget and is used to draw the prim tree view in
# usdview.
# More of the prim browser specific behavior needs to be migrated from
# appController into this class.
class PrimTreeWidget(QtWidgets.QTreeWidget):
def __init__(self, parent):
super(PrimTreeWidget, self).__init__(parent=parent)
self._appController = None
self._selectionModel = PrimItemSelectionModel(self.model())
self.setSelectionModel(self._selectionModel)
# The list of ancestors of currently selected items
self._ancestorsOfSelected = []
def InitControllers(self, appController):
self._appController = appController
selectedAncestorItemDelegate = SelectedAncestorItemDelegate(parent=self)
self.setItemDelegate(selectedAncestorItemDelegate)
drawModeItemDelegate = DrawModeItemDelegate(appController._printTiming,
parent=self)
self.setItemDelegateForColumn(PrimViewColumnIndex.DRAWMODE,
drawModeItemDelegate)
def ShowDrawModeWidgetForItem(self, primViewItem):
self.openPersistentEditor(primViewItem, PrimViewColumnIndex.DRAWMODE)
def UpdatePrimViewDrawMode(self, rootItem=None):
"""Updates browser's "Draw Mode" columns."""
with Timer() as t:
self.setUpdatesEnabled(False)
# Update draw-model for the entire prim tree if the given
# rootItem is None.
if rootItem is None:
rootItem = self.invisibleRootItem().child(0)
if rootItem.childCount() == 0:
self._appController._populateChildren(rootItem)
rootsToProcess = [rootItem.child(i) for i in
range(rootItem.childCount())]
for item in rootsToProcess:
PrimViewItem.propagateDrawMode(item, self)
self.setUpdatesEnabled(True)
if self._appController._printTiming:
t.PrintTime("update draw mode column")
def ColumnPressCausesSelection(self, col):
"""If this method returns True for column `col`, then we want a
click in that column to cause the item to be selected."""
return col != PrimViewColumnIndex.VIS and col != PrimViewColumnIndex.DRAWMODE
def ExpandItemRecursively(self, item):
item = item.parent()
while item.parent():
if not item.isExpanded():
self.expandItem(item)
item = item.parent()
def FrameSelection(self):
if (self._appController):
selectedItems = [
self._appController._getItemAtPath(prim.GetPath())
for prim in self._appController._dataModel.selection.getPrims()]
for item in selectedItems:
self.ExpandItemRecursively(item)
self.scrollToItem(selectedItems[0])
# We set selectability based on the column we mousePress'd in, and then
# restore to true when leaving the widget, so that when we're not
# interacting with the browser, anyone can modify selection through the
# regular API's, which is important for the appController and other
# clients. If we retore it *before* leaving the widget, some internal
# QTreeWidget mechanism (an event filter?) _occasionally_ selects the item
# after a mouse release!
def mousePressEvent(self, ev):
item = self.itemAt(QtCore.QPoint(ev.x(), ev.y()))
if item:
col = self.columnAt(ev.x())
self._selectionModel.processSelections = self.ColumnPressCausesSelection(col)
super(PrimTreeWidget, self).mousePressEvent(ev)
def leaveEvent(self, ev):
super(PrimTreeWidget, self).leaveEvent(ev)
self._selectionModel.processSelections = True
# We override these selection and interaction-related API, and provide a
# batch wrapper for QTreeWidgetItem.setSelected in case, in the future,
# we have user plugins firing while we are still interacting with this
# widget, and they manipulate selection.
def clearSelection(self):
self._resetAncestorsOfSelected()
with SelectionEnabler(self._selectionModel):
super(PrimTreeWidget, self).clearSelection()
def reset(self):
self._resetAncestorsOfSelected()
with SelectionEnabler(self._selectionModel):
super(PrimTreeWidget, self).reset()
def selectAll(self):
self._resetAncestorsOfSelected()
with SelectionEnabler(self._selectionModel):
super(PrimTreeWidget, self).selectAll()
def keyPressEvent(self, ev):
with SelectionEnabler(self._selectionModel):
# Because setCurrentItem autoexpands the primview so that
# the current item is visible, we must set the current item
# only when we know it'll be needed for arrow navigation.
# We call this here before the selection data model clears
# the selection.
if ev.key() == QtCore.Qt.Key_Down \
or ev.key() == QtCore.Qt.Key_Up \
or ev.key() == QtCore.Qt.Key_Right \
or ev.key() == QtCore.Qt.Key_Left:
currentPrim = self._appController._dataModel.selection.getFocusPrim()
currentItem = self._appController._getItemAtPath(currentPrim.GetPath())
self.setCurrentItem(currentItem, 0, QtCore.QItemSelectionModel.NoUpdate)
super(PrimTreeWidget, self).keyPressEvent(ev)
# Handling the F hotkey comes after the super class's event handling,
# since the default behavior in the super class's keyPressEvent function
# is to set the current item to the first item found that alphabetically
# matches the key entered. Since we want to override this behavior for
# the F hotkey, we must handle it after the super class's keyPressEvent.
if ev.key() == KeyboardShortcuts.FramingKey:
self.FrameSelection()
def keyReleaseEvent(self, ev):
with SelectionEnabler(self._selectionModel):
super(PrimTreeWidget, self).keyReleaseEvent(ev)
def updateSelection(self, added, removed):
"""Mutate the widget's selected items, selecting items in `added`
and deselecting items in `removed`. Prefer this method for client
use over calling setSelected directly on PrimViewItems."""
with SelectionEnabler(self._selectionModel):
for item in added:
item.setSelected(True)
for item in removed:
item.setSelected(False)
self._refreshAncestorsOfSelected()
# This is a big hammer... if we instead built up a list of the
# ModelIndices of all the changed ancestors, we could instead make
# our selectionModel emit selectionChanged for just those items,
# instead. Does not currently seem to be impacting interactivity.
QtWidgets.QWidget.update(self)
def _resetAncestorsOfSelected(self):
for item in self._ancestorsOfSelected:
item.ancestorOfSelected = False
self._ancestorsOfSelected = []
# Refresh the list of ancestors of selected prims
def _refreshAncestorsOfSelected(self):
selectedItems = [
self._appController._getItemAtPath(prim.GetPath())
for prim in self._appController._dataModel.selection.getPrims()]
self._resetAncestorsOfSelected()
# Add all ancestor of the prim associated with the item
# to _ancestorsOfSelected, and mark them as selected ancestors
for item in selectedItems:
while item.parent():
item.parent().ancestorOfSelected = True
self._ancestorsOfSelected.append(item.parent())
item = item.parent()
| 21,809 | Python | 41.597656 | 89 | 0.661332 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/layerStackContextMenu.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from .usdviewContextMenuItem import UsdviewContextMenuItem
import os, subprocess, sys
from pxr import Ar
#
# Specialized context menu for running commands in the layer stack view.
#
class LayerStackContextMenu(QtWidgets.QMenu):
def __init__(self, parent, item):
QtWidgets.QMenu.__init__(self, parent)
self._menuItems = _GetContextMenuItems(item)
for menuItem in self._menuItems:
if menuItem.isValid():
# create menu actions
action = self.addAction(menuItem.GetText(), menuItem.RunCommand)
# set enabled
if not menuItem.IsEnabled():
action.setEnabled(False)
def _GetContextMenuItems(item):
return [OpenLayerMenuItem(item),
UsdviewLayerMenuItem(item),
CopyLayerPathMenuItem(item),
CopyLayerIdentifierMenuItem(item),
CopyPathMenuItem(item)]
#
# The base class for layer stack context menu items.
#
class LayerStackContextMenuItem(UsdviewContextMenuItem):
def __init__(self, item):
self._item = item
def IsEnabled(self):
return True
def GetText(self):
return ""
def RunCommand(self):
pass
#
# Opens the layer using usdedit.
#
class OpenLayerMenuItem(LayerStackContextMenuItem):
# XXX: Note that this logic is duplicated from usddiff
# see bug 150247 for centralizing this API.
def _FindUsdEdit(self):
import platform
from distutils.spawn import find_executable
usdedit = find_executable('usdedit')
if not usdedit:
usdedit = find_executable('usdedit', path=os.path.abspath(os.path.dirname(sys.argv[0])))
if not usdedit and (platform.system() == 'Windows'):
for path in os.environ['PATH'].split(os.pathsep):
base = os.path.join(path, 'usdedit')
for ext in ['.cmd', '']:
if os.access(base + ext, os.X_OK):
usdedit = base + ext
return usdedit
def GetText(self):
from .common import PrettyFormatSize
fileSize = 0
if (hasattr(self._item, "layerPath")
and os.path.isfile(getattr(self._item, "layerPath"))):
fileSize = os.path.getsize(getattr(self._item, "layerPath"))
if fileSize:
return "Open Layer In Editor (%s)" % PrettyFormatSize(fileSize)
else:
return "Open Layer In Editor"
def IsEnabled(self):
return hasattr(self._item, "layerPath")
def RunCommand(self):
if not self._item:
return
# Get layer path from item
layerPath = getattr(self._item, "layerPath")
if not layerPath:
print("Error: Could not find layer file.")
return
if Ar.IsPackageRelativePath(layerPath):
layerName = os.path.basename(
Ar.SplitPackageRelativePathInner(layerPath)[1])
else:
layerName = os.path.basename(layerPath)
layerName += ".tmp"
usdeditExe = self._FindUsdEdit()
if not usdeditExe:
print("Warning: Could not find 'usdedit', expected it to be in PATH.")
return
print("Opening file: %s" % layerPath)
command = [usdeditExe,'-n',layerPath,'-p',layerName]
subprocess.Popen(command, close_fds=True)
#
# Opens the layer using usdview.
#
class UsdviewLayerMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Open Layer In usdview"
def IsEnabled(self):
return hasattr(self._item, "layerPath")
def RunCommand(self):
if not self._item:
return
# Get layer path from item
layerPath = getattr(self._item, "layerPath")
if not layerPath:
return
print("Spawning usdview %s" % layerPath)
os.system("usdview %s &" % layerPath)
#
# Copy the layer path to clipboard
#
class CopyLayerPathMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Copy Layer Path"
def RunCommand(self):
if not self._item:
return
layerPath = getattr(self._item, "layerPath")
if not layerPath:
return
cb = QtWidgets.QApplication.clipboard()
cb.setText(layerPath, QtGui.QClipboard.Selection )
cb.setText(layerPath, QtGui.QClipboard.Clipboard )
#
# Copy the layer identifier to clipboard
#
class CopyLayerIdentifierMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Copy Layer Identifier"
def RunCommand(self):
if not self._item:
return
identifier = getattr(self._item, "identifier")
if not identifier:
return
cb = QtWidgets.QApplication.clipboard()
cb.setText(identifier, QtGui.QClipboard.Selection )
cb.setText(identifier, QtGui.QClipboard.Clipboard )
#
# Copy the prim path to clipboard, if there is one
#
class CopyPathMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Copy Object Path"
def RunCommand(self):
if not self._item:
return
path = getattr(self._item, "path")
if not path:
return
path = str(path)
cb = QtWidgets.QApplication.clipboard()
cb.setText(path, QtGui.QClipboard.Selection )
cb.setText(path, QtGui.QClipboard.Clipboard )
def IsEnabled(self):
return hasattr(self._item, "path")
| 6,596 | Python | 28.986364 | 100 | 0.637811 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/attributeValueEditor.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from pxr import Usd
from .qt import QtCore, QtWidgets
from .attributeValueEditorUI import Ui_AttributeValueEditor
from .common import GetPropertyColor, UIPropertyValueSourceColors
from .scalarTypes import ToString
# This is the widget that appears when selecting an attribute and
# opening the "Value" tab.
class AttributeValueEditor(QtWidgets.QWidget):
editComplete = QtCore.Signal('QString')
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
self._ui = Ui_AttributeValueEditor()
self._ui.setupUi(self)
self._defaultView = self._ui.valueViewer
from .arrayAttributeView import ArrayAttributeView
self._extraAttrViews = [
ArrayAttributeView(self),
]
for attrView in self._extraAttrViews:
self._ui.stackedWidget.addWidget(attrView)
self.clear()
def setAppController(self, appController):
# pass the appController instance from which to retrieve
# variable data.
self._appController = appController
def populate(self, primPath, propName):
# called when the selected attribute has changed
self._primPath = primPath
try:
self._attribute = self._appController._propertiesDict[propName]
except KeyError:
self._attribute = None
self._isSet = True # an attribute is selected
self.refresh() # load the value at the current frame
def _FindView(self, attr):
# Early-out for CustomAttributes and Relationships
if not isinstance(attr, Usd.Attribute):
return None
for attrView in self._extraAttrViews:
if attrView.CanView(attr):
return attrView
return None
def refresh(self):
# usually called upon frame change or selected attribute change
if not self._isSet:
return
# attribute connections and relationship targets have no value to display
# in the value viewer.
if self._attribute is None:
return
# If the current attribute doesn't belong to the current prim, don't
# display its value.
if self._attribute.GetPrimPath() != self._primPath:
self._ui.valueViewer.setText("")
return
frame = self._appController._dataModel.currentFrame
# get the value of the attribute
if isinstance(self._attribute, Usd.Relationship):
self._val = self._attribute.GetTargets()
else: # Usd.Attribute or CustomAttribute
self._val = self._attribute.Get(frame)
whichView = self._FindView(self._attribute)
if whichView:
self._ui.stackedWidget.setCurrentWidget(whichView)
whichView.SetAttribute(self._attribute, frame)
else:
self._ui.stackedWidget.setCurrentWidget(self._defaultView)
txtColor = GetPropertyColor(self._attribute, frame)
# set text and color in the value viewer
self._ui.valueViewer.setTextColor(txtColor)
if isinstance(self._attribute, Usd.Relationship):
typeName = None
else:
typeName = self._attribute.GetTypeName()
rowText = ToString(self._val, typeName)
self._ui.valueViewer.setText(rowText)
def clear(self):
# set the value editor to 'no attribute selected' mode
self._isSet = False
self._ui.valueViewer.setText("")
# make sure we're showing the default view
self._ui.stackedWidget.setCurrentWidget(self._defaultView)
| 4,690 | Python | 35.084615 | 81 | 0.665672 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/frameSlider.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtWidgets, QtGui
class FrameSlider(QtWidgets.QSlider):
"""Custom QSlider class to allow scrubbing on left-click."""
PAUSE_TIMER_INTERVAL = 500
def __init__(self, parent=None):
super(FrameSlider, self).__init__(parent=parent)
# Create a mouse pause timer to trigger an update if the slider
# scrubbing pauses.
self._mousePauseTimer = QtCore.QTimer(self)
self._mousePauseTimer.setInterval(self.PAUSE_TIMER_INTERVAL)
self._mousePauseTimer.timeout.connect(self.mousePaused)
def mousePaused(self):
"""Slot called when the slider scrubbing is paused."""
self._mousePauseTimer.stop()
self.valueChanged.emit(self.sliderPosition())
def mousePressEvent(self, event):
# This is a temporary solution that should revisited in future.
#
# The issue is that the current QStyle on the application
# only allows the slider position to be set on a MiddleButton
# MouseEvent.
#
# The correct solution is for us to create a QProxyStyle for the
# application so we can edit the value of the
# QStyle.SH_Slider_AbsoluteSetButtons property (to include
# LeftButton). Unfortunately QProxyStyle is not yet available
# in this version of PySide.
#
# Instead, we are forced to duplicate the MouseEvent as a
# MiddleButton event. This creates the exact behavior we
# want to see from the QSlider.
styleHint = QtWidgets.QStyle.SH_Slider_AbsoluteSetButtons
if self.style().styleHint(styleHint) == QtCore.Qt.MiddleButton:
if event.button() == QtCore.Qt.LeftButton:
event = QtGui.QMouseEvent(
event.type(),
event.pos(),
QtCore.Qt.MiddleButton,
QtCore.Qt.MiddleButton,
event.modifiers()
)
super(FrameSlider, self).mousePressEvent(event)
def mouseMoveEvent(self, event):
super(FrameSlider, self).mouseMoveEvent(event)
# Start the pause timer if tracking is disabled.
if not self.hasTracking():
self._mousePauseTimer.start()
def mouseReleaseEvent(self, event):
# Stop the pause timer.
self._mousePauseTimer.stop()
super(FrameSlider, self).mouseReleaseEvent(event)
| 3,471 | Python | 39.372093 | 74 | 0.674157 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/viewSettingsDataModel.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore
from pxr import UsdGeom, Sdf
from pxr.UsdAppUtils.complexityArgs import RefinementComplexities
from .common import (RenderModes, ColorCorrectionModes, PickModes,
SelectionHighlightModes, CameraMaskModes,
PrintWarning)
from . import settings2
from .settings2 import StateSource
from .constantGroup import ConstantGroup
from .freeCamera import FreeCamera
from .common import ClearColors, HighlightColors
# Map of clear color names to rgba color tuples.
_CLEAR_COLORS_DICT = {
ClearColors.BLACK: (0.0, 0.0, 0.0, 1.0),
ClearColors.DARK_GREY: (0.3, 0.3, 0.3, 1.0),
ClearColors.LIGHT_GREY: (0.7, 0.7, 0.7, 1.0),
ClearColors.WHITE: (1.0, 1.0, 1.0, 1.0)}
# Map of highlight color names to rgba color tuples.
_HIGHLIGHT_COLORS_DICT = {
HighlightColors.WHITE: (1.0, 1.0, 1.0, 0.5),
HighlightColors.YELLOW: (1.0, 1.0, 0.0, 0.5),
HighlightColors.CYAN: (0.0, 1.0, 1.0, 0.5)}
# Default values for default material components.
DEFAULT_AMBIENT = 0.2
DEFAULT_SPECULAR = 0.1
def visibleViewSetting(f):
def wrapper(self, *args, **kwargs):
f(self, *args, **kwargs)
# If f raises an exception, the signal is not emitted.
self.signalVisibleSettingChanged.emit()
self.signalSettingChanged.emit()
return wrapper
def invisibleViewSetting(f):
def wrapper(self, *args, **kwargs):
f(self, *args, **kwargs)
# If f raises an exception, the signal is not emitted.
self.signalSettingChanged.emit()
return wrapper
class ViewSettingsDataModel(QtCore.QObject, StateSource):
"""Data model containing settings related to the rendered view of a USD
file.
"""
# emitted when any view setting changes
signalSettingChanged = QtCore.Signal()
# emitted when any view setting which may affect the rendered image changes
signalVisibleSettingChanged = QtCore.Signal()
# emitted when any aspect of the defaultMaterial changes
signalDefaultMaterialChanged = QtCore.Signal()
# emitted when any setting affecting the GUI style changes
signalStyleSettingsChanged = QtCore.Signal()
def __init__(self, rootDataModel, parent):
QtCore.QObject.__init__(self)
StateSource.__init__(self, parent, "model")
self._rootDataModel = rootDataModel
self._cameraMaskColor = tuple(self.stateProperty("cameraMaskColor", default=[0.1, 0.1, 0.1, 1.0]))
self._cameraReticlesColor = tuple(self.stateProperty("cameraReticlesColor", default=[0.0, 0.7, 1.0, 1.0]))
self._defaultMaterialAmbient = self.stateProperty("defaultMaterialAmbient", default=DEFAULT_AMBIENT)
self._defaultMaterialSpecular = self.stateProperty("defaultMaterialSpecular", default=DEFAULT_SPECULAR)
self._redrawOnScrub = self.stateProperty("redrawOnScrub", default=True)
self._renderMode = self.stateProperty("renderMode", default=RenderModes.SMOOTH_SHADED)
self._freeCameraFOV = self.stateProperty("freeCameraFOV", default=60.0)
self._colorCorrectionMode = self.stateProperty("colorCorrectionMode", default=ColorCorrectionModes.SRGB)
self._pickMode = self.stateProperty("pickMode", default=PickModes.PRIMS)
# We need to store the trinary selHighlightMode state here,
# because the stageView only deals in True/False (because it
# cannot know anything about playback state).
self._selHighlightMode = self.stateProperty("selectionHighlightMode", default=SelectionHighlightModes.ONLY_WHEN_PAUSED)
# We store the highlightColorName so that we can compare state during
# initialization without inverting the name->value logic
self._highlightColorName = self.stateProperty("highlightColor", default="Yellow")
self._ambientLightOnly = self.stateProperty("cameraLightEnabled", default=True)
self._domeLightEnabled = self.stateProperty("domeLightEnabled", default=False)
self._clearColorText = self.stateProperty("backgroundColor", default="Grey (Dark)")
self._autoComputeClippingPlanes = self.stateProperty("autoComputeClippingPlanes", default=False)
self._showBBoxPlayback = self.stateProperty("showBBoxesDuringPlayback", default=False)
self._showBBoxes = self.stateProperty("showBBoxes", default=True)
self._showAABBox = self.stateProperty("showAABBox", default=True)
self._showOBBox = self.stateProperty("showOBBox", default=True)
self._displayGuide = self.stateProperty("displayGuide", default=False)
self._displayProxy = self.stateProperty("displayProxy", default=True)
self._displayRender = self.stateProperty("displayRender", default=False)
self._displayPrimId = self.stateProperty("displayPrimId", default=False)
self._enableSceneMaterials = self.stateProperty("enableSceneMaterials", default=True)
self._cullBackfaces = self.stateProperty("cullBackfaces", default=False)
self._showInactivePrims = self.stateProperty("showInactivePrims", default=True)
self._showAllMasterPrims = self.stateProperty("showAllMasterPrims", default=False)
self._showUndefinedPrims = self.stateProperty("showUndefinedPrims", default=False)
self._showAbstractPrims = self.stateProperty("showAbstractPrims", default=False)
self._rolloverPrimInfo = self.stateProperty("rolloverPrimInfo", default=False)
self._displayCameraOracles = self.stateProperty("cameraOracles", default=False)
self._cameraMaskMode = self.stateProperty("cameraMaskMode", default=CameraMaskModes.NONE)
self._showMask_Outline = self.stateProperty("cameraMaskOutline", default=False)
self._showReticles_Inside = self.stateProperty("cameraReticlesInside", default=False)
self._showReticles_Outside = self.stateProperty("cameraReticlesOutside", default=False)
self._showHUD = self.stateProperty("showHUD", default=True)
self._showHUD_Info = self.stateProperty("showHUDInfo", default=False)
# XXX Until we can make the "Subtree Info" stats-gathering faster
# we do not want the setting to persist from session to session.
self._showHUD_Info = False
self._showHUD_Complexity = self.stateProperty("showHUDComplexity", default=True)
self._showHUD_Performance = self.stateProperty("showHUDPerformance", default=True)
self._showHUD_GPUstats = self.stateProperty("showHUDGPUStats", default=False)
self._complexity = RefinementComplexities.LOW
self._freeCamera = None
self._cameraPath = None
self._fontSize = self.stateProperty("fontSize", default=10)
def onSaveState(self, state):
state["cameraMaskColor"] = list(self._cameraMaskColor)
state["cameraReticlesColor"] = list(self._cameraReticlesColor)
state["defaultMaterialAmbient"] = self._defaultMaterialAmbient
state["defaultMaterialSpecular"] = self._defaultMaterialSpecular
state["redrawOnScrub"] = self._redrawOnScrub
state["renderMode"] = self._renderMode
state["freeCameraFOV"] = self._freeCameraFOV
state["colorCorrectionMode"] = self._colorCorrectionMode
state["pickMode"] = self._pickMode
state["selectionHighlightMode"] = self._selHighlightMode
state["highlightColor"] = self._highlightColorName
state["cameraLightEnabled"] = self._ambientLightOnly
state["domeLightEnabled"] = self._domeLightEnabled
state["backgroundColor"] = self._clearColorText
state["autoComputeClippingPlanes"] = self._autoComputeClippingPlanes
state["showBBoxesDuringPlayback"] = self._showBBoxPlayback
state["showBBoxes"] = self._showBBoxes
state["showAABBox"] = self._showAABBox
state["showOBBox"] = self._showOBBox
state["displayGuide"] = self._displayGuide
state["displayProxy"] = self._displayProxy
state["displayRender"] = self._displayRender
state["displayPrimId"] = self._displayPrimId
state["enableSceneMaterials"] = self._enableSceneMaterials
state["cullBackfaces"] = self._cullBackfaces
state["showInactivePrims"] = self._showInactivePrims
state["showAllMasterPrims"] = self._showAllMasterPrims
state["showUndefinedPrims"] = self._showUndefinedPrims
state["showAbstractPrims"] = self._showAbstractPrims
state["rolloverPrimInfo"] = self._rolloverPrimInfo
state["cameraOracles"] = self._displayCameraOracles
state["cameraMaskMode"] = self._cameraMaskMode
state["cameraMaskOutline"] = self._showMask_Outline
state["cameraReticlesInside"] = self._showReticles_Inside
state["cameraReticlesOutside"] = self._showReticles_Outside
state["showHUD"] = self._showHUD
state["showHUDInfo"] = self._showHUD_Info
state["showHUDComplexity"] = self._showHUD_Complexity
state["showHUDPerformance"] = self._showHUD_Performance
state["showHUDGPUStats"] = self._showHUD_GPUstats
state["fontSize"] = self._fontSize
@property
def cameraMaskColor(self):
return self._cameraMaskColor
@cameraMaskColor.setter
@visibleViewSetting
def cameraMaskColor(self, color):
self._cameraMaskColor = color
@property
def cameraReticlesColor(self):
return self._cameraReticlesColor
@cameraReticlesColor.setter
@visibleViewSetting
def cameraReticlesColor(self, color):
self._cameraReticlesColor = color
@property
def defaultMaterialAmbient(self):
return self._defaultMaterialAmbient
@defaultMaterialAmbient.setter
@visibleViewSetting
def defaultMaterialAmbient(self, value):
if value != self._defaultMaterialAmbient:
self._defaultMaterialAmbient = value
self.signalDefaultMaterialChanged.emit()
@property
def defaultMaterialSpecular(self):
return self._defaultMaterialSpecular
@defaultMaterialSpecular.setter
@visibleViewSetting
def defaultMaterialSpecular(self, value):
if value != self._defaultMaterialSpecular:
self._defaultMaterialSpecular = value
self.signalDefaultMaterialChanged.emit()
@visibleViewSetting
def setDefaultMaterial(self, ambient, specular):
if (ambient != self._defaultMaterialAmbient
or specular != self._defaultMaterialSpecular):
self._defaultMaterialAmbient = ambient
self._defaultMaterialSpecular = specular
self.signalDefaultMaterialChanged.emit()
def resetDefaultMaterial(self):
self.setDefaultMaterial(DEFAULT_AMBIENT, DEFAULT_SPECULAR)
@property
def complexity(self):
return self._complexity
@complexity.setter
@visibleViewSetting
def complexity(self, value):
if value not in RefinementComplexities.ordered():
raise ValueError("Expected Complexity, got: '{}'.".format(value))
self._complexity = value
@property
def renderMode(self):
return self._renderMode
@renderMode.setter
@visibleViewSetting
def renderMode(self, value):
self._renderMode = value
@property
def freeCameraFOV(self):
return self._freeCameraFOV
@freeCameraFOV.setter
@visibleViewSetting
def freeCameraFOV(self, value):
if self._freeCamera:
# Setting the freeCamera's fov will trigger our own update
self._freeCamera.fov = value
else:
self._freeCameraFOV = value
@visibleViewSetting
def _updateFOV(self):
if self._freeCamera:
self._freeCameraFOV = self.freeCamera.fov
@property
def colorCorrectionMode(self):
return self._colorCorrectionMode
@colorCorrectionMode.setter
@visibleViewSetting
def colorCorrectionMode(self, value):
self._colorCorrectionMode = value
@property
def pickMode(self):
return self._pickMode
@pickMode.setter
@invisibleViewSetting
def pickMode(self, value):
self._pickMode = value
@property
def showAABBox(self):
return self._showAABBox
@showAABBox.setter
@visibleViewSetting
def showAABBox(self, value):
self._showAABBox = value
@property
def showOBBox(self):
return self._showOBBox
@showOBBox.setter
@visibleViewSetting
def showOBBox(self, value):
self._showOBBox = value
@property
def showBBoxes(self):
return self._showBBoxes
@showBBoxes.setter
@visibleViewSetting
def showBBoxes(self, value):
self._showBBoxes = value
@property
def autoComputeClippingPlanes(self):
return self._autoComputeClippingPlanes
@autoComputeClippingPlanes.setter
@visibleViewSetting
def autoComputeClippingPlanes(self, value):
self._autoComputeClippingPlanes = value
@property
def showBBoxPlayback(self):
return self._showBBoxPlayback
@showBBoxPlayback.setter
@visibleViewSetting
def showBBoxPlayback(self, value):
self._showBBoxPlayback = value
@property
def displayGuide(self):
return self._displayGuide
@displayGuide.setter
@visibleViewSetting
def displayGuide(self, value):
self._displayGuide = value
@property
def displayProxy(self):
return self._displayProxy
@displayProxy.setter
@visibleViewSetting
def displayProxy(self, value):
self._displayProxy = value
@property
def displayRender(self):
return self._displayRender
@displayRender.setter
@visibleViewSetting
def displayRender(self, value):
self._displayRender = value
@property
def displayCameraOracles(self):
return self._displayCameraOracles
@displayCameraOracles.setter
@visibleViewSetting
def displayCameraOracles(self, value):
self._displayCameraOracles = value
@property
def displayPrimId(self):
return self._displayPrimId
@displayPrimId.setter
@visibleViewSetting
def displayPrimId(self, value):
self._displayPrimId = value
@property
def enableSceneMaterials(self):
return self._enableSceneMaterials
@enableSceneMaterials.setter
@visibleViewSetting
def enableSceneMaterials(self, value):
self._enableSceneMaterials = value
@property
def cullBackfaces(self):
return self._cullBackfaces
@cullBackfaces.setter
@visibleViewSetting
def cullBackfaces(self, value):
self._cullBackfaces = value
@property
def showInactivePrims(self):
return self._showInactivePrims
@showInactivePrims.setter
@invisibleViewSetting
def showInactivePrims(self, value):
self._showInactivePrims = value
@property
def showAllMasterPrims(self):
return self._showAllMasterPrims
@showAllMasterPrims.setter
@invisibleViewSetting
def showAllMasterPrims(self, value):
self._showAllMasterPrims = value
@property
def showUndefinedPrims(self):
return self._showUndefinedPrims
@showUndefinedPrims.setter
@invisibleViewSetting
def showUndefinedPrims(self, value):
self._showUndefinedPrims = value
@property
def showAbstractPrims(self):
return self._showAbstractPrims
@showAbstractPrims.setter
@invisibleViewSetting
def showAbstractPrims(self, value):
self._showAbstractPrims = value
@property
def rolloverPrimInfo(self):
return self._rolloverPrimInfo
@rolloverPrimInfo.setter
@invisibleViewSetting
def rolloverPrimInfo(self, value):
self._rolloverPrimInfo = value
@property
def cameraMaskMode(self):
return self._cameraMaskMode
@cameraMaskMode.setter
@visibleViewSetting
def cameraMaskMode(self, value):
self._cameraMaskMode = value
@property
def showMask(self):
return self._cameraMaskMode in (CameraMaskModes.FULL, CameraMaskModes.PARTIAL)
@property
def showMask_Opaque(self):
return self._cameraMaskMode == CameraMaskModes.FULL
@property
def showMask_Outline(self):
return self._showMask_Outline
@showMask_Outline.setter
@visibleViewSetting
def showMask_Outline(self, value):
self._showMask_Outline = value
@property
def showReticles_Inside(self):
return self._showReticles_Inside
@showReticles_Inside.setter
@visibleViewSetting
def showReticles_Inside(self, value):
self._showReticles_Inside = value
@property
def showReticles_Outside(self):
return self._showReticles_Outside
@showReticles_Outside.setter
@visibleViewSetting
def showReticles_Outside(self, value):
self._showReticles_Outside = value
@property
def showHUD(self):
return self._showHUD
@showHUD.setter
@visibleViewSetting
def showHUD(self, value):
self._showHUD = value
@property
def showHUD_Info(self):
return self._showHUD_Info
@showHUD_Info.setter
@visibleViewSetting
def showHUD_Info(self, value):
self._showHUD_Info = value
@property
def showHUD_Complexity(self):
return self._showHUD_Complexity
@showHUD_Complexity.setter
@visibleViewSetting
def showHUD_Complexity(self, value):
self._showHUD_Complexity = value
@property
def showHUD_Performance(self):
return self._showHUD_Performance
@showHUD_Performance.setter
@visibleViewSetting
def showHUD_Performance(self, value):
self._showHUD_Performance = value
@property
def showHUD_GPUstats(self):
return self._showHUD_GPUstats
@showHUD_GPUstats.setter
@visibleViewSetting
def showHUD_GPUstats(self, value):
self._showHUD_GPUstats = value
@property
def ambientLightOnly(self):
return self._ambientLightOnly
@ambientLightOnly.setter
@visibleViewSetting
def ambientLightOnly(self, value):
self._ambientLightOnly = value
@property
def domeLightEnabled(self):
return self._domeLightEnabled
@domeLightEnabled.setter
@visibleViewSetting
def domeLightEnabled(self, value):
self._domeLightEnabled = value
@property
def clearColorText(self):
return self._clearColorText
@clearColorText.setter
@visibleViewSetting
def clearColorText(self, value):
if value not in ClearColors:
raise ValueError("Unknown clear color: '{}'".format(value))
self._clearColorText = value
@property
def clearColor(self):
return _CLEAR_COLORS_DICT[self._clearColorText]
@property
def highlightColorName(self):
return self._highlightColorName
@highlightColorName.setter
@visibleViewSetting
def highlightColorName(self, value):
if value not in HighlightColors:
raise ValueError("Unknown highlight color: '{}'".format(value))
self._highlightColorName = value
@property
def highlightColor(self):
return _HIGHLIGHT_COLORS_DICT[self._highlightColorName]
@property
def selHighlightMode(self):
return self._selHighlightMode
@selHighlightMode.setter
@visibleViewSetting
def selHighlightMode(self, value):
if value not in SelectionHighlightModes:
raise ValueError("Unknown highlight mode: '{}'".format(value))
self._selHighlightMode = value
@property
def redrawOnScrub(self):
return self._redrawOnScrub
@redrawOnScrub.setter
@visibleViewSetting
def redrawOnScrub(self, value):
self._redrawOnScrub = value
@property
def freeCamera(self):
return self._freeCamera
@freeCamera.setter
@visibleViewSetting
def freeCamera(self, value):
# ViewSettingsDataModel does not guarantee it will hold a valid
# FreeCamera, but if one is set, we will keep the dataModel's stateful
# FOV ('freeCameraFOV') in sync with the FreeCamera
if not isinstance(value, FreeCamera) and value != None:
raise TypeError("Free camera must be a FreeCamera object.")
if self._freeCamera:
self._freeCamera.signalFrustumChanged.disconnect(self._updateFOV)
self._freeCamera = value
if self._freeCamera:
self._freeCamera.signalFrustumChanged.connect(self._updateFOV)
self._freeCameraFOV = self._freeCamera.fov
@property
def cameraPath(self):
return self._cameraPath
@cameraPath.setter
@visibleViewSetting
def cameraPath(self, value):
if ((not isinstance(value, Sdf.Path) or not value.IsPrimPath())
and value is not None):
raise TypeError("Expected prim path, got: {}".format(value))
self._cameraPath = value
@property
def cameraPrim(self):
if self.cameraPath is not None and self._rootDataModel.stage is not None:
return self._rootDataModel.stage.GetPrimAtPath(self.cameraPath)
else:
return None
@cameraPrim.setter
def cameraPrim(self, value):
if value is not None:
if value.IsA(UsdGeom.Camera):
self.cameraPath = value.GetPrimPath()
else:
PrintWarning("Incorrect Prim Type",
"Attempted to view the scene using the prim '%s', but "
"the prim is not a UsdGeom.Camera." % (value.GetName()))
else:
self.cameraPath = None
@property
def fontSize(self):
return self._fontSize
@fontSize.setter
@visibleViewSetting
def fontSize(self, value):
if value != self._fontSize:
self._fontSize = value
self.signalStyleSettingsChanged.emit()
| 22,972 | Python | 32.783823 | 127 | 0.687924 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/stageView.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
'''
Module that provides the StageView class.
'''
from __future__ import print_function
from math import tan, floor, ceil, radians as rad, isinf
import os, sys
from time import time
from .qt import QtCore, QtGui, QtWidgets, QtOpenGL
from pxr import Tf
from pxr import Gf
from pxr import Glf
from pxr import Sdf, Usd, UsdGeom
from pxr import UsdImagingGL
from pxr import CameraUtil
from .common import (RenderModes, ColorCorrectionModes, ShadedRenderModes, Timer,
ReportMetricSize, SelectionHighlightModes, DEBUG_CLIPPING)
from .rootDataModel import RootDataModel
from .selectionDataModel import ALL_INSTANCES, SelectionDataModel
from .viewSettingsDataModel import ViewSettingsDataModel
from .freeCamera import FreeCamera
# A viewport rectangle to be used for GL must be integer values.
# In order to loose the least amount of precision the viewport
# is centered and adjusted to initially contain entirely the
# given viewport.
# If it turns out that doing so gives more than a pixel width
# or height of error the viewport is instead inset.
# This does mean that the returned viewport may have a slightly
# different aspect ratio to the given viewport.
def ViewportMakeCenteredIntegral(viewport):
# The values are initially integral and containing the
# the given rect
left = int(floor(viewport[0]))
bottom = int(floor(viewport[1]))
right = int(ceil(viewport[0] + viewport[2]))
top = int(ceil(viewport[1] + viewport[3]))
width = right - left
height = top - bottom
# Compare the integral height to the original height
# and do a centered 1 pixel adjustment if more than
# a pixel off.
if (height - viewport[3]) > 1.0:
bottom += 1
height -= 2
# Compare the integral width to the original width
# and do a centered 1 pixel adjustment if more than
# a pixel off.
if (width - viewport[2]) > 1.0:
left += 1
width -= 2
return (left, bottom, width, height)
class GLSLProgram():
def __init__(self, VS3, FS3, VS2, FS2, uniformDict):
from OpenGL import GL
self._glMajorVersion = int(GL.glGetString(GL.GL_VERSION)[0])
self.program = GL.glCreateProgram()
vertexShader = GL.glCreateShader(GL.GL_VERTEX_SHADER)
fragmentShader = GL.glCreateShader(GL.GL_FRAGMENT_SHADER)
if (self._glMajorVersion >= 3):
vsSource = VS3
fsSource = FS3
else:
vsSource = VS2
fsSource = FS2
GL.glShaderSource(vertexShader, vsSource)
GL.glCompileShader(vertexShader)
GL.glShaderSource(fragmentShader, fsSource)
GL.glCompileShader(fragmentShader)
GL.glAttachShader(self.program, vertexShader)
GL.glAttachShader(self.program, fragmentShader)
GL.glLinkProgram(self.program)
if GL.glGetProgramiv(self.program, GL.GL_LINK_STATUS) == GL.GL_FALSE:
print(GL.glGetShaderInfoLog(vertexShader))
print(GL.glGetShaderInfoLog(fragmentShader))
print(GL.glGetProgramInfoLog(self.program))
GL.glDeleteShader(vertexShader)
GL.glDeleteShader(fragmentShader)
GL.glDeleteProgram(self.program)
self.program = 0
GL.glDeleteShader(vertexShader)
GL.glDeleteShader(fragmentShader)
self.uniformLocations = {}
for param in uniformDict:
self.uniformLocations[param] = GL.glGetUniformLocation(self.program, param)
def uniform4f(self, param, x, y, z, w):
from OpenGL import GL
GL.glUniform4f(self.uniformLocations[param], x, y, z, w)
class Rect():
def __init__(self):
self.xywh = [0.0] * 4
@classmethod
def fromXYWH(cls, xywh):
self = cls()
self.xywh[:] = list(map(float, xywh[:4]))
return self
@classmethod
def fromCorners(cls, c0, c1):
self = cls()
self.xywh[0] = float(min(c0[0], c1[0]))
self.xywh[1] = float(min(c0[1], c1[1]))
self.xywh[2] = float(max(c0[0], c1[0])) - self.xywh[0]
self.xywh[3] = float(max(c0[1], c1[1])) - self.xywh[1]
return self
def scaledAndBiased(self, sxy, txy):
ret = self.__class__()
for c in range(2):
ret.xywh[c] = sxy[c] * self.xywh[c] + txy[c]
ret.xywh[c + 2] = sxy[c] * self.xywh[c + 2]
return ret
def _splitAlongY(self, y):
bottom = self.__class__()
top = self.__class__()
bottom.xywh[:] = self.xywh
top.xywh[:] = self.xywh
top.xywh[1] = y
bottom.xywh[3] = top.xywh[1] - bottom.xywh[1]
top.xywh[3] = top.xywh[3] - bottom.xywh[3]
return bottom, top
def _splitAlongX(self, x):
left = self.__class__()
right = self.__class__()
left.xywh[:] = self.xywh
right.xywh[:] = self.xywh
right.xywh[0] = x
left.xywh[2] = right.xywh[0] - left.xywh[0]
right.xywh[2] = right.xywh[2] - left.xywh[2]
return left, right
def difference(self, xywh):
#check x
if xywh[0] > self.xywh[0]:
#keep left, check right
left, right = self._splitAlongX(xywh[0])
return [left] + right.difference(xywh)
if (xywh[0] + xywh[2]) < (self.xywh[0] + self.xywh[2]):
#keep right
left, right = self._splitAlongX(xywh[0] + xywh[2])
return [right]
#check y
if xywh[1] > self.xywh[1]:
#keep bottom, check top
bottom, top = self._splitAlongY(xywh[1])
return [bottom] + top.difference(xywh)
if (xywh[1] + xywh[3]) < (self.xywh[1] + self.xywh[3]):
#keep top
bottom, top = self._splitAlongY(xywh[1] + xywh[3])
return [top]
return []
class OutlineRect(Rect):
_glslProgram = None
_vbo = 0
_vao = 0
def __init__(self):
Rect.__init__(self)
@classmethod
def compileProgram(self):
if self._glslProgram:
return self._glslProgram
from OpenGL import GL
import ctypes
# prep a quad line vbo
self._vbo = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._vbo)
st = [0, 0, 1, 0, 1, 1, 0, 1]
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(st)*4,
(ctypes.c_float*len(st))(*st), GL.GL_STATIC_DRAW)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
self._glslProgram = GLSLProgram(
# for OpenGL 3.1 or later
"""#version 140
uniform vec4 rect;
in vec2 st;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1); }""",
"""#version 140
out vec4 fragColor;
uniform vec4 color;
void main() { fragColor = color; }""",
# for OpenGL 2.1 (osx compatibility profile)
"""#version 120
uniform vec4 rect;
attribute vec2 st;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1); }""",
"""#version 120
uniform vec4 color;
void main() { gl_FragColor = color; }""",
["rect", "color"])
return self._glslProgram
def glDraw(self, color):
from OpenGL import GL
cls = self.__class__
program = cls.compileProgram()
if (program.program == 0):
return
GL.glUseProgram(program.program)
if (program._glMajorVersion >= 4):
GL.glDisable(GL.GL_SAMPLE_ALPHA_TO_COVERAGE)
# requires PyOpenGL 3.0.2 or later for glGenVertexArrays.
if (program._glMajorVersion >= 3 and hasattr(GL, 'glGenVertexArrays')):
if (cls._vao == 0):
cls._vao = GL.glGenVertexArrays(1)
GL.glBindVertexArray(cls._vao)
# for some reason, we need to bind at least 1 vertex attrib (is OSX)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, cls._vbo)
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 2, GL.GL_FLOAT, False, 0, None)
program.uniform4f("color", *color)
program.uniform4f("rect", *self.xywh)
GL.glDrawArrays(GL.GL_LINE_LOOP, 0, 4)
class FilledRect(Rect):
_glslProgram = None
_vbo = 0
_vao = 0
def __init__(self):
Rect.__init__(self)
@classmethod
def compileProgram(self):
if self._glslProgram:
return self._glslProgram
from OpenGL import GL
import ctypes
# prep a quad line vbo
self._vbo = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._vbo)
st = [0, 0, 1, 0, 0, 1, 1, 1]
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(st)*4,
(ctypes.c_float*len(st))(*st), GL.GL_STATIC_DRAW)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
self._glslProgram = GLSLProgram(
# for OpenGL 3.1 or later
"""#version 140
uniform vec4 rect;
in vec2 st;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1); }""",
"""#version 140
out vec4 fragColor;
uniform vec4 color;
void main() { fragColor = color; }""",
# for OpenGL 2.1 (osx compatibility profile)
"""#version 120
uniform vec4 rect;
attribute vec2 st;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1); }""",
"""#version 120
uniform vec4 color;
void main() { gl_FragColor = color; }""",
["rect", "color"])
return self._glslProgram
def glDraw(self, color):
#don't draw if too small
if self.xywh[2] < 0.001 or self.xywh[3] < 0.001:
return
from OpenGL import GL
cls = self.__class__
program = cls.compileProgram()
if (program.program == 0):
return
GL.glUseProgram(program.program)
if (program._glMajorVersion >= 4):
GL.glDisable(GL.GL_SAMPLE_ALPHA_TO_COVERAGE)
# requires PyOpenGL 3.0.2 or later for glGenVertexArrays.
if (program._glMajorVersion >= 3 and hasattr(GL, 'glGenVertexArrays')):
if (cls._vao == 0):
cls._vao = GL.glGenVertexArrays(1)
GL.glBindVertexArray(cls._vao)
# for some reason, we need to bind at least 1 vertex attrib (is OSX)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, cls._vbo)
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 2, GL.GL_FLOAT, False, 0, None)
program.uniform4f("color", *color)
program.uniform4f("rect", *self.xywh)
GL.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4)
class Prim2DSetupTask():
def __init__(self, viewport):
self._viewport = viewport[:]
def Sync(self, ctx):
pass
def Execute(self, ctx):
from OpenGL import GL
GL.glViewport(*self._viewport)
GL.glDisable(GL.GL_DEPTH_TEST)
GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
GL.glEnable(GL.GL_BLEND)
class Prim2DDrawTask():
def __init__(self):
self._prims = []
self._colors = []
self._pixelRatio = QtWidgets.QApplication.instance().devicePixelRatio()
def Sync(self, ctx):
for prim in self._prims:
prim.__class__.compileProgram()
def Execute(self, ctx):
from OpenGL import GL
for prim, color in zip(self._prims, self._colors):
prim.glDraw(color)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
GL.glDisableVertexAttribArray(0)
if (int(GL.glGetString(GL.GL_VERSION)[0]) >= 3 and hasattr(GL, 'glGenVertexArrays')):
GL.glBindVertexArray(0)
GL.glUseProgram(0)
class Outline(Prim2DDrawTask):
def __init__(self):
Prim2DDrawTask.__init__(self)
self._outlineColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(0.0, 0.0, 0.0, 1.0))
def updatePrims(self, croppedViewport, qglwidget):
width = float(qglwidget.width()) * self._pixelRatio
height = float(qglwidget.height()) * self._pixelRatio
prims = [ OutlineRect.fromXYWH(croppedViewport) ]
self._prims = [p.scaledAndBiased((2.0 / width, 2.0 / height), (-1, -1))
for p in prims]
self._colors = [ self._outlineColor ]
class Reticles(Prim2DDrawTask):
def __init__(self):
Prim2DDrawTask.__init__(self)
self._outlineColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(0.0, 0.7, 1.0, 0.9))
def updateColor(self, color):
self._outlineColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(*color))
def updatePrims(self, croppedViewport, qglwidget, inside, outside):
width = float(qglwidget.width()) * self._pixelRatio
height = float(qglwidget.height()) * self._pixelRatio
prims = [ ]
ascenders = [0, 0]
descenders = [0, 0]
if inside:
descenders = [7, 15]
if outside:
ascenders = [7, 15]
# vertical reticles on the top and bottom
for i in range(5):
w = 2.6
h = ascenders[i & 1] + descenders[i & 1]
x = croppedViewport[0] - (w // 2) + ((i + 1) * croppedViewport[2]) // 6
bottomY = croppedViewport[1] - ascenders[i & 1]
topY = croppedViewport[1] + croppedViewport[3] - descenders[i & 1]
prims.append(FilledRect.fromXYWH((x, bottomY, w, h)))
prims.append(FilledRect.fromXYWH((x, topY, w, h)))
# horizontal reticles on the left and right
for i in range(5):
w = ascenders[i & 1] + descenders[i & 1]
h = 2.6
leftX = croppedViewport[0] - ascenders[i & 1]
rightX = croppedViewport[0] + croppedViewport[2] - descenders[i & 1]
y = croppedViewport[1] - (h // 2) + ((i + 1) * croppedViewport[3]) // 6
prims.append(FilledRect.fromXYWH((leftX, y, w, h)))
prims.append(FilledRect.fromXYWH((rightX, y, w, h)))
self._prims = [p.scaledAndBiased((2.0 / width, 2.0 / height), (-1, -1))
for p in prims]
self._colors = [ self._outlineColor ] * len(self._prims)
class Mask(Prim2DDrawTask):
def __init__(self):
Prim2DDrawTask.__init__(self)
self._maskColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(0.0, 0.0, 0.0, 1.0))
def updateColor(self, color):
self._maskColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(*color))
def updatePrims(self, croppedViewport, qglwidget):
width = float(qglwidget.width()) * self._pixelRatio
height = float(qglwidget.height()) * self._pixelRatio
rect = FilledRect.fromXYWH((0, 0, width, height))
prims = rect.difference(croppedViewport)
self._prims = [p.scaledAndBiased((2.0 / width, 2.0 / height), (-1, -1))
for p in prims]
self._colors = [ self._maskColor ] * 2
class HUD():
class Group():
def __init__(self, name, w, h):
self.x = 0
self.y = 0
self.w = w
self.h = h
pixelRatio = QtWidgets.QApplication.instance().devicePixelRatio()
imageW = w * pixelRatio
imageH = h * pixelRatio
self.qimage = QtGui.QImage(imageW, imageH, QtGui.QImage.Format_ARGB32)
self.qimage.fill(QtGui.QColor(0, 0, 0, 0))
self.painter = QtGui.QPainter()
def __init__(self):
self._pixelRatio = QtWidgets.QApplication.instance().devicePixelRatio()
self._HUDLineSpacing = 15
self._HUDFont = QtGui.QFont("Menv Mono Numeric", 9*self._pixelRatio)
self._groups = {}
self._glslProgram = None
self._glMajorVersion = 0
self._vao = 0
def compileProgram(self):
from OpenGL import GL
import ctypes
# prep a quad vbo
self._vbo = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._vbo)
st = [0, 0, 1, 0, 0, 1, 1, 1]
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(st)*4,
(ctypes.c_float*len(st))(*st), GL.GL_STATIC_DRAW)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
self._glslProgram = GLSLProgram(
# for OpenGL 3.1 or later
"""#version 140
uniform vec4 rect;
in vec2 st;
out vec2 uv;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1);
uv = vec2(st.x, 1 - st.y); }""",
"""#version 140
in vec2 uv;
out vec4 color;
uniform sampler2D tex;
void main() { color = texture(tex, uv); }""",
# for OpenGL 2.1 (osx compatibility profile)
"""#version 120
uniform vec4 rect;
attribute vec2 st;
varying vec2 uv;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1);
uv = vec2(st.x, 1 - st.y); }""",
"""#version 120
varying vec2 uv;
uniform sampler2D tex;
void main() { gl_FragColor = texture2D(tex, uv); }""",
["rect", "tex"])
return True
def addGroup(self, name, w, h):
self._groups[name] = self.Group(name, w, h)
def updateGroup(self, name, x, y, col, dic, keys = None):
group = self._groups[name]
group.qimage.fill(QtGui.QColor(0, 0, 0, 0))
group.x = x
group.y = y
painter = group.painter
painter.begin(group.qimage)
from .prettyPrint import prettyPrint
if keys is None:
keys = sorted(dic.keys())
# find the longest key so we know how far from the edge to print
# add [0] at the end so that max() never gets an empty sequence
longestKeyLen = max([len(k) for k in dic.keys()]+[0])
margin = int(longestKeyLen*1.4)
painter.setFont(self._HUDFont)
color = QtGui.QColor()
yy = 10 * self._pixelRatio
lineSpacing = self._HUDLineSpacing * self._pixelRatio
for key in keys:
if key not in dic:
continue
line = key.rjust(margin) + ": " + str(prettyPrint(dic[key]))
# Shadow of text
shadow = Gf.ConvertDisplayToLinear(Gf.Vec3f(.2, .2, .2))
color.setRgbF(shadow[0], shadow[1], shadow[2])
painter.setPen(color)
painter.drawText(1, yy+1, line)
# Colored text
color.setRgbF(col[0], col[1], col[2])
painter.setPen(color)
painter.drawText(0, yy, line)
yy += lineSpacing
painter.end()
return y + lineSpacing
def draw(self, qglwidget):
from OpenGL import GL
if (self._glslProgram == None):
self.compileProgram()
if (self._glslProgram.program == 0):
return
GL.glUseProgram(self._glslProgram.program)
width = float(qglwidget.width())
height = float(qglwidget.height())
if (self._glslProgram._glMajorVersion >= 4):
GL.glDisable(GL.GL_SAMPLE_ALPHA_TO_COVERAGE)
# requires PyOpenGL 3.0.2 or later for glGenVertexArrays.
if (self._glslProgram._glMajorVersion >= 3 and hasattr(GL, 'glGenVertexArrays')):
if (self._vao == 0):
self._vao = GL.glGenVertexArrays(1)
GL.glBindVertexArray(self._vao)
# for some reason, we need to bind at least 1 vertex attrib (is OSX)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._vbo)
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 2, GL.GL_FLOAT, False, 0, None)
# seems like a bug in Qt4.8/CoreProfile on OSX that GL_UNPACK_ROW_LENGTH has changed.
GL.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, 0)
for name in self._groups:
group = self._groups[name]
tex = qglwidget.bindTexture(group.qimage, GL.GL_TEXTURE_2D, GL.GL_RGBA,
QtOpenGL.QGLContext.NoBindOption)
GL.glUniform4f(self._glslProgram.uniformLocations["rect"],
2*group.x/width - 1,
1 - 2*group.y/height - 2*group.h/height,
2*group.w/width,
2*group.h/height)
GL.glUniform1i(self._glslProgram.uniformLocations["tex"], 0)
GL.glActiveTexture(GL.GL_TEXTURE0)
GL.glBindTexture(GL.GL_TEXTURE_2D, tex)
GL.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4)
GL.glDeleteTextures(tex)
GL.glBindTexture(GL.GL_TEXTURE_2D, 0)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
GL.glDisableVertexAttribArray(0)
if (self._vao != 0):
GL.glBindVertexArray(0)
GL.glUseProgram(0)
class StageView(QtOpenGL.QGLWidget):
'''
QGLWidget that displays a USD Stage. A StageView requires a dataModel
object from which it will query state it needs to properly image its
given UsdStage. See the nested DefaultDataModel class for the expected
API.
'''
# TODO: most, if not all of the state StageView requires (except possibly
# the stage?), should be migrated to come from the dataModel, and redrawing
# should be triggered by signals the dataModel emits.
class DefaultDataModel(RootDataModel):
def __init__(self):
super(StageView.DefaultDataModel, self).__init__()
self._selectionDataModel = SelectionDataModel(self)
self._viewSettingsDataModel = ViewSettingsDataModel(self, None)
@property
def selection(self):
return self._selectionDataModel
@property
def viewSettings(self):
return self._viewSettingsDataModel
###########
# Signals #
###########
signalBboxUpdateTimeChanged = QtCore.Signal(int)
# First arg is primPath, (which could be empty Path)
# Second arg is instanceIndex (or UsdImagingGL.ALL_INSTANCES for all
# instances)
# Third and fourth arg are primPath, instanceIndex, of root level
# boundable (if applicable).
# Fifth arg is selectedPoint
# Sixth and seventh args represent state at time of the pick
signalPrimSelected = QtCore.Signal(Sdf.Path, int, Sdf.Path, int, Gf.Vec3f,
QtCore.Qt.MouseButton,
QtCore.Qt.KeyboardModifiers)
# Only raised when StageView has been told to do so, setting
# rolloverPicking to True
signalPrimRollover = QtCore.Signal(Sdf.Path, int, Sdf.Path, int,
Gf.Vec3f, QtCore.Qt.KeyboardModifiers)
signalMouseDrag = QtCore.Signal()
signalErrorMessage = QtCore.Signal(str)
signalSwitchedToFreeCam = QtCore.Signal()
signalFrustumChanged = QtCore.Signal()
@property
def renderParams(self):
return self._renderParams
@renderParams.setter
def renderParams(self, params):
self._renderParams = params
@property
def autoClip(self):
return self._dataModel.viewSettings.autoComputeClippingPlanes
@property
def showReticles(self):
return ((self._dataModel.viewSettings.showReticles_Inside or self._dataModel.viewSettings.showReticles_Outside)
and self._dataModel.viewSettings.cameraPrim != None)
@property
def _fitCameraInViewport(self):
return ((self._dataModel.viewSettings.showMask or self._dataModel.viewSettings.showMask_Outline or self.showReticles)
and self._dataModel.viewSettings.cameraPrim != None)
@property
def _cropImageToCameraViewport(self):
return ((self._dataModel.viewSettings.showMask and self._dataModel.viewSettings.showMask_Opaque)
and self._dataModel.viewSettings.cameraPrim != None)
@property
def cameraPrim(self):
return self._dataModel.viewSettings.cameraPrim
@cameraPrim.setter
def cameraPrim(self, prim):
self._dataModel.viewSettings.cameraPrim = prim
@property
def rolloverPicking(self):
return self._rolloverPicking
@rolloverPicking.setter
def rolloverPicking(self, enabled):
self._rolloverPicking = enabled
self.setMouseTracking(enabled)
@property
def fpsHUDInfo(self):
return self._fpsHUDInfo
@fpsHUDInfo.setter
def fpsHUDInfo(self, info):
self._fpsHUDInfo = info
@property
def fpsHUDKeys(self):
return self._fpsHUDKeys
@fpsHUDKeys.setter
def fpsHUDKeys(self, keys):
self._fpsHUDKeys = keys
@property
def upperHUDInfo(self):
return self._upperHUDInfo
@upperHUDInfo.setter
def upperHUDInfo(self, info):
self._upperHUDInfo = info
@property
def HUDStatKeys(self):
return self._HUDStatKeys
@HUDStatKeys.setter
def HUDStatKeys(self, keys):
self._HUDStatKeys = keys
@property
def overrideNear(self):
return self._overrideNear
@overrideNear.setter
def overrideNear(self, value):
"""To remove the override, set to None. Causes FreeCamera to become
active."""
self._overrideNear = value
self.switchToFreeCamera()
self._dataModel.viewSettings.freeCamera.overrideNear = value
self.updateGL()
@property
def overrideFar(self):
return self._overrideFar
@overrideFar.setter
def overrideFar(self, value):
"""To remove the override, set to None. Causes FreeCamera to become
active."""
self._overrideFar = value
self.switchToFreeCamera()
self._dataModel.viewSettings.freeCamera.overrideFar = value
self.updateGL()
@property
def allSceneCameras(self):
return self._allSceneCameras
@allSceneCameras.setter
def allSceneCameras(self, value):
self._allSceneCameras = value
@property
def gfCamera(self):
"""Return the last computed Gf Camera"""
return self._lastComputedGfCamera
@property
def cameraFrustum(self):
"""Unlike the StageView.freeCamera property, which is invalid/None
whenever we are viewing from a scene/stage camera, the 'cameraFrustum'
property will always return the last-computed camera frustum, regardless
of source."""
return self._lastComputedGfCamera.frustum
@property
def rendererDisplayName(self):
return self._rendererDisplayName
@property
def rendererAovName(self):
return self._rendererAovName
def __init__(self, parent=None, dataModel=None, printTiming=False):
# Note: The default format *disables* the alpha component and so the
# default backbuffer uses GL_RGB.
glFormat = QtOpenGL.QGLFormat()
msaa = os.getenv("USDVIEW_ENABLE_MSAA", "1")
if msaa == "1":
glFormat.setSampleBuffers(True)
glFormat.setSamples(4)
# XXX: for OSX (QT5 required)
# glFormat.setProfile(QtOpenGL.QGLFormat.CoreProfile)
super(StageView, self).__init__(glFormat, parent)
self._dataModel = dataModel or StageView.DefaultDataModel()
self._printTiming = printTiming
self._isFirstImage = True
# update() whenever a visible view setting (one which affects the view)
# is changed.
self._dataModel.viewSettings.signalVisibleSettingChanged.connect(
self.update)
self._dataModel.signalStageReplaced.connect(self._stageReplaced)
self._dataModel.selection.signalPrimSelectionChanged.connect(
self._primSelectionChanged)
self._dataModel.viewSettings.freeCamera = FreeCamera(True,
self._dataModel.viewSettings.freeCameraFOV)
self._lastComputedGfCamera = None
# prep Mask regions
self._mask = Mask()
self._maskOutline = Outline()
self._reticles = Reticles()
# prep HUD regions
self._hud = HUD()
self._hud.addGroup("TopLeft", 250, 160) # subtree
self._hud.addGroup("TopRight", 140, 32) # Hydra: Enabled
self._hud.addGroup("BottomLeft", 250, 160) # GPU stats
self._hud.addGroup("BottomRight", 210, 32) # Camera, Complexity
self._stageIsZup = True
self._cameraMode = "none"
self._rolloverPicking = False
self._dragActive = False
self._lastX = 0
self._lastY = 0
self._renderer = None
self._renderPauseState = False
self._renderStopState = False
self._reportedContextError = False
self._renderModeDict = {
RenderModes.WIREFRAME: UsdImagingGL.DrawMode.DRAW_WIREFRAME,
RenderModes.WIREFRAME_ON_SURFACE:
UsdImagingGL.DrawMode.DRAW_WIREFRAME_ON_SURFACE,
RenderModes.SMOOTH_SHADED: UsdImagingGL.DrawMode.DRAW_SHADED_SMOOTH,
RenderModes.POINTS: UsdImagingGL.DrawMode.DRAW_POINTS,
RenderModes.FLAT_SHADED: UsdImagingGL.DrawMode.DRAW_SHADED_FLAT,
RenderModes.GEOM_ONLY: UsdImagingGL.DrawMode.DRAW_GEOM_ONLY,
RenderModes.GEOM_SMOOTH: UsdImagingGL.DrawMode.DRAW_GEOM_SMOOTH,
RenderModes.GEOM_FLAT: UsdImagingGL.DrawMode.DRAW_GEOM_FLAT,
RenderModes.HIDDEN_SURFACE_WIREFRAME:
UsdImagingGL.DrawMode.DRAW_WIREFRAME
}
self._renderParams = UsdImagingGL.RenderParams()
# Optionally override OCIO lut size. Similar env var available for
# other apps: ***_OCIO_LUT3D_EDGE_SIZE
ocioLutSize = os.getenv("USDVIEW_OCIO_LUT3D_EDGE_SIZE", 0)
if ocioLutSize > 0:
self._renderParams.lut3dSizeOCIO = ocioLutSize
self._dist = 50
self._bbox = Gf.BBox3d()
self._selectionBBox = Gf.BBox3d()
self._selectionBrange = Gf.Range3d()
self._selectionOrientedRange = Gf.Range3d()
self._bbcenterForBoxDraw = (0, 0, 0)
self._overrideNear = None
self._overrideFar = None
self._forceRefresh = False
self._renderTime = 0
self._allSceneCameras = None
# HUD properties
self._fpsHUDInfo = dict()
self._fpsHUDKeys = []
self._upperHUDInfo = dict()
self._HUDStatKeys = list()
self._glPrimitiveGeneratedQuery = None
self._glTimeElapsedQuery = None
self._simpleGLSLProgram = None
self._axisVBO = None
self._bboxVBO = None
self._cameraGuidesVBO = None
self._vao = 0
# Update all properties for the current stage.
self._stageReplaced()
def _getRenderer(self):
# Unfortunately, we cannot assume that initializeGL() was called
# before attempts to use the renderer (e.g. pick()), so we must
# create the renderer lazily, when we try to do real work with it.
if not self._renderer:
if self.context().isValid():
if self.context().initialized():
self._renderer = UsdImagingGL.Engine()
self._handleRendererChanged(self.GetCurrentRendererId())
elif not self._reportedContextError:
self._reportedContextError = True
raise RuntimeError("StageView could not initialize renderer without a valid GL context")
return self._renderer
def _handleRendererChanged(self, rendererId):
self._rendererDisplayName = self.GetRendererDisplayName(rendererId)
self._rendererAovName = "color"
self._renderPauseState = False
self._renderStopState = False
# XXX For HdSt we explicitely enable AOV via SetRendererAov
# This is because ImagingGL / TaskController are spawned via prims in
# Presto, so we default AOVs OFF until everything is AOV ready.
self.SetRendererAov(self.rendererAovName)
def _scaleMouseCoords(self, point):
return point * QtWidgets.QApplication.instance().devicePixelRatio()
def closeRenderer(self):
'''Close the current renderer.'''
with Timer() as t:
self._renderer = None
if self._printTiming:
t.PrintTime('shut down Hydra')
def GetRendererPlugins(self):
if self._renderer:
return self._renderer.GetRendererPlugins()
else:
return []
def GetRendererDisplayName(self, plugId):
if self._renderer:
return self._renderer.GetRendererDisplayName(plugId)
else:
return ""
def GetCurrentRendererId(self):
if self._renderer:
return self._renderer.GetCurrentRendererId()
else:
return ""
def SetRendererPlugin(self, plugId):
if self._renderer:
if self._renderer.SetRendererPlugin(plugId):
self._handleRendererChanged(plugId)
self.updateGL()
return True
else:
return False
return True
def GetRendererAovs(self):
if self._renderer:
return self._renderer.GetRendererAovs()
else:
return []
def SetRendererAov(self, aov):
if self._renderer:
if self._renderer.SetRendererAov(aov):
self._rendererAovName = aov
self.updateGL()
return True
else:
return False
return True
def GetRendererSettingsList(self):
if self._renderer:
return self._renderer.GetRendererSettingsList()
else:
return []
def GetRendererSetting(self, name):
if self._renderer:
return self._renderer.GetRendererSetting(name)
else:
return None
def SetRendererSetting(self, name, value):
if self._renderer:
self._renderer.SetRendererSetting(name, value)
self.updateGL()
def SetRendererPaused(self, paused):
if self._renderer and (not self._renderer.IsConverged()):
if paused:
self._renderPauseState = self._renderer.PauseRenderer()
else:
self._renderPauseState = not self._renderer.ResumeRenderer()
self.updateGL()
def IsPauseRendererSupported(self):
if self._renderer:
if self._renderer.IsPauseRendererSupported():
return True
return False
def IsRendererConverged(self):
return self._renderer and self._renderer.IsConverged()
def SetRendererStopped(self, stopped):
if self._renderer:
if stopped:
self._renderStopState = self._renderer.StopRenderer()
else:
self._renderStopState = not self._renderer.RestartRenderer()
self.updateGL()
def IsStopRendererSupported(self):
if self._renderer:
if self._renderer.IsStopRendererSupported():
return True
return False
def _stageReplaced(self):
'''Set the USD Stage this widget will be displaying. To decommission
(even temporarily) this widget, supply None as 'stage'.'''
self.allSceneCameras = None
if self._dataModel.stage:
self._stageIsZup = (
UsdGeom.GetStageUpAxis(self._dataModel.stage) == UsdGeom.Tokens.z)
self._dataModel.viewSettings.freeCamera = \
FreeCamera(self._stageIsZup,
self._dataModel.viewSettings.freeCameraFOV)
# simple GLSL program for axis/bbox drawings
def GetSimpleGLSLProgram(self):
if self._simpleGLSLProgram == None:
self._simpleGLSLProgram = GLSLProgram(
"""#version 140
uniform mat4 mvpMatrix;
in vec3 position;
void main() { gl_Position = vec4(position, 1)*mvpMatrix; }""",
"""#version 140
out vec4 outColor;
uniform vec4 color;
void main() { outColor = color; }""",
"""#version 120
uniform mat4 mvpMatrix;
attribute vec3 position;
void main() { gl_Position = vec4(position, 1)*mvpMatrix; }""",
"""#version 120
uniform vec4 color;
void main() { gl_FragColor = color; }""",
["mvpMatrix", "color"])
return self._simpleGLSLProgram
def DrawAxis(self, viewProjectionMatrix):
from OpenGL import GL
import ctypes
# grab the simple shader
glslProgram = self.GetSimpleGLSLProgram()
if (glslProgram.program == 0):
return
# vao
if (glslProgram._glMajorVersion >= 3 and hasattr(GL, 'glGenVertexArrays')):
if (self._vao == 0):
self._vao = GL.glGenVertexArrays(1)
GL.glBindVertexArray(self._vao)
# prep a vbo for axis
if (self._axisVBO is None):
self._axisVBO = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._axisVBO)
data = [1, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0]
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(data)*4,
(ctypes.c_float*len(data))(*data), GL.GL_STATIC_DRAW)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._axisVBO)
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, 0, ctypes.c_void_p(0))
GL.glUseProgram(glslProgram.program)
# i *think* this actually wants the camera dist so that the axis stays
# somewhat fixed in screen-space size.
mvpMatrix = Gf.Matrix4f().SetScale(self._dist/20.0) * viewProjectionMatrix
matrix = (ctypes.c_float*16).from_buffer_copy(mvpMatrix)
GL.glUniformMatrix4fv(glslProgram.uniformLocations["mvpMatrix"],
1, GL.GL_TRUE, matrix)
GL.glUniform4f(glslProgram.uniformLocations["color"], 1, 0, 0, 1)
GL.glDrawArrays(GL.GL_LINES, 0, 2)
GL.glUniform4f(glslProgram.uniformLocations["color"], 0, 1, 0, 1)
GL.glDrawArrays(GL.GL_LINES, 2, 2)
GL.glUniform4f(glslProgram.uniformLocations["color"], 0, 0, 1, 1)
GL.glDrawArrays(GL.GL_LINES, 4, 2)
GL.glDisableVertexAttribArray(0)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
GL.glUseProgram(0)
if (self._vao != 0):
GL.glBindVertexArray(0)
def DrawBBox(self, viewProjectionMatrix):
col = self._dataModel.viewSettings.clearColor
color = Gf.Vec3f(col[0]-.5 if col[0]>0.5 else col[0]+.5,
col[1]-.5 if col[1]>0.5 else col[1]+.5,
col[2]-.5 if col[2]>0.5 else col[2]+.5)
# Draw axis-aligned bounding box
if self._dataModel.viewSettings.showAABBox:
bsize = self._selectionBrange.max - self._selectionBrange.min
trans = Gf.Transform()
trans.SetScale(0.5*bsize)
trans.SetTranslation(self._bbcenterForBoxDraw)
self.drawWireframeCube(color,
Gf.Matrix4f(trans.GetMatrix()) * viewProjectionMatrix)
# Draw oriented bounding box
if self._dataModel.viewSettings.showOBBox:
bsize = self._selectionOrientedRange.max - self._selectionOrientedRange.min
center = bsize / 2. + self._selectionOrientedRange.min
trans = Gf.Transform()
trans.SetScale(0.5*bsize)
trans.SetTranslation(center)
self.drawWireframeCube(color,
Gf.Matrix4f(trans.GetMatrix()) *
Gf.Matrix4f(self._selectionBBox.matrix) *
viewProjectionMatrix)
# XXX:
# First pass at visualizing cameras in usdview-- just oracles for
# now. Eventually the logic should live in usdImaging, where the delegate
# would add the camera guide geometry to the GL buffers over the course over
# its stage traversal, and get time samples accordingly.
def DrawCameraGuides(self, mvpMatrix):
from OpenGL import GL
import ctypes
# prep a vbo for camera guides
if (self._cameraGuidesVBO is None):
self._cameraGuidesVBO = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._cameraGuidesVBO)
data = []
for camera in self._allSceneCameras:
# Don't draw guides for the active camera.
if camera == self._dataModel.viewSettings.cameraPrim or not (camera and camera.IsActive()):
continue
gfCamera = UsdGeom.Camera(camera).GetCamera(
self._dataModel.currentFrame)
frustum = gfCamera.frustum
# (Gf documentation seems to be wrong)-- Ordered as
# 0: left bottom near
# 1: right bottom near
# 2: left top near
# 3: right top near
# 4: left bottom far
# 5: right bottom far
# 6: left top far
# 7: right top far
oraclePoints = frustum.ComputeCorners()
# Near plane
indices = [0,1,1,3,3,2,2,0, # Near plane
4,5,5,7,7,6,6,4, # Far plane
3,7,0,4,1,5,2,6] # Lines between near and far planes.
data.extend([oraclePoints[i][j] for i in indices for j in range(3)])
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(data)*4,
(ctypes.c_float*len(data))(*data), GL.GL_STATIC_DRAW)
# grab the simple shader
glslProgram = self.GetSimpleGLSLProgram()
if (glslProgram.program == 0):
return
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, 0, ctypes.c_void_p(0))
GL.glUseProgram(glslProgram.program)
matrix = (ctypes.c_float*16).from_buffer_copy(mvpMatrix)
GL.glUniformMatrix4fv(glslProgram.uniformLocations["mvpMatrix"],
1, GL.GL_TRUE, matrix)
# Grabbed fallback oracleColor from CamCamera.
GL.glUniform4f(glslProgram.uniformLocations["color"],
0.82745, 0.39608, 0.1647, 1)
GL.glDrawArrays(GL.GL_LINES, 0, len(data)//3)
GL.glDisableVertexAttribArray(0)
GL.glUseProgram(0)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
def updateBboxPurposes(self):
includedPurposes = self._dataModel.includedPurposes
if self._dataModel.viewSettings.displayGuide:
includedPurposes.add(UsdGeom.Tokens.guide)
elif UsdGeom.Tokens.guide in includedPurposes:
includedPurposes.remove(UsdGeom.Tokens.guide)
if self._dataModel.viewSettings.displayProxy:
includedPurposes.add(UsdGeom.Tokens.proxy)
elif UsdGeom.Tokens.proxy in includedPurposes:
includedPurposes.remove(UsdGeom.Tokens.proxy)
if self._dataModel.viewSettings.displayRender:
includedPurposes.add(UsdGeom.Tokens.render)
elif UsdGeom.Tokens.render in includedPurposes:
includedPurposes.remove(UsdGeom.Tokens.render)
self._dataModel.includedPurposes = includedPurposes
# force the bbox to refresh
self._bbox = Gf.BBox3d()
def recomputeBBox(self):
selectedPrims = self._dataModel.selection.getLCDPrims()
try:
startTime = time()
self._bbox = self.getStageBBox()
if len(selectedPrims) == 1 and selectedPrims[0].GetPath() == '/':
if self._bbox.GetRange().IsEmpty():
self._selectionBBox = self._getDefaultBBox()
else:
self._selectionBBox = self._bbox
else:
self._selectionBBox = self.getSelectionBBox()
# BBox computation time for HUD
endTime = time()
ms = (endTime - startTime) * 1000.
self.signalBboxUpdateTimeChanged.emit(ms)
except RuntimeError:
# This may fail, but we want to keep the UI available,
# so print the error and attempt to continue loading
self.signalErrorMessage.emit("unable to get bounding box on "
"stage at frame {0}".format(self._dataModel.currentFrame))
import traceback
traceback.print_exc()
self._bbox = self._getEmptyBBox()
self._selectionBBox = self._getDefaultBBox()
self._selectionBrange = self._selectionBBox.ComputeAlignedRange()
self._selectionOrientedRange = self._selectionBBox.box
self._bbcenterForBoxDraw = self._selectionBBox.ComputeCentroid()
def resetCam(self, frameFit=1.1):
validFrameRange = (not self._selectionBrange.IsEmpty() and
self._selectionBrange.GetMax() != self._selectionBrange.GetMin())
if validFrameRange:
self.switchToFreeCamera()
self._dataModel.viewSettings.freeCamera.frameSelection(self._selectionBBox,
frameFit)
self.computeAndSetClosestDistance()
def updateView(self, resetCam=False, forceComputeBBox=False, frameFit=1.1):
'''Updates bounding boxes and camera. resetCam = True causes the camera to reframe
the specified prims. frameFit sets the ratio of the camera's frustum's
relevant dimension to the object's bounding box. 1.1, the default,
fits the prim's bounding box in the frame with a roughly 10% margin.
'''
# Only compute BBox if forced, if needed for drawing,
# or if this is the first time running.
computeBBox = forceComputeBBox or \
(self._dataModel.viewSettings.showBBoxes and
(self._dataModel.viewSettings.showAABBox or self._dataModel.viewSettings.showOBBox))\
or self._bbox.GetRange().IsEmpty()
if computeBBox:
self.recomputeBBox()
if resetCam:
self.resetCam(frameFit)
self.updateGL()
def updateSelection(self):
try:
renderer = self._getRenderer()
if not renderer:
# error has already been issued
return
renderer.ClearSelected()
psuRoot = self._dataModel.stage.GetPseudoRoot()
allInstances = self._dataModel.selection.getPrimInstances()
for prim in self._dataModel.selection.getLCDPrims():
if prim == psuRoot:
continue
primInstances = allInstances[prim]
if primInstances != ALL_INSTANCES:
for instanceIndex in primInstances:
renderer.AddSelected(prim.GetPath(), instanceIndex)
else:
renderer.AddSelected(
prim.GetPath(), UsdImagingGL.ALL_INSTANCES)
except Tf.ErrorException as e:
# If we encounter an error, we want to continue running. Just log
# the error and continue.
sys.stderr.write(
"ERROR: Usdview encountered an error while updating selection."
"{}\n".format(e))
finally:
# Make sure not to leak a reference to the renderer
renderer = None
def _getEmptyBBox(self):
# This returns the default empty bbox [FLT_MAX,-FLT_MAX]
return Gf.BBox3d()
def _getDefaultBBox(self):
return Gf.BBox3d(Gf.Range3d((-10,-10,-10), (10,10,10)))
def _isInfiniteBBox(self, bbox):
return isinf(bbox.GetRange().GetMin().GetLength()) or \
isinf(bbox.GetRange().GetMax().GetLength())
def getStageBBox(self):
bbox = self._dataModel.computeWorldBound(
self._dataModel.stage.GetPseudoRoot())
if bbox.GetRange().IsEmpty() or self._isInfiniteBBox(bbox):
bbox = self._getEmptyBBox()
return bbox
def getSelectionBBox(self):
bbox = Gf.BBox3d()
for n in self._dataModel.selection.getLCDPrims():
if n.IsActive() and not n.IsInMaster():
primBBox = self._dataModel.computeWorldBound(n)
bbox = Gf.BBox3d.Combine(bbox, primBBox)
return bbox
def renderSinglePass(self, renderMode, renderSelHighlights):
if not self._dataModel.stage:
return
renderer = self._getRenderer()
if not renderer:
# error has already been issued
return
# update rendering parameters
self._renderParams.frame = self._dataModel.currentFrame
self._renderParams.complexity = self._dataModel.viewSettings.complexity.value
self._renderParams.drawMode = renderMode
self._renderParams.showGuides = self._dataModel.viewSettings.displayGuide
self._renderParams.showProxy = self._dataModel.viewSettings.displayProxy
self._renderParams.showRender = self._dataModel.viewSettings.displayRender
self._renderParams.forceRefresh = self._forceRefresh
self._renderParams.cullStyle = \
(UsdImagingGL.CullStyle.CULL_STYLE_BACK_UNLESS_DOUBLE_SIDED
if self._dataModel.viewSettings.cullBackfaces
else UsdImagingGL.CullStyle.CULL_STYLE_NOTHING)
self._renderParams.gammaCorrectColors = False
self._renderParams.enableIdRender = self._dataModel.viewSettings.displayPrimId
self._renderParams.enableSampleAlphaToCoverage = not self._dataModel.viewSettings.displayPrimId
self._renderParams.highlight = renderSelHighlights
self._renderParams.enableSceneMaterials = self._dataModel.viewSettings.enableSceneMaterials
self._renderParams.colorCorrectionMode = self._dataModel.viewSettings.colorCorrectionMode
self._renderParams.clearColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(self._dataModel.viewSettings.clearColor))
pseudoRoot = self._dataModel.stage.GetPseudoRoot()
renderer.SetSelectionColor(self._dataModel.viewSettings.highlightColor)
try:
renderer.Render(pseudoRoot, self._renderParams)
except Tf.ErrorException as e:
# If we encounter an error during a render, we want to continue
# running. Just log the error and continue.
sys.stderr.write(
"ERROR: Usdview encountered an error while rendering.{}\n".format(e))
finally:
# Make sure not to leak a reference to the renderer
renderer = None
self._forceRefresh = False
def initializeGL(self):
if not self.isValid():
return
from pxr import Glf
if not Glf.GlewInit():
return
Glf.RegisterDefaultDebugOutputMessageCallback()
def updateGL(self):
"""We override this virtual so that we can make it a no-op during
playback. The client driving playback at a particular rate should
instead call updateForPlayback() to image the next frame."""
if not self._dataModel.playing:
super(StageView, self).updateGL()
def updateForPlayback(self):
"""If playing, update the GL canvas. Otherwise a no-op"""
if self._dataModel.playing:
super(StageView, self).updateGL()
def getActiveSceneCamera(self):
cameraPrim = self._dataModel.viewSettings.cameraPrim
if cameraPrim and cameraPrim.IsActive():
return cameraPrim
return None
# XXX: Consolidate window/frustum conformance code that is littered in
# several places.
def computeWindowPolicy(self, cameraAspectRatio):
# The freeCam always uses 'MatchVertically'.
# When using a scene cam, we factor in the masking setting and window
# size to compute it.
windowPolicy = CameraUtil.MatchVertically
if self.getActiveSceneCamera():
if self._cropImageToCameraViewport:
targetAspect = (
float(self.size().width()) / max(1.0, self.size().height()))
if targetAspect < cameraAspectRatio:
windowPolicy = CameraUtil.MatchHorizontally
else:
if self._fitCameraInViewport:
windowPolicy = CameraUtil.Fit
return windowPolicy
def computeWindowSize(self):
size = self.size() * self.devicePixelRatioF()
return (int(size.width()), int(size.height()))
def computeWindowViewport(self):
return (0, 0) + self.computeWindowSize()
def resolveCamera(self):
"""Returns a tuple of the camera to use for rendering (either a scene
camera or a free camera) and that camera's original aspect ratio.
Depending on camera guide settings, the camera frustum may be conformed
to fit the window viewport. Emits a signalFrustumChanged if the
camera frustum has changed since the last time resolveCamera was called."""
# If 'camera' is None, make sure we have a valid freeCamera
sceneCam = self.getActiveSceneCamera()
if sceneCam:
gfCam = UsdGeom.Camera(sceneCam).GetCamera(
self._dataModel.currentFrame)
else:
self.switchToFreeCamera()
gfCam = self._dataModel.viewSettings.freeCamera.computeGfCamera(
self._bbox, autoClip=self.autoClip)
cameraAspectRatio = gfCam.aspectRatio
# Conform the camera's frustum to the window viewport, if necessary.
if not self._cropImageToCameraViewport:
targetAspect = float(self.size().width()) / max(1.0, self.size().height())
if self._fitCameraInViewport:
CameraUtil.ConformWindow(gfCam, CameraUtil.Fit, targetAspect)
else:
CameraUtil.ConformWindow(gfCam, CameraUtil.MatchVertically, targetAspect)
frustumChanged = ((not self._lastComputedGfCamera) or
self._lastComputedGfCamera.frustum != gfCam.frustum)
# We need to COPY the camera, not assign it...
self._lastComputedGfCamera = Gf.Camera(gfCam)
if frustumChanged:
self.signalFrustumChanged.emit()
return (gfCam, cameraAspectRatio)
def computeCameraViewport(self, cameraAspectRatio):
# Conform the camera viewport to the camera's aspect ratio,
# and center the camera viewport in the window viewport.
windowPolicy = CameraUtil.MatchVertically
targetAspect = (
float(self.size().width()) / max(1.0, self.size().height()))
if targetAspect < cameraAspectRatio:
windowPolicy = CameraUtil.MatchHorizontally
viewport = Gf.Range2d(Gf.Vec2d(0, 0),
Gf.Vec2d(self.computeWindowSize()))
viewport = CameraUtil.ConformedWindow(viewport, windowPolicy, cameraAspectRatio)
viewport = (viewport.GetMin()[0], viewport.GetMin()[1],
viewport.GetSize()[0], viewport.GetSize()[1])
viewport = ViewportMakeCenteredIntegral(viewport)
return viewport
def copyViewState(self):
"""Returns a copy of this StageView's view-affecting state,
which can be used later to restore the view via restoreViewState().
Take note that we do NOT include the StageView's notion of the
current time (used by prim-based cameras to extract their data),
since we do not want a restore operation to put us out of sync
with respect to our owner's time.
"""
viewState = {}
viewState["_cameraPrim"] = self._dataModel.viewSettings.cameraPrim
viewState["_stageIsZup"] = self._stageIsZup
viewState["_overrideNear"] = self._overrideNear
viewState["_overrideFar"] = self._overrideFar
# Since FreeCamera is a compound/class object, we must copy
# it more deeply
viewState["_freeCamera"] = self._dataModel.viewSettings.freeCamera.clone() if self._dataModel.viewSettings.freeCamera else None
return viewState
def restoreViewState(self, viewState):
"""Restore view parameters from 'viewState', and redraw"""
self._dataModel.viewSettings.cameraPrim = viewState["_cameraPrim"]
self._stageIsZup = viewState["_stageIsZup"]
self._overrideNear = viewState["_overrideNear"]
self._overrideFar = viewState["_overrideFar"]
restoredCamera = viewState["_freeCamera"]
# Detach our freeCamera from the given viewState, to
# insulate against changes to viewState by caller
self._dataModel.viewSettings.freeCamera = restoredCamera.clone() if restoredCamera else None
self.update()
def drawWireframeCube(self, col, mvpMatrix):
from OpenGL import GL
import ctypes, itertools
# grab the simple shader
glslProgram = self.GetSimpleGLSLProgram()
if (glslProgram.program == 0):
return
# vao
if (glslProgram._glMajorVersion >= 3 and hasattr(GL, 'glGenVertexArrays')):
if (self._vao == 0):
self._vao = GL.glGenVertexArrays(1)
GL.glBindVertexArray(self._vao)
# prep a vbo for bbox
if (self._bboxVBO is None):
self._bboxVBO = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._bboxVBO)
# create 12 edges
data = []
p = list(itertools.product([-1,1],[-1,1],[-1,1]))
for i in p:
data.extend([i[0], i[1], i[2]])
for i in p:
data.extend([i[1], i[2], i[0]])
for i in p:
data.extend([i[2], i[0], i[1]])
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(data)*4,
(ctypes.c_float*len(data))(*data), GL.GL_STATIC_DRAW)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._bboxVBO)
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, 0, ctypes.c_void_p(0))
GL.glEnable(GL.GL_LINE_STIPPLE)
GL.glLineStipple(2,0xAAAA)
GL.glUseProgram(glslProgram.program)
matrix = (ctypes.c_float*16).from_buffer_copy(mvpMatrix)
GL.glUniformMatrix4fv(glslProgram.uniformLocations["mvpMatrix"],
1, GL.GL_TRUE, matrix)
GL.glUniform4f(glslProgram.uniformLocations["color"],
col[0], col[1], col[2], 1)
GL.glDrawArrays(GL.GL_LINES, 0, 24)
GL.glDisableVertexAttribArray(0)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
GL.glUseProgram(0)
GL.glDisable(GL.GL_LINE_STIPPLE)
if (self._vao != 0):
GL.glBindVertexArray(0)
def paintGL(self):
if not self._dataModel.stage:
return
renderer = self._getRenderer()
if not renderer:
# error has already been issued
return
try:
from OpenGL import GL
if self._dataModel.viewSettings.showHUD_GPUstats:
if self._glPrimitiveGeneratedQuery is None:
self._glPrimitiveGeneratedQuery = Glf.GLQueryObject()
if self._glTimeElapsedQuery is None:
self._glTimeElapsedQuery = Glf.GLQueryObject()
self._glPrimitiveGeneratedQuery.BeginPrimitivesGenerated()
self._glTimeElapsedQuery.BeginTimeElapsed()
if not UsdImagingGL.Engine.IsColorCorrectionCapable():
from OpenGL.GL.EXT.framebuffer_sRGB import GL_FRAMEBUFFER_SRGB_EXT
GL.glEnable(GL_FRAMEBUFFER_SRGB_EXT)
# Clear the default FBO associated with the widget/context to
# fully transparent and *not* the bg color.
# The bg color is used as the clear color for the aov, and the
# results of rendering are composited over the FBO (and not blit).
GL.glClearColor(*Gf.Vec4f(0,0,0,0))
GL.glEnable(GL.GL_DEPTH_TEST)
GL.glDepthFunc(GL.GL_LESS)
GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
GL.glEnable(GL.GL_BLEND)
# Note: camera lights and camera guides require the
# resolved (adjusted) camera viewProjection matrix, which is
# why we resolve the camera above always.
(gfCamera, cameraAspect) = self.resolveCamera()
frustum = gfCamera.frustum
cameraViewport = self.computeCameraViewport(cameraAspect)
viewport = self.computeWindowViewport()
windowViewport = viewport
if self._cropImageToCameraViewport:
viewport = cameraViewport
cam_pos = frustum.position
cam_up = frustum.ComputeUpVector()
cam_right = Gf.Cross(frustum.ComputeViewDirection(), cam_up)
# not using the actual camera dist ...
cam_light_dist = self._dist
sceneCam = self.getActiveSceneCamera()
renderer.SetRenderViewport(viewport)
renderer.SetWindowPolicy(self.computeWindowPolicy(cameraAspect))
if sceneCam:
# When using a USD camera, simply set it as the active camera.
# Window policy conformance is handled in the engine/hydra.
renderer.SetCameraPath(sceneCam.GetPath())
else:
# When using the free cam (which isn't currently backed on the
# USD stage), we send the camera matrices to the engine.
renderer.SetCameraState(frustum.ComputeViewMatrix(),
frustum.ComputeProjectionMatrix())
viewProjectionMatrix = Gf.Matrix4f(frustum.ComputeViewMatrix()
* frustum.ComputeProjectionMatrix())
GL.glViewport(*windowViewport)
GL.glClear(GL.GL_COLOR_BUFFER_BIT|GL.GL_DEPTH_BUFFER_BIT)
# ensure viewport is right for the camera framing
GL.glViewport(*viewport)
# Set the clipping planes.
self._renderParams.clipPlanes = [Gf.Vec4d(i) for i in
gfCamera.clippingPlanes]
if len(self._dataModel.selection.getLCDPrims()) > 0:
sceneAmbient = (0.01, 0.01, 0.01, 1.0)
material = Glf.SimpleMaterial()
lights = []
# for renderModes that need lights
if self._dataModel.viewSettings.renderMode in ShadedRenderModes:
# ambient light located at the camera
if self._dataModel.viewSettings.ambientLightOnly:
l = Glf.SimpleLight()
l.ambient = (0, 0, 0, 0)
l.position = (cam_pos[0], cam_pos[1], cam_pos[2], 1)
lights.append(l)
# Default Dome Light
if self._dataModel.viewSettings.domeLightEnabled:
l = Glf.SimpleLight()
l.isDomeLight = True
if self._stageIsZup:
l.transform = Gf.Matrix4d().SetRotate(
Gf.Rotation(Gf.Vec3d.XAxis(), 90))
lights.append(l)
kA = self._dataModel.viewSettings.defaultMaterialAmbient
kS = self._dataModel.viewSettings.defaultMaterialSpecular
material.ambient = (kA, kA, kA, 1.0)
material.specular = (kS, kS, kS, 1.0)
material.shininess = 32.0
# modes that want no lighting simply leave lights as an empty list
renderer.SetLightingState(lights, material, sceneAmbient)
if self._dataModel.viewSettings.renderMode == RenderModes.HIDDEN_SURFACE_WIREFRAME:
GL.glEnable( GL.GL_POLYGON_OFFSET_FILL )
GL.glPolygonOffset( 1.0, 1.0 )
GL.glPolygonMode( GL.GL_FRONT_AND_BACK, GL.GL_FILL )
self.renderSinglePass(
UsdImagingGL.DrawMode.DRAW_GEOM_ONLY, False)
GL.glDisable( GL.GL_POLYGON_OFFSET_FILL )
# Use display space for the second clear because we
# composite the framebuffer contents with the
# color-corrected (i.e., display space) aov contents.
clearColor = Gf.Vec4f(self._dataModel.viewSettings.clearColor)
GL.glClearColor(*clearColor)
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
highlightMode = self._dataModel.viewSettings.selHighlightMode
if self._dataModel.playing:
# Highlight mode must be ALWAYS to draw highlights during playback.
drawSelHighlights = (
highlightMode == SelectionHighlightModes.ALWAYS)
else:
# Highlight mode can be ONLY_WHEN_PAUSED or ALWAYS to draw
# highlights when paused.
drawSelHighlights = (
highlightMode != SelectionHighlightModes.NEVER)
self.renderSinglePass(
self._renderModeDict[self._dataModel.viewSettings.renderMode],
drawSelHighlights)
if not UsdImagingGL.Engine.IsColorCorrectionCapable():
GL.glDisable(GL_FRAMEBUFFER_SRGB_EXT)
self.DrawAxis(viewProjectionMatrix)
# XXX:
# Draw camera guides-- no support for toggling guide visibility on
# individual cameras until we move this logic directly into
# usdImaging.
if self._dataModel.viewSettings.displayCameraOracles:
self.DrawCameraGuides(viewProjectionMatrix)
if self._dataModel.viewSettings.showBBoxes and\
(self._dataModel.viewSettings.showBBoxPlayback or not self._dataModel.playing):
self.DrawBBox(viewProjectionMatrix)
else:
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
if self._dataModel.viewSettings.showHUD_GPUstats:
self._glPrimitiveGeneratedQuery.End()
self._glTimeElapsedQuery.End()
# reset the viewport for 2D and HUD drawing
uiTasks = [ Prim2DSetupTask(self.computeWindowViewport()) ]
if self._dataModel.viewSettings.showMask:
color = self._dataModel.viewSettings.cameraMaskColor
if self._dataModel.viewSettings.showMask_Opaque:
color = color[0:3] + (1.0,)
else:
color = color[0:3] + (color[3] * 0.45,)
self._mask.updateColor(color)
self._mask.updatePrims(cameraViewport, self)
uiTasks.append(self._mask)
if self._dataModel.viewSettings.showMask_Outline:
self._maskOutline.updatePrims(cameraViewport, self)
uiTasks.append(self._maskOutline)
if self.showReticles:
color = self._dataModel.viewSettings.cameraReticlesColor
color = color[0:3] + (color[3] * 0.85,)
self._reticles.updateColor(color)
self._reticles.updatePrims(cameraViewport, self,
self._dataModel.viewSettings.showReticles_Inside, self._dataModel.viewSettings.showReticles_Outside)
uiTasks.append(self._reticles)
for task in uiTasks:
task.Sync(None)
for task in uiTasks:
task.Execute(None)
# check current state of renderer -- (not IsConverged()) means renderer is running
if self._renderStopState and (not renderer.IsConverged()):
self._renderStopState = False
# ### DRAW HUD ### #
if self._dataModel.viewSettings.showHUD:
self.drawHUD(renderer)
if (not self._dataModel.playing) & (not renderer.IsConverged()):
QtCore.QTimer.singleShot(5, self.update)
except Tf.ErrorException as e:
# If we encounter an error during a render, we want to continue
# running. Just log the error and continue.
sys.stderr.write(
"ERROR: Usdview encountered an error while rendering."
"{}\n".format(e))
finally:
# Make sure not to leak a reference to the renderer
renderer = None
def drawHUD(self, renderer):
# compute the time it took to render this frame,
# so we can display it in the HUD
ms = self._renderTime * 1000.
fps = float("inf")
if not self._renderTime == 0:
fps = 1./self._renderTime
# put the result in the HUD string
self.fpsHUDInfo['Render'] = "%.2f ms (%.2f FPS)" % (ms, fps)
col = Gf.Vec3f(.733,.604,.333)
# the subtree info does not update while animating, grey it out
if not self._dataModel.playing:
subtreeCol = col
else:
subtreeCol = Gf.Vec3f(.6,.6,.6)
# Subtree Info
if self._dataModel.viewSettings.showHUD_Info:
self._hud.updateGroup("TopLeft", 0, 14, subtreeCol,
self.upperHUDInfo,
self.HUDStatKeys)
else:
self._hud.updateGroup("TopLeft", 0, 0, subtreeCol, {})
# Complexity
if self._dataModel.viewSettings.showHUD_Complexity:
# Camera name
camName = "Free%s" % (" AutoClip" if self.autoClip else "")
if self._dataModel.viewSettings.cameraPrim:
camName = self._dataModel.viewSettings.cameraPrim.GetName()
toPrint = {"Complexity" : self._dataModel.viewSettings.complexity.name,
"Camera" : camName}
self._hud.updateGroup("BottomRight",
self.width()-210, self.height()-self._hud._HUDLineSpacing*2,
col, toPrint)
else:
self._hud.updateGroup("BottomRight", 0, 0, col, {})
# Hydra Enabled (Top Right)
hydraMode = "Disabled"
if UsdImagingGL.Engine.IsHydraEnabled():
hydraMode = self._rendererDisplayName
if not hydraMode:
hydraMode = "Enabled"
if self._renderPauseState:
toPrint = {"Hydra": "(paused)"}
elif self._renderStopState:
toPrint = {"Hydra": "(stopped)"}
else:
toPrint = {"Hydra": hydraMode}
if self._rendererAovName != "color":
toPrint[" AOV"] = self._rendererAovName
self._hud.updateGroup("TopRight", self.width()-160, 14, col,
toPrint, toPrint.keys())
# bottom left
from collections import OrderedDict
toPrint = OrderedDict()
# GPU stats (TimeElapsed is in nano seconds)
if self._dataModel.viewSettings.showHUD_GPUstats:
def _addSizeMetric(toPrint, stats, label, key):
if key in stats:
toPrint[label] = ReportMetricSize(stats[key])
rStats = renderer.GetRenderStats()
toPrint["GL prims "] = self._glPrimitiveGeneratedQuery.GetResult()
if not (self._renderPauseState or self._renderStopState):
toPrint["GPU time "] = "%.2f ms " % (self._glTimeElapsedQuery.GetResult() / 1000000.0)
_addSizeMetric(toPrint, rStats, "GPU mem ", "gpuMemoryUsed")
_addSizeMetric(toPrint, rStats, " primvar ", "primvar")
_addSizeMetric(toPrint, rStats, " topology", "topology")
_addSizeMetric(toPrint, rStats, " shader ", "drawingShader")
_addSizeMetric(toPrint, rStats, " texture ", "textureMemory")
if "numCompletedSamples" in rStats:
toPrint["Samples done "] = rStats["numCompletedSamples"]
# Playback Rate
if (not (self._renderPauseState or self._renderStopState)) and \
self._dataModel.viewSettings.showHUD_Performance:
for key in self.fpsHUDKeys:
toPrint[key] = self.fpsHUDInfo[key]
self._hud.updateGroup("BottomLeft",
0, self.height()-len(toPrint)*self._hud._HUDLineSpacing,
col, toPrint, toPrint.keys())
# draw HUD
self._hud.draw(self)
def sizeHint(self):
return QtCore.QSize(460, 460)
def switchToFreeCamera(self, computeAndSetClosestDistance=True):
"""
If our current camera corresponds to a prim, create a FreeCamera
that has the same view and use it.
"""
if self._dataModel.viewSettings.cameraPrim != None:
# cameraPrim may no longer be valid, so use the last-computed
# gf camera
if self._lastComputedGfCamera:
self._dataModel.viewSettings.freeCamera = FreeCamera.FromGfCamera(
self._lastComputedGfCamera, self._stageIsZup)
else:
self._dataModel.viewSettings.freeCamera = FreeCamera(
self._stageIsZup,
self._dataModel.viewSettings.freeCameraFOV)
# override clipping plane state is managed by StageView,
# so that it can be persistent. Therefore we must restore it
# now
self._dataModel.viewSettings.freeCamera.overrideNear = self._overrideNear
self._dataModel.viewSettings.freeCamera.overrideFar = self._overrideFar
self._dataModel.viewSettings.cameraPrim = None
if computeAndSetClosestDistance:
self.computeAndSetClosestDistance()
# let the controller know we've done this!
self.signalSwitchedToFreeCam.emit()
# It WBN to support marquee selection in the viewer also, at some point...
def mousePressEvent(self, event):
"""This widget claims the Alt modifier key as the enabler for camera
manipulation, and will consume mousePressEvents when Alt is present.
In any other modifier state, a mousePressEvent will result in a
pick operation, and the pressed button and active modifiers will be
made available to clients via a signalPrimSelected()."""
# It's important to set this first, since pickObject(), called below
# may produce the mouse-up event that will terminate the drag
# initiated by this mouse-press
self._dragActive = True
# Note: multiplying by devicePixelRatio is only necessary because this
# is a QGLWidget.
x = event.x() * self.devicePixelRatioF()
y = event.y() * self.devicePixelRatioF()
# Allow for either meta or alt key, since meta maps to Windows and Apple
# keys on various hardware/os combos, and some windowing systems consume
# one or the other by default, but hopefully not both.
if (event.modifiers() & (QtCore.Qt.AltModifier | QtCore.Qt.MetaModifier)):
if event.button() == QtCore.Qt.LeftButton:
self.switchToFreeCamera()
ctrlModifier = event.modifiers() & QtCore.Qt.ControlModifier
self._cameraMode = "truck" if ctrlModifier else "tumble"
if event.button() == QtCore.Qt.MidButton:
self.switchToFreeCamera()
self._cameraMode = "truck"
if event.button() == QtCore.Qt.RightButton:
self.switchToFreeCamera()
self._cameraMode = "zoom"
else:
self._cameraMode = "pick"
self.pickObject(x, y, event.button(), event.modifiers())
self._lastX = x
self._lastY = y
def mouseReleaseEvent(self, event):
self._cameraMode = "none"
self._dragActive = False
def mouseMoveEvent(self, event):
# Note: multiplying by devicePixelRatio is only necessary because this
# is a QGLWidget.
x = event.x() * self.devicePixelRatioF()
y = event.y() * self.devicePixelRatioF()
if self._dragActive:
dx = x - self._lastX
dy = y - self._lastY
if dx == 0 and dy == 0:
return
freeCam = self._dataModel.viewSettings.freeCamera
if self._cameraMode == "tumble":
freeCam.Tumble(0.25 * dx, 0.25*dy)
elif self._cameraMode == "zoom":
zoomDelta = -.002 * (dx + dy)
if freeCam.orthographic:
# orthographic cameras zoom by scaling fov
# fov is the height of the view frustum in world units
freeCam.fov *= (1 + zoomDelta)
else:
# perspective cameras dolly forward or back
freeCam.AdjustDistance(1 + zoomDelta)
elif self._cameraMode == "truck":
height = float(self.size().height())
pixelsToWorld = freeCam.ComputePixelsToWorldFactor(height)
self._dataModel.viewSettings.freeCamera.Truck(
-dx * pixelsToWorld,
dy * pixelsToWorld)
self._lastX = x
self._lastY = y
self.updateGL()
self.signalMouseDrag.emit()
elif self._cameraMode == "none":
# Mouse tracking is only enabled when rolloverPicking is enabled,
# and this function only gets called elsewise when mouse-tracking
# is enabled
self.pickObject(event.x(), event.y(), None, event.modifiers())
else:
event.ignore()
def wheelEvent(self, event):
self.switchToFreeCamera()
self._dataModel.viewSettings.freeCamera.AdjustDistance(
1-max(-0.5,min(0.5,(event.angleDelta().y()/1000.))))
self.updateGL()
def detachAndReClipFromCurrentCamera(self):
"""If we are currently rendering from a prim camera, switch to the
FreeCamera. Then reset the near/far clipping planes based on
distance to closest geometry."""
if not self._dataModel.viewSettings.freeCamera:
self.switchToFreeCamera()
else:
self.computeAndSetClosestDistance()
def computeAndSetClosestDistance(self):
'''Using the current FreeCamera's frustum, determine the world-space
closest rendered point to the camera. Use that point
to set our FreeCamera's closest visible distance.'''
# pick() operates at very low screen resolution, but that's OK for
# our purposes. Ironically, the same limited Z-buffer resolution for
# which we are trying to compensate may cause us to completely lose
# ALL of our geometry if we set the near-clip really small (which we
# want to do so we don't miss anything) when geometry is clustered
# closer to far-clip. So in the worst case, we may need to perform
# two picks, with the first pick() using a small near and far, and the
# second pick() using a near that keeps far within the safe precision
# range. We don't expect the worst-case to happen often.
if not self._dataModel.viewSettings.freeCamera:
return
cameraFrustum = self.resolveCamera()[0].frustum
trueFar = cameraFrustum.nearFar.max
smallNear = min(FreeCamera.defaultNear,
self._dataModel.viewSettings.freeCamera._selSize / 10.0)
cameraFrustum.nearFar = \
Gf.Range1d(smallNear, smallNear*FreeCamera.maxSafeZResolution)
pickResults = self.pick(cameraFrustum)
if pickResults[0] is None or pickResults[1] == Sdf.Path.emptyPath:
cameraFrustum.nearFar = \
Gf.Range1d(trueFar/FreeCamera.maxSafeZResolution, trueFar)
pickResults = self.pick(cameraFrustum)
if Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING):
print("computeAndSetClosestDistance: Needed to call pick() a second time")
if pickResults[0] is not None and pickResults[1] != Sdf.Path.emptyPath:
self._dataModel.viewSettings.freeCamera.setClosestVisibleDistFromPoint(pickResults[0])
self.updateView()
def pick(self, pickFrustum):
'''
Find closest point in scene rendered through 'pickFrustum'.
Returns a quintuple:
selectedPoint, selectedPrimPath, selectedInstancerPath,
selectedInstanceIndex, selectedInstancerContext
'''
renderer = self._getRenderer()
if not self._dataModel.stage or not renderer:
# error has already been issued
return None, Sdf.Path.emptyPath, None, None, None
# this import is here to make sure the create_first_image stat doesn't
# regress..
from OpenGL import GL
# Need a correct OpenGL Rendering context for FBOs
self.makeCurrent()
# update rendering parameters
self._renderParams.frame = self._dataModel.currentFrame
self._renderParams.complexity = self._dataModel.viewSettings.complexity.value
self._renderParams.drawMode = self._renderModeDict[self._dataModel.viewSettings.renderMode]
self._renderParams.showGuides = self._dataModel.viewSettings.displayGuide
self._renderParams.showProxy = self._dataModel.viewSettings.displayProxy
self._renderParams.showRender = self._dataModel.viewSettings.displayRender
self._renderParams.forceRefresh = self._forceRefresh
self._renderParams.cullStyle = \
(UsdImagingGL.CullStyle.CULL_STYLE_BACK_UNLESS_DOUBLE_SIDED
if self._dataModel.viewSettings.cullBackfaces
else UsdImagingGL.CullStyle.CULL_STYLE_NOTHING)
self._renderParams.gammaCorrectColors = False
self._renderParams.enableIdRender = True
self._renderParams.enableSampleAlphaToCoverage = False
self._renderParams.enableSceneMaterials = self._dataModel.viewSettings.enableSceneMaterials
results = renderer.TestIntersection(
pickFrustum.ComputeViewMatrix(),
pickFrustum.ComputeProjectionMatrix(),
self._dataModel.stage.GetPseudoRoot(), self._renderParams)
if Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING):
print("Pick results = {}".format(results))
return results
def computePickFrustum(self, x, y):
# compute pick frustum
(gfCamera, cameraAspect) = self.resolveCamera()
cameraFrustum = gfCamera.frustum
viewport = self.computeWindowViewport()
if self._cropImageToCameraViewport:
viewport = self.computeCameraViewport(cameraAspect)
# normalize position and pick size by the viewport size
point = Gf.Vec2d((x - viewport[0]) / float(viewport[2]),
(y - viewport[1]) / float(viewport[3]))
point[0] = (point[0] * 2.0 - 1.0)
point[1] = -1.0 * (point[1] * 2.0 - 1.0)
size = Gf.Vec2d(1.0 / viewport[2], 1.0 / viewport[3])
# "point" is normalized to the image viewport size, but if the image
# is cropped to the camera viewport, the image viewport won't fill the
# whole window viewport. Clicking outside the image will produce
# normalized coordinates > 1 or < -1; in this case, we should skip
# picking.
inImageBounds = (abs(point[0]) <= 1.0 and abs(point[1]) <= 1.0)
return (inImageBounds, cameraFrustum.ComputeNarrowedFrustum(point, size))
def pickObject(self, x, y, button, modifiers):
'''
Render stage into fbo with each piece as a different color.
Emits a signalPrimSelected or signalRollover depending on
whether 'button' is None.
'''
if not self._dataModel.stage:
return
renderer = self._getRenderer()
if not renderer:
# error has already been issued
return
try:
(inImageBounds, pickFrustum) = self.computePickFrustum(x,y)
if inImageBounds:
selectedPoint, selectedPrimPath, \
selectedInstanceIndex, selectedTLPath, selectedTLIndex = \
self.pick(pickFrustum)
else:
# If we're picking outside the image viewport (maybe because
# camera guides are on), treat that as a de-select.
selectedPoint, selectedPrimPath, \
selectedInstanceIndex, selectedTLPath, selectedTLIndex = \
None, Sdf.Path.emptyPath, -1, Sdf.Path.emptyPath, -1
# Correct for high DPI displays
coord = self._scaleMouseCoords( \
QtCore.QPoint(selectedPoint[0], selectedPoint[1]))
selectedPoint[0] = coord.x()
selectedPoint[1] = coord.y()
if button:
self.signalPrimSelected.emit(
selectedPrimPath, selectedInstanceIndex, selectedTLPath,
selectedTLIndex, selectedPoint, button, modifiers)
else:
self.signalPrimRollover.emit(
selectedPrimPath, selectedInstanceIndex, selectedTLPath,
selectedTLIndex, selectedPoint, modifiers)
except Tf.ErrorException as e:
# If we encounter an error, we want to continue running. Just log
# the error and continue.
sys.stderr.write(
"ERROR: Usdview encountered an error while picking."
"{}\n".format(e))
finally:
renderer = None
def glDraw(self):
# override glDraw so we can time it.
with Timer() as t:
QtOpenGL.QGLWidget.glDraw(self)
# Render creation is a deferred operation, so the render may not
# be initialized on entry to the function.
#
# This function itself can not create the render, as to create the
# renderer we need a valid GL context, which QT has not made current
# yet.
#
# So instead check that the render has been created after the fact.
# The point is to avoid reporting an invalid first image time.
if not self._renderer:
# error has already been issued
return
self._renderTime = t.interval
# If timings are being printed and this is the first time an image is
# being drawn, report how long it took to do so.
if self._printTiming and self._isFirstImage:
self._isFirstImage = False
t.PrintTime("create first image")
def SetForceRefresh(self, val):
self._forceRefresh = val or self._forceRefresh
def ExportFreeCameraToStage(self, stage, defcamName='usdviewCam',
imgWidth=None, imgHeight=None):
'''
Export the free camera to the specified USD stage, if it is
currently defined. If it is not active (i.e. we are viewing through
a stage camera), raise a ValueError.
'''
if not self._dataModel.viewSettings.freeCamera:
raise ValueError("StageView's Free Camera is not defined, so cannot"
" be exported")
imgWidth = imgWidth if imgWidth is not None else self.width()
imgHeight = imgHeight if imgHeight is not None else self.height()
defcam = UsdGeom.Camera.Define(stage, '/'+defcamName)
# Map free camera params to usd camera. We do **not** want to burn
# auto-clipping near/far into our exported camera
gfCamera = self._dataModel.viewSettings.freeCamera.computeGfCamera(self._bbox, autoClip=False)
targetAspect = float(imgWidth) / max(1.0, imgHeight)
CameraUtil.ConformWindow(
gfCamera, CameraUtil.MatchVertically, targetAspect)
when = (self._dataModel.currentFrame
if stage.HasAuthoredTimeCodeRange() else Usd.TimeCode.Default())
defcam.SetFromCamera(gfCamera, when)
def ExportSession(self, stagePath, defcamName='usdviewCam',
imgWidth=None, imgHeight=None):
'''
Export the free camera (if currently active) and session layer to a
USD file at the specified stagePath that references the current-viewed
stage.
'''
tmpStage = Usd.Stage.CreateNew(stagePath)
if self._dataModel.stage:
tmpStage.GetRootLayer().TransferContent(
self._dataModel.stage.GetSessionLayer())
if not self.cameraPrim:
# Export the free camera if it's the currently-visible camera
self.ExportFreeCameraToStage(tmpStage, defcamName, imgWidth,
imgHeight)
tmpStage.GetRootLayer().Save()
del tmpStage
# Reopen just the tmp layer, to sublayer in the pose cache without
# incurring Usd composition cost.
if self._dataModel.stage:
from pxr import Sdf
sdfLayer = Sdf.Layer.FindOrOpen(stagePath)
sdfLayer.subLayerPaths.append(
os.path.abspath(
self._dataModel.stage.GetRootLayer().realPath))
sdfLayer.Save()
def _primSelectionChanged(self):
# set highlighted paths to renderer
self.updateSelection()
self.update()
| 91,396 | Python | 38.531574 | 135 | 0.594687 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/__init__.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import sys, argparse, os
from .qt import QtWidgets, QtCore
from .common import Timer
from .appController import AppController
from pxr import UsdAppUtils, Tf
class InvalidUsdviewOption(Exception):
"""Raised when an invalid Usdview option is found in
Launcher.ValidateOptions or any methods which override it.
"""
pass
class Launcher(object):
'''
Base class for argument parsing, validation, and initialization for UsdView
Subclasses can choose to override
-- GetHelpDescription()
-- RegisterOptions()
-- ParseOptions()
-- ValidateOptions()
-- GetResolverContext()
'''
def __init__(self):
pass
def Run(self):
'''
The main entry point to launch a process using UsdView.
'''
parser = argparse.ArgumentParser(prog=sys.argv[0],
description=self.GetHelpDescription())
traceCollector = None
with Timer() as totalTimer:
self.RegisterPositionals(parser)
self.RegisterOptions(parser)
arg_parse_result = self.ParseOptions(parser)
self.ValidateOptions(arg_parse_result)
if arg_parse_result.traceToFile:
from pxr import Trace
traceCollector = Trace.Collector()
traceCollector.pythonTracingEnabled = True
traceCollector.enabled = True
self.__LaunchProcess(arg_parse_result)
if traceCollector:
traceCollector.enabled = False
if arg_parse_result.timing and arg_parse_result.quitAfterStartup:
totalTimer.PrintTime('open and close usdview')
if traceCollector:
if arg_parse_result.traceFormat == 'trace':
Trace.Reporter.globalReporter.Report(
arg_parse_result.traceToFile)
elif arg_parse_result.traceFormat == 'chrome':
Trace.Reporter.globalReporter.ReportChromeTracingToFile(
arg_parse_result.traceToFile)
else:
Tf.RaiseCodingError("Invalid trace format option provided: %s -"
"trace/chrome are the valid options" %
arg_parse_result.traceFormat)
def GetHelpDescription(self):
'''return the help description'''
return 'View a usd file'
def RegisterPositionals(self, parser):
'''
register positional arguments on the ArgParser
'''
parser.add_argument('usdFile', action='store',
type=str,
help='The file to view')
def RegisterOptions(self, parser):
'''
register optional arguments on the ArgParser
'''
from pxr import UsdUtils
parser.add_argument('--renderer', action='store',
type=str, dest='renderer',
choices=AppController.GetRendererOptionChoices(),
help="Which render backend to use (named as it "
"appears in the menu). Use '%s' to "
"turn off Hydra renderers." %
AppController.HYDRA_DISABLED_OPTION_STRING,
default='')
parser.add_argument('--select', action='store', default='/',
dest='primPath', type=str,
help='A prim path to initially select and frame')
UsdAppUtils.cameraArgs.AddCmdlineArgs(parser,
altHelpText=(
"Which camera to set the view to on open - may be given as "
"either just the camera's prim name (ie, just the last "
"element in the prim path), or as a full prim path. Note "
"that if only the prim name is used, and more than one camera "
"exists with the name, which is used will be effectively "
"random (default=%(default)s)"))
parser.add_argument('--mask', action='store',
dest='populationMask',
metavar='PRIMPATH[,PRIMPATH...]',
help='Limit stage population to these prims, '
'their descendants and ancestors. To specify '
'multiple paths, either use commas with no spaces '
'or quote the argument and separate paths by '
'commas and/or spaces.')
parser.add_argument('--clearsettings', action='store_true',
dest='clearSettings',
help='Restores usdview settings to default')
parser.add_argument('--defaultsettings', action='store_true',
dest='defaultSettings',
help='Launch usdview with default settings')
parser.add_argument('--norender', action='store_true',
dest='noRender',
help='Display only hierarchy browser')
parser.add_argument('--noplugins', action='store_true',
dest='noPlugins',
help='Do not load plugins')
parser.add_argument('--unloaded', action='store_true',
dest='unloaded',
help='Do not load payloads')
parser.add_argument('--timing', action='store_true',
dest='timing',
help='Echo timing stats to console. NOTE: timings will be unreliable when the --mallocTagStats option is also in use')
parser.add_argument('--traceToFile', action='store',
type=str,
dest='traceToFile',
default=None,
help='Start tracing at application startup and '
'write --traceFormat specified format output to the '
'specified trace file when the application quits')
parser.add_argument('--traceFormat', action='store',
type=str,
dest='traceFormat',
default='chrome',
choices=['chrome', 'trace'],
help='Output format for trace file specified by '
'--traceToFile. \'chrome\' files can be read in '
'chrome, \'trace\' files are simple text reports. '
'(default=%(default)s)')
parser.add_argument('--memstats', action='store', default='none',
dest='mallocTagStats', type=str,
choices=['none', 'stage', 'stageAndImaging'],
help='Use the Pxr MallocTags memory accounting system to profile USD, saving results to a tmp file, with a summary to the console. Will have no effect if MallocTags are not supported in the USD installation.')
parser.add_argument('--numThreads', action='store',
type=int, default=0,
help='Number of threads used for processing'
'(0 is max, negative numbers imply max - N)')
parser.add_argument('--ff', action='store',
dest='firstframe', type=int,
help='Set the first frame of the viewer')
parser.add_argument('--lf', action='store',
dest='lastframe', type=int,
help='Set the last frame of the viewer')
parser.add_argument('--cf', action='store',
dest='currentframe', type=int,
help='Set the current frame of the viewer')
UsdAppUtils.complexityArgs.AddCmdlineArgs(parser,
altHelpText=(
'Set the initial mesh refinement complexity (%(default)s).'))
parser.add_argument('--quitAfterStartup', action='store_true',
dest='quitAfterStartup',
help='quit immediately after start up')
parser.add_argument('--sessionLayer', default=None, type=str,
help= "If specified, the stage will be opened "
"with the 'sessionLayer' in place of the default "
"anonymous layer. As this changes the session "
"layer from anonymous to persistent, be "
"aware that layers saved from Export Overrides "
"will include the opinions in the persistent "
"session layer.")
def ParseOptions(self, parser):
'''
runs the parser on the arguments
'''
return parser.parse_args()
def ValidateOptions(self, arg_parse_result):
'''
Called by Run(), after ParseOptions() is called. Validates and
potentially modifies the parsed arguments. Raises InvalidUsdviewOption
if an invalid option is found. If a derived class has overridden
ParseOptions(), ValidateOptions() is an opportunity to process the
options and transmute other "core" options in response. If
overridden, derived classes should likely first call the base method.
'''
# split arg_parse_result.populationMask into paths.
if arg_parse_result.populationMask:
arg_parse_result.populationMask = (
arg_parse_result.populationMask.replace(',', ' ').split())
# Verify that the camera path is either an absolute path, or is just
# the name of a camera.
if arg_parse_result.camera:
camPath = arg_parse_result.camera
if camPath.isEmpty:
raise InvalidUsdviewOption(
"invalid camera path - %r" % camPath)
if not camPath.IsPrimPath():
raise InvalidUsdviewOption(
"invalid camera path - must be a raw prim path with no "
"variant selections or properties - got: %r" % camPath)
# If it's a multi-element path, make sure it is absolute.
if camPath.pathElementCount > 1:
if not camPath.IsAbsolutePath():
# perhaps we should error here? For now just pre-pending
# root, and printing warning...
from pxr import Sdf
print("WARNING: camera path %r was not absolute, prepending "
"%r to make it absolute" % (str(camPath),
str(Sdf.Path.absoluteRootPath)), file=sys.stderr)
arg_parse_result.camera = camPath.MakeAbsolutePath(
Sdf.Path.absoluteRootPath)
if arg_parse_result.clearSettings and arg_parse_result.defaultSettings:
raise InvalidUsdviewOption(
"cannot supply both --clearsettings and --defaultsettings.")
def GetResolverContext(self, usdFile):
"""
Create and return the ArResolverContext that will be used to Open
the Stage for the given usdFile. Base implementation
creates a default asset context for the usdFile asset, but derived
classes can do more sophisticated resolver and context configuration.
Will be called each time a new stage is opened.
It is not necessary to create an ArResolverContext for every UsdStage
one opens, as the Stage will use reasonable fallback behavior if no
context is provided. For usdview, configuring an asset context by
default is reasonable, and allows clients that embed usdview to
achieve different behavior when needed.
"""
from pxr import Ar
r = Ar.GetResolver()
r.ConfigureResolverForAsset(usdFile)
return r.CreateDefaultContextForAsset(usdFile)
def LaunchPreamble(self, arg_parse_result):
# Initialize concurrency limit as early as possible so that it is
# respected by subsequent imports.
from pxr import Work
Work.SetConcurrencyLimitArgument(arg_parse_result.numThreads)
if arg_parse_result.clearSettings:
AppController.clearSettings()
# Create the Qt application
app = QtWidgets.QApplication(sys.argv)
contextCreator = lambda usdFile: self.GetResolverContext(usdFile)
appController = AppController(arg_parse_result, contextCreator)
return (app, appController)
def __LaunchProcess(self, arg_parse_result):
'''
after the arguments have been parsed, launch the UI in a forked process
'''
# Initialize concurrency limit as early as possible so that it is
# respected by subsequent imports.
(app, appController) = self.LaunchPreamble(arg_parse_result)
if arg_parse_result.quitAfterStartup:
# Enqueue event to shutdown application. We don't use quit() because
# it doesn't trigger the closeEvent() on the main window which is
# used to orchestrate the shutdown.
QtCore.QTimer.singleShot(0, app.instance().closeAllWindows)
app.exec_()
| 14,564 | Python | 42.607784 | 238 | 0.572164 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/debugFlagsWidget.py | #
# Copyright 2019 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from pxr import Tf
# Returns a list of debug flags whose names are prefixed by debugFlagPrefix
# followed by an '_'.
#
def _GetDebugFlagsWithPrefix(debugFlagPrefix):
debugFlagPrefix += "_"
return [flag for flag in Tf.Debug.GetDebugSymbolNames()
if flag.startswith(debugFlagPrefix)]
# Main DebugFlags editor widget
#
class DebugFlagsWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(DebugFlagsWidget, self).__init__(parent)
self.setObjectName("Debug Flags")
self.setMinimumSize(640, 300)
self._listView = QtWidgets.QListView()
self._tableWidget = QtWidgets.QTableWidget(0, 2)
# Configure and populate the left list view
self._listView.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self._populateDebugFlagsListView(self._listView)
self._listView.selectionModel().selectionChanged.connect(
self._onFlagSelectionChanged)
# Configure the table widget
self._tableWidget.horizontalHeader().setStretchLastSection(True)
self._tableWidget.horizontalHeader().setDefaultSectionSize(200)
self._tableWidget.setHorizontalHeaderLabels(
['Debug Symbol', 'Description'])
self._tableWidget.verticalHeader().hide()
self._tableWidget.itemClicked.connect(self._onDebugFlagChecked)
# Set the layout
lay = QtWidgets.QHBoxLayout()
lay.addWidget(self._listView, 0)
lay.addWidget(self._tableWidget, 1)
self.setLayout(lay)
def _populateDebugFlagsListView(self, listView):
allDebugFlags = Tf.Debug.GetDebugSymbolNames()
allDebugPrefixes = [ x[:x.find('_')] if x.find('_') > 0 else x
for x in allDebugFlags]
self._allDebugFlagPrefixes = list(sorted(set(allDebugPrefixes)))
listModel = QtCore.QStringListModel(self._allDebugFlagPrefixes)
listView.setModel(listModel)
def _populateDebugFlagsTableView(self, debugFlagPrefix):
debugFlags = _GetDebugFlagsWithPrefix(debugFlagPrefix)
self._tableWidget.setRowCount(len(debugFlags))
row = 0
for f in debugFlags:
item = QtWidgets.QTableWidgetItem()
item.setFlags(QtCore.Qt.ItemIsUserCheckable |
QtCore.Qt.ItemIsEnabled)
if Tf.Debug.IsDebugSymbolNameEnabled(f):
item.setCheckState(QtCore.Qt.Checked)
else:
item.setCheckState(QtCore.Qt.Unchecked)
item.setText(f)
self._tableWidget.setItem(row, 0, item)
item = QtWidgets.QTableWidgetItem()
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
item.setText(Tf.Debug.GetDebugSymbolDescription(f))
self._tableWidget.setItem(row, 1, item)
row += 1
def _onFlagSelectionChanged(self, selected, deselected):
if len(selected.indexes()) > 0:
self._populateDebugFlagsTableView(self._allDebugFlagPrefixes[
selected.indexes()[0].row()])
def _onDebugFlagChecked(self, item):
value = (item.checkState() == QtCore.Qt.Checked)
Tf.Debug.SetDebugSymbolsByName(item.text(), value)
| 4,363 | Python | 36.947826 | 75 | 0.678891 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primLegend.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtWidgets
from .primLegendUI import Ui_PrimLegend
from .common import (UIPrimTypeColors,
ColorizeLabelText, BoldenLabelText, ItalicizeLabelText)
class PrimLegend(QtWidgets.QWidget):
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
self._ui = Ui_PrimLegend()
self._ui.setupUi(self)
# start out in a minimized/hidden state
self.setMaximumHeight(0)
self._isMinimized = True
graphicsScene = QtWidgets.QGraphicsScene()
# Set colors
self._ui.primLegendColorHasArcs.setScene(graphicsScene)
self._ui.primLegendColorNormal.setScene(graphicsScene)
self._ui.primLegendColorInstance.setScene(graphicsScene)
self._ui.primLegendColorMaster.setScene(graphicsScene)
self._ui.primLegendColorHasArcs.setForegroundBrush(UIPrimTypeColors.HAS_ARCS)
self._ui.primLegendColorNormal.setForegroundBrush(UIPrimTypeColors.NORMAL)
self._ui.primLegendColorInstance.setForegroundBrush(UIPrimTypeColors.INSTANCE)
self._ui.primLegendColorMaster.setForegroundBrush(UIPrimTypeColors.MASTER)
legendTextUpdate = lambda t, c: (('<font color=\"%s\">' % c.color().name())
+ t.text() + '</font>')
normalLegend = self._ui.primLegendLabelNormal
normalLegend.setText(legendTextUpdate(normalLegend, UIPrimTypeColors.NORMAL))
masterLegend = self._ui.primLegendLabelMaster
masterLegend.setText(legendTextUpdate(masterLegend, UIPrimTypeColors.MASTER))
instanceLegend = self._ui.primLegendLabelInstance
instanceLegend.setText(legendTextUpdate(instanceLegend, UIPrimTypeColors.INSTANCE))
hasArcsLegend = self._ui.primLegendLabelHasArcs
hasArcsLegend.setText(legendTextUpdate(hasArcsLegend, UIPrimTypeColors.HAS_ARCS))
undefinedFontLegend = self._ui.primLegendLabelFontsUndefined
undefinedFontLegend.setText(ItalicizeLabelText(undefinedFontLegend.text(),
undefinedFontLegend.text()))
definedFontLegend = self._ui.primLegendLabelFontsDefined
definedFontLegend.setText(BoldenLabelText(definedFontLegend.text(),
definedFontLegend.text()))
# Set three individual colors in the text line to indicate
# the dimmed version of each primary prim color
dimmedLegend = self._ui.primLegendLabelDimmed
dimmedLegendText = dimmedLegend.text()
dimmedLegendText = ColorizeLabelText(
dimmedLegendText, "Dimmed colors", 148, 105, 30)
dimmedLegendText = ColorizeLabelText(
dimmedLegendText, "denote", 78, 91, 145)
dimmedLegendText = ColorizeLabelText(
dimmedLegendText, "inactive prims", 151, 151, 151)
dimmedLegend.setText(dimmedLegendText)
def IsMinimized(self):
return self._isMinimized
def ToggleMinimized(self):
self._isMinimized = not self._isMinimized
def GetHeight(self):
return self.height()
def GetResetHeight(self):
return self.sizeHint().height()
| 4,258 | Python | 41.59 | 91 | 0.700798 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/arrayAttributeView.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
def _GetLengthOfRange(start, stop, step):
if step == 0:
return 0
k = 1 if step > 0 else -1
num = 1 + (stop - k - start) // step
# note, sign(stop - start) != sign(step) when we have an empty range. In those
# cases, "num" ends up non-positive, so we can just take the max(num, 0)
return max(0, num)
class _ArrayAttributeModel(QtCore.QAbstractListModel):
'''This is a data model that represents a slice into some array data.
'''
RawDataRole = QtCore.Qt.UserRole + 0
def __init__(self):
super(_ArrayAttributeModel, self).__init__()
self._arrayData = None
self._scalarTypeName = ""
self._slice = slice(None)
self._fetchMoreTimer = QtCore.QTimer()
self._fetchMoreTimer.setInterval(1000)
self._fetchMoreTimer.timeout.connect(self.TryToFetchMore)
self._fetchMoreTimer.start()
self._rowCount = 0
self._publishedRows = 0
def SetArrayDataAndTypeName(self, arrayData, scalarTypeName):
self._arrayData = arrayData
self._scalarTypeName = scalarTypeName
self._Reset()
def SetSlice(self, slice_):
if self._slice == slice_:
return
self._slice = slice_
self._Reset()
def _Reset(self):
self._publishedRows = 0
self._rowCount = 0
if self._arrayData is not None:
self._rowCount = _GetLengthOfRange(*self._slice.indices(len(self._arrayData)))
self.modelReset.emit()
def GetArrayData(self):
return self._arrayData
def GetScalarTypeName(self):
return self._scalarTypeName
def index(self, row, col, parent=QtCore.QModelIndex()):
return self.createIndex(row, col)
def parent(self, index):
return QtCore.QModelIndex()
def rowCount(self, parent=QtCore.QModelIndex()):
if not parent.isValid():
return self._publishedRows
return 0
def columnCount(self, parent=QtCore.QModelIndex()):
return 1
def data(self, index, role=QtCore.Qt.DisplayRole):
start, _, step = self._slice.indices(len(self._arrayData))
idx = start + index.row() * step
dataVal = self._arrayData[idx]
if role == QtCore.Qt.DisplayRole:
from .scalarTypes import ToString
return str(idx) + ": " + ToString(
dataVal, self._scalarTypeName)
elif role == _ArrayAttributeModel.RawDataRole:
return dataVal
return None
def fetchMore(self, index):
left = self._rowCount - self._publishedRows
toFetch = min(5000 if self._publishedRows == 0 else 100, left)
self.beginInsertRows(
index, self._publishedRows, self._publishedRows + toFetch - 1)
self._publishedRows += toFetch
self.endInsertRows()
def canFetchMore(self, index):
return self._publishedRows < self._rowCount
def TryToFetchMore(self):
rootIndex = QtCore.QModelIndex()
if self.canFetchMore(rootIndex):
self.fetchMore(rootIndex)
class ArrayAttributeView(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ArrayAttributeView, self).__init__(parent)
layout = QtWidgets.QVBoxLayout()
self.setLayout(layout)
sliceLayout = QtWidgets.QHBoxLayout()
layout.addLayout(sliceLayout)
sliceLayout.addWidget(QtWidgets.QLabel("Slice:"))
self._lineEdit = _SliceLineEdit()
self._lineEdit.setPlaceholderText('e.g.: "0:5000", "::-1"')
sliceLayout.addWidget(self._lineEdit)
self._arrayAttrModel = _ArrayAttributeModel()
self._listView = QtWidgets.QListView()
self._listView.setUniformItemSizes(True)
self._listView.setViewMode(QtWidgets.QListView.ListMode)
self._listView.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self._listView.setModel(self._arrayAttrModel)
layout.addWidget(self._listView)
self._lineEdit.SliceChanged.connect(self._arrayAttrModel.SetSlice)
self._SetupContextMenu()
def SetAttribute(self, attr, frame):
from .scalarTypes import GetScalarTypeFromAttr
arrayData = attr.Get(frame)
scalarTypeName, _ = GetScalarTypeFromAttr(attr)
self._arrayAttrModel.SetArrayDataAndTypeName(arrayData, scalarTypeName)
def CanView(self, attr):
return attr.GetTypeName().isArray
def keyPressEvent(self, e):
# XXX note, this is extremely finicky. it does not really
# have keyboard focus.
if e.matches(QtGui.QKeySequence.Copy):
self.Copy()
else:
return super(ArrayAttributeView, self).keyPressEvent(e)
# context menu stuff
def _SetupContextMenu(self):
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self._ShowContextMenu)
def _ShowContextMenu(self, point):
menu = QtWidgets.QMenu(self)
if self._listView.selectedIndexes():
menu.addAction("Copy Selected", self.CopySelected)
else:
menu.addAction("Copy All", self.CopyAll)
menu.addAction("Select All", self.SelectAll)
menu.exec_(QtGui.QCursor.pos())
def CopyAll(self):
self._CopyValsToClipboard(self._arrayAttrModel.GetArrayData())
def CopySelected(self):
selectedIndexes = self._listView.selectedIndexes()
self._CopyValsToClipboard([
self._listView.model().data(idx, _ArrayAttributeModel.RawDataRole)
for idx in selectedIndexes])
def _CopyValsToClipboard(self, vals):
from .scalarTypes import ToClipboard
scalarTypeName = self._arrayAttrModel.GetScalarTypeName()
copyText = "[ %s ]" % (", ".join(
ToClipboard(val, scalarTypeName)
for val in vals))
QtWidgets.QApplication.clipboard().setText(copyText)
def SelectAll(self):
self._listView.selectAll()
def _IntOrNone(s):
if not s:
return None
return int(s)
def _GetSliceFromString(s):
s = slice(*map(_IntOrNone, s.split(':')))
if s.step == 0:
raise ValueError("Slice cannot be 0")
return s
class _SliceLineEdit(QtWidgets.QLineEdit):
"""LineEdit for inputing strings that represent slices"""
SliceChanged = QtCore.Signal(object)
def __init__(self, parent=None):
super(_SliceLineEdit, self).__init__(parent)
self.setValidator(_SliceLineEdit.Validator())
self.editingFinished.connect(self._OnEditingFinished)
class Validator(QtGui.QValidator):
def validate(self, s, pos):
s = s.strip()
try:
_GetSliceFromString(s)
return (QtGui.QValidator.Acceptable, s, pos)
except:
return (QtGui.QValidator.Intermediate, s, pos)
def setText(self, t):
super(_SliceLineEdit, self).setText(t)
self._OnEditingFinished()
def _OnEditingFinished(self):
self.SliceChanged.emit(_GetSliceFromString(self.text()))
| 8,189 | Python | 32.292683 | 90 | 0.651728 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/scalarTypes.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
def GetScalarTypeFromAttr(attr):
'''
returns the (scalar, isArray) where isArray is True if it was an array type
'''
# Usd.Attribute and customAttributes.CustomAttribute have a
# GetTypeName function, while Sdf.AttributeSpec has a typeName attr.
if hasattr(attr, 'GetTypeName'):
typeName = attr.GetTypeName()
elif hasattr(attr, 'typeName'):
typeName = attr.typeName
else:
typeName = ""
from pxr import Sdf
if isinstance(typeName, Sdf.ValueTypeName):
return typeName.scalarType, typeName.isArray
else:
return None, False
_toStringFnCache = {}
def ToString(v, valueType=None):
"""Returns a string representing a "detailed view" of the value v.
This string is used in the watch window"""
from pxr import Tf, Gf
global _toStringFnCache
# Check cache.
t = type(v)
cacheKey = (t, valueType)
fn = _toStringFnCache.get(cacheKey)
if fn:
return fn(v)
# Cache miss. Compute string typeName for the given value
# using the given valueType as a hint.
typeName = ""
from pxr import Sdf
if isinstance(valueType, Sdf.ValueTypeName):
tfType = valueType.type
else:
tfType = Tf.Type.Find(t)
if tfType != Tf.Type.Unknown:
typeName = tfType.typeName
# Pretty-print "None"
if v is None:
fn = lambda _: 'None'
# Pretty-print a bounding box
elif isinstance(v, Gf.BBox3d):
def bboxToString(v):
prettyMatrix = (
"%s\n%s\n%s\n%s" %
(v.matrix[0], v.matrix[1],
v.matrix[2], v.matrix[3])).replace("(","").replace(")","")
result = ("Endpts of box diagonal:\n"
"%s\n%s\n\nTransform matrix:\n%s\n"
% (v.box.GetCorner(0), v.box.GetCorner(7), prettyMatrix))
if (v.hasZeroAreaPrimitives):
result += "\nHas zero-area primitives\n"
else:
result += "\nDoes not have zero-area primitives\n"
worldSpaceRange = Gf.Range3d()
worldSpaceRange.UnionWith(v.matrix.Transform(v.GetRange().GetMin()))
worldSpaceRange.UnionWith(v.matrix.Transform(v.GetRange().GetMax()))
result += "\nWorld-space range:\n%s\n%s\n" % \
(worldSpaceRange.GetMin(), worldSpaceRange.GetMax())
return result
fn = lambda b: bboxToString(b)
# Pretty-print a GfMatrix*
elif typeName.startswith("GfMatrix"):
def matrixToString(v):
result = ""
numRows = int(typeName[8])
for i in range(numRows):
result += str(v[i]) + "\n"
result = result.replace("(","").replace(")","")
return result
fn = lambda m: matrixToString(m)
# Pretty-print a GfVec* or a GfRange*
elif typeName.startswith("GfVec") or typeName.startswith("GfRange"):
fn = lambda v: str(v)
# pretty print an int
elif isinstance(v, int):
fn = lambda i: "{:,d}".format(i)
# pretty print a float
elif isinstance(v, float):
fn = lambda f: "{:,.6f}".format(f)
# print a string as-is
elif isinstance(v, str):
fn = lambda s: s
else:
import pprint
fn = lambda v: pprint.pformat(v)
# Populate cache and invoke function to produce the string.
_toStringFnCache[cacheKey] = fn
return fn(v)
def ToClipboard(v, typeName=None):
# XXX: we can have this give you the repr
return ToString(v, typeName)
| 4,632 | Python | 32.572464 | 80 | 0.622409 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/preferencesUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'preferencesUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_Preferences(object):
def setupUi(self, Preferences):
if not Preferences.objectName():
Preferences.setObjectName(u"Preferences")
Preferences.resize(295, 99)
self.verticalLayout = QVBoxLayout(Preferences)
self.verticalLayout.setObjectName(u"verticalLayout")
self.prefsOverButtonsLayout = QVBoxLayout()
self.prefsOverButtonsLayout.setObjectName(u"prefsOverButtonsLayout")
self.horizontalLayout_3 = QHBoxLayout()
self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
self.fontSizeLabel = QLabel(Preferences)
self.fontSizeLabel.setObjectName(u"fontSizeLabel")
self.horizontalLayout_3.addWidget(self.fontSizeLabel)
self.fontSizeSpinBox = QSpinBox(Preferences)
self.fontSizeSpinBox.setObjectName(u"fontSizeSpinBox")
self.fontSizeSpinBox.setMinimum(6)
self.fontSizeSpinBox.setValue(10)
self.horizontalLayout_3.addWidget(self.fontSizeSpinBox)
self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(self.horizontalSpacer_2)
self.prefsOverButtonsLayout.addLayout(self.horizontalLayout_3)
self.verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
self.prefsOverButtonsLayout.addItem(self.verticalSpacer)
self.line = QFrame(Preferences)
self.line.setObjectName(u"line")
self.line.setFrameShape(QFrame.HLine)
self.line.setFrameShadow(QFrame.Sunken)
self.prefsOverButtonsLayout.addWidget(self.line)
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(self.horizontalSpacer)
self.buttonBox = QDialogButtonBox(Preferences)
self.buttonBox.setObjectName(u"buttonBox")
self.buttonBox.setStandardButtons(QDialogButtonBox.Apply|QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
self.horizontalLayout_2.addWidget(self.buttonBox)
self.prefsOverButtonsLayout.addLayout(self.horizontalLayout_2)
self.verticalLayout.addLayout(self.prefsOverButtonsLayout)
self.retranslateUi(Preferences)
QMetaObject.connectSlotsByName(Preferences)
# setupUi
def retranslateUi(self, Preferences):
Preferences.setWindowTitle(QCoreApplication.translate("Preferences", u"Preferences", None))
Preferences.setProperty("comment", QCoreApplication.translate("Preferences", u"\n"
" Copyright 2020 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
self.fontSizeLabel.setText(QCoreApplication.translate("Preferences", u"Font Size", None))
# retranslateUi
| 5,326 | Python | 47.427272 | 109 | 0.58374 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/appController.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
# Qt Components
from .qt import QtCore, QtGui, QtWidgets
# Stdlib components
import re, sys, os, cProfile, pstats, traceback
from itertools import groupby
from time import time, sleep
from collections import deque, OrderedDict
from functools import cmp_to_key
# Usd Library Components
from pxr import Usd, UsdGeom, UsdShade, UsdUtils, UsdImagingGL, Glf, Sdf, Tf, Ar
from pxr import UsdAppUtils
from pxr.UsdAppUtils.complexityArgs import RefinementComplexities
# UI Components
from ._usdviewq import Utils
from .stageView import StageView
from .mainWindowUI import Ui_MainWindow
from .primContextMenu import PrimContextMenu
from .headerContextMenu import HeaderContextMenu
from .layerStackContextMenu import LayerStackContextMenu
from .attributeViewContextMenu import AttributeViewContextMenu
from .customAttributes import (_GetCustomAttributes, CustomAttribute,
BoundingBoxAttribute, LocalToWorldXformAttribute,
ResolvedBoundMaterial)
from .primTreeWidget import PrimTreeWidget, PrimViewColumnIndex
from .primViewItem import PrimViewItem
from .variantComboBox import VariantComboBox
from .legendUtil import ToggleLegendWithBrowser
from . import prettyPrint, adjustClipping, adjustDefaultMaterial, preferences, settings
from .constantGroup import ConstantGroup
from .selectionDataModel import ALL_INSTANCES, SelectionDataModel
# Common Utilities
from .common import (UIBaseColors, UIPropertyValueSourceColors, UIFonts,
GetPropertyColor, GetPropertyTextFont,
Timer, Drange, BusyContext, DumpMallocTags,
GetValueAndDisplayString, ResetSessionVisibility,
InvisRootPrims, GetAssetCreationTime,
PropertyViewIndex, PropertyViewIcons, PropertyViewDataRoles,
RenderModes, ColorCorrectionModes, ShadedRenderModes,
PickModes, SelectionHighlightModes, CameraMaskModes,
PropTreeWidgetTypeIsRel, PrimNotFoundException,
GetRootLayerStackInfo, HasSessionVis, GetEnclosingModelPrim,
GetPrimsLoadability, ClearColors,
HighlightColors, KeyboardShortcuts)
from . import settings2
from .settings2 import StateSource
from .usdviewApi import UsdviewApi
from .rootDataModel import RootDataModel, ChangeNotice
from .viewSettingsDataModel import ViewSettingsDataModel
from . import plugin
from .pythonInterpreter import Myconsole
SETTINGS_VERSION = "1"
class HUDEntries(ConstantGroup):
# Upper HUD entries (declared in variables for abstraction)
PRIM = "Prims"
CV = "CVs"
VERT = "Verts"
FACE = "Faces"
# Lower HUD entries
PLAYBACK = "Playback"
RENDER = "Render"
GETBOUNDS = "BBox"
# Name for prims that have no type
NOTYPE = "Typeless"
class PropertyIndex(ConstantGroup):
VALUE, METADATA, LAYERSTACK, COMPOSITION = range(4)
class UIDefaults(ConstantGroup):
STAGE_VIEW_WIDTH = 604
PRIM_VIEW_WIDTH = 521
ATTRIBUTE_VIEW_WIDTH = 682
ATTRIBUTE_INSPECTOR_WIDTH = 443
TOP_HEIGHT = 538
BOTTOM_HEIGHT = 306
# Name of the Qt binding being used
QT_BINDING = QtCore.__name__.split('.')[0]
class UsdviewDataModel(RootDataModel):
def __init__(self, printTiming, settings2):
super(UsdviewDataModel, self).__init__(printTiming)
self._selectionDataModel = SelectionDataModel(self)
self._viewSettingsDataModel = ViewSettingsDataModel(self, settings2)
@property
def selection(self):
return self._selectionDataModel
@property
def viewSettings(self):
return self._viewSettingsDataModel
def _emitPrimsChanged(self, primChange, propertyChange):
# Override from base class: before alerting listening controllers,
# ensure our owned selectionDataModel is updated
if primChange == ChangeNotice.RESYNC:
self.selection.removeUnpopulatedPrims()
super(UsdviewDataModel, self)._emitPrimsChanged(primChange,
propertyChange)
class UIStateProxySource(StateSource):
"""XXX Temporary class which allows AppController to serve as two state sources.
All fields here will be moved back into AppController in the future.
"""
def __init__(self, mainWindow, parent, name):
StateSource.__init__(self, parent, name)
self._mainWindow = mainWindow
primViewColumnVisibility = self.stateProperty("primViewColumnVisibility",
default=[True, True, True, False], validator=lambda value:
len(value) == 4)
propertyViewColumnVisibility = self.stateProperty("propertyViewColumnVisibility",
default=[True, True, True], validator=lambda value: len(value) == 3)
attributeInspectorCurrentTab = self.stateProperty("attributeInspectorCurrentTab", default=PropertyIndex.VALUE)
# UI is different when --norender is used so just save the default splitter sizes.
# TODO Save the loaded state so it doesn't disappear after using --norender.
if not self._mainWindow._noRender:
stageViewWidth = self.stateProperty("stageViewWidth", default=UIDefaults.STAGE_VIEW_WIDTH)
primViewWidth = self.stateProperty("primViewWidth", default=UIDefaults.PRIM_VIEW_WIDTH)
attributeViewWidth = self.stateProperty("attributeViewWidth", default=UIDefaults.ATTRIBUTE_VIEW_WIDTH)
attributeInspectorWidth = self.stateProperty("attributeInspectorWidth", default=UIDefaults.ATTRIBUTE_INSPECTOR_WIDTH)
topHeight = self.stateProperty("topHeight", default=UIDefaults.TOP_HEIGHT)
bottomHeight = self.stateProperty("bottomHeight", default=UIDefaults.BOTTOM_HEIGHT)
viewerMode = self.stateProperty("viewerMode", default=False)
if viewerMode:
self._mainWindow._ui.primStageSplitter.setSizes([0, 1])
self._mainWindow._ui.topBottomSplitter.setSizes([1, 0])
else:
self._mainWindow._ui.primStageSplitter.setSizes(
[primViewWidth, stageViewWidth])
self._mainWindow._ui.topBottomSplitter.setSizes(
[topHeight, bottomHeight])
self._mainWindow._ui.attribBrowserInspectorSplitter.setSizes(
[attributeViewWidth, attributeInspectorWidth])
self._mainWindow._viewerModeEscapeSizes = topHeight, bottomHeight, primViewWidth, stageViewWidth
else:
self._mainWindow._ui.primStageSplitter.setSizes(
[UIDefaults.PRIM_VIEW_WIDTH, UIDefaults.STAGE_VIEW_WIDTH])
self._mainWindow._ui.attribBrowserInspectorSplitter.setSizes(
[UIDefaults.ATTRIBUTE_VIEW_WIDTH, UIDefaults.ATTRIBUTE_INSPECTOR_WIDTH])
self._mainWindow._ui.topBottomSplitter.setSizes(
[UIDefaults.TOP_HEIGHT, UIDefaults.BOTTOM_HEIGHT])
for i, visible in enumerate(primViewColumnVisibility):
self._mainWindow._ui.primView.setColumnHidden(i, not visible)
for i, visible in enumerate(propertyViewColumnVisibility):
self._mainWindow._ui.propertyView.setColumnHidden(i, not visible)
propertyIndex = attributeInspectorCurrentTab
if propertyIndex not in PropertyIndex:
propertyIndex = PropertyIndex.VALUE
self._mainWindow._ui.propertyInspector.setCurrentIndex(propertyIndex)
def onSaveState(self, state):
# UI is different when --norender is used so don't load the splitter sizes.
if not self._mainWindow._noRender:
primViewWidth, stageViewWidth = self._mainWindow._ui.primStageSplitter.sizes()
attributeViewWidth, attributeInspectorWidth = self._mainWindow._ui.attribBrowserInspectorSplitter.sizes()
topHeight, bottomHeight = self._mainWindow._ui.topBottomSplitter.sizes()
viewerMode = (bottomHeight == 0 and primViewWidth == 0)
# If viewer mode is active, save the escape sizes instead of the
# actual sizes. If there are no escape sizes, just save the defaults.
if viewerMode:
if self._mainWindow._viewerModeEscapeSizes is not None:
topHeight, bottomHeight, primViewWidth, stageViewWidth = self._mainWindow._viewerModeEscapeSizes
else:
primViewWidth = UIDefaults.STAGE_VIEW_WIDTH
stageViewWidth = UIDefaults.PRIM_VIEW_WIDTH
attributeViewWidth = UIDefaults.ATTRIBUTE_VIEW_WIDTH
attributeInspectorWidth = UIDefaults.ATTRIBUTE_INSPECTOR_WIDTH
topHeight = UIDefaults.TOP_HEIGHT
bottomHeight = UIDefaults.BOTTOM_HEIGHT
state["primViewWidth"] = primViewWidth
state["stageViewWidth"] = stageViewWidth
state["attributeViewWidth"] = attributeViewWidth
state["attributeInspectorWidth"] = attributeInspectorWidth
state["topHeight"] = topHeight
state["bottomHeight"] = bottomHeight
state["viewerMode"] = viewerMode
state["primViewColumnVisibility"] = [
not self._mainWindow._ui.primView.isColumnHidden(c)
for c in range(self._mainWindow._ui.primView.columnCount())]
state["propertyViewColumnVisibility"] = [
not self._mainWindow._ui.propertyView.isColumnHidden(c)
for c in range(self._mainWindow._ui.propertyView.columnCount())]
state["attributeInspectorCurrentTab"] = self._mainWindow._ui.propertyInspector.currentIndex()
class Blocker:
"""Object which can be used to temporarily block the execution of a body of
code. This object is a context manager, and enters a 'blocked' state when
used in a 'with' statement. The 'blocked()' method can be used to find if
the Blocker is in this 'blocked' state.
For example, this is used to prevent UI code from handling signals from the
selection data model while the UI code itself modifies selection.
"""
def __init__(self):
# A count is used rather than a 'blocked' flag to allow for nested
# blocking.
self._count = 0
def __enter__(self):
"""Enter the 'blocked' state until the context is exited."""
self._count += 1
def __exit__(self, *args):
"""Exit the 'blocked' state."""
self._count -= 1
def blocked(self):
"""Returns True if in the 'blocked' state, and False otherwise."""
return self._count > 0
class MainWindow(QtWidgets.QMainWindow):
"This class exists to simplify and streamline the shutdown process."
"The application may be closed via the File menu, or by closing the main"
"window, both of which result in the same behavior."
def __init__(self, closeFunc):
super(MainWindow, self).__init__(None) # no parent widget
self._closeFunc = closeFunc
def closeEvent(self, event):
self._closeFunc()
class AppController(QtCore.QObject):
HYDRA_DISABLED_OPTION_STRING = "HydraDisabled"
###########
# Signals #
###########
@classmethod
def clearSettings(cls):
settingsPath = cls._outputBaseDirectory()
if settingsPath is None:
return None
else:
settingsPath = os.path.join(settingsPath, 'state')
if not os.path.exists(settingsPath):
print('INFO: ClearSettings requested, but there '
'were no settings currently stored.')
return None
if not os.access(settingsPath, os.W_OK):
print('ERROR: Could not remove settings file.')
return None
else:
os.remove(settingsPath)
print('INFO: Settings restored to default.')
def _configurePlugins(self):
with Timer() as t:
self._plugRegistry = plugin.loadPlugins(
self._usdviewApi, self._mainWindow)
if self._printTiming:
t.PrintTime("configure and load plugins.")
def _openSettings2(self, defaultSettings):
settingsPathDir = self._outputBaseDirectory()
if (settingsPathDir is None) or defaultSettings:
# Create an ephemeral settings object by withholding the file path.
self._settings2 = settings2.Settings(SETTINGS_VERSION)
else:
settings2Path = os.path.join(settingsPathDir, "state.json")
self._settings2 = settings2.Settings(SETTINGS_VERSION, settings2Path)
def _setStyleSheetUsingState(self):
# We use a style file that is actually a template, which we fill
# in from state, and is how we change app font sizes, for example.
# Find the resource directory
resourceDir = os.path.dirname(os.path.realpath(__file__)) + "/"
# Qt style sheet accepts only forward slashes as path separators
resourceDir = resourceDir.replace("\\", "/")
fontSize = self._dataModel.viewSettings.fontSize
baseFontSizeStr = "%spt" % str(fontSize)
# The choice of 8 for smallest smallSize is for performance reasons,
# based on the "Gotham Rounded" font used by usdviewstyle.qss . If we
# allow it to float, we get a 2-3 hundred millisecond hit in startup
# time as Qt (apparently) manufactures a suitably sized font.
# Mysteriously, we don't see this cost for larger font sizes.
smallSize = 8 if fontSize < 12 else int(round(fontSize * 0.8))
smallFontSizeStr = "%spt" % str(smallSize)
# Apply the style sheet to it
sheet = open(os.path.join(resourceDir, 'usdviewstyle.qss'), 'r')
sheetString = sheet.read() % {
'RESOURCE_DIR' : resourceDir,
'BASE_FONT_SZ' : baseFontSizeStr,
'SMALL_FONT_SZ' : smallFontSizeStr }
app = QtWidgets.QApplication.instance()
app.setStyleSheet(sheetString)
def __del__(self):
# This is needed to free Qt items before exit; Qt hits failed GTK
# assertions without it.
self._primToItemMap.clear()
def __init__(self, parserData, resolverContextFn):
QtCore.QObject.__init__(self)
with Timer() as uiOpenTimer:
self._primToItemMap = {}
self._itemsToPush = []
self._currentSpec = None
self._currentLayer = None
self._console = None
self._debugFlagsWindow = None
self._interpreter = None
self._parserData = parserData
self._noRender = parserData.noRender
self._noPlugins = parserData.noPlugins
self._unloaded = parserData.unloaded
self._resolverContextFn = resolverContextFn
self._debug = os.getenv('USDVIEW_DEBUG', False)
self._printTiming = parserData.timing or self._debug
self._lastViewContext = {}
self._paused = False
self._stopped = False
if QT_BINDING == 'PySide':
self._statusFileName = 'state'
self._deprecatedStatusFileNames = ('.usdviewrc')
else:
self._statusFileName = 'state.%s'%QT_BINDING
self._deprecatedStatusFileNames = ('state', '.usdviewrc')
self._mallocTags = parserData.mallocTagStats
self._allowViewUpdates = True
# When viewer mode is active, the panel sizes are cached so they can
# be restored later.
self._viewerModeEscapeSizes = None
self._rendererNameOpt = parserData.renderer
if self._rendererNameOpt:
if self._rendererNameOpt == \
AppController.HYDRA_DISABLED_OPTION_STRING:
os.environ['HD_ENABLED'] = '0'
else:
os.environ['HD_DEFAULT_RENDERER'] = self._rendererNameOpt
self._openSettings2(parserData.defaultSettings)
self._dataModel = UsdviewDataModel(
self._printTiming, self._settings2)
# Now that we've read in our state and applied parserData
# overrides, we can process our styleSheet... *before* we
# start listening for style-related changes.
self._setStyleSheetUsingState()
self._mainWindow = MainWindow(lambda: self._cleanAndClose())
self._ui = Ui_MainWindow()
self._ui.setupUi(self._mainWindow)
self._mainWindow.setWindowTitle(parserData.usdFile)
self._statusBar = QtWidgets.QStatusBar(self._mainWindow)
self._mainWindow.setStatusBar(self._statusBar)
# Waiting to show the mainWindow till after setting the
# statusBar saves considerable GUI configuration time.
self._mainWindow.show()
self._mainWindow.setFocus()
# Install our custom event filter. The member assignment of the
# filter is just for lifetime management
from .appEventFilter import AppEventFilter
self._filterObj = AppEventFilter(self)
QtWidgets.QApplication.instance().installEventFilter(self._filterObj)
# Setup Usdview API and optionally load plugins. We do this before
# loading the stage in case a plugin wants to modify global settings
# that affect stage loading.
self._plugRegistry = None
self._usdviewApi = UsdviewApi(self)
if not self._noPlugins:
self._configurePlugins()
# read the stage here
stage = self._openStage(
self._parserData.usdFile, self._parserData.sessionLayer,
self._parserData.populationMask)
if not stage:
sys.exit(0)
if not stage.GetPseudoRoot():
print(parserData.usdFile, 'has no prims; exiting.')
sys.exit(0)
# We instantiate a UIStateProxySource only for its side-effects
uiProxy = UIStateProxySource(self, self._settings2, "ui")
self._dataModel.stage = stage
self._primViewSelectionBlocker = Blocker()
self._propertyViewSelectionBlocker = Blocker()
self._dataModel.selection.signalPrimSelectionChanged.connect(
self._primSelectionChanged)
self._dataModel.selection.signalPropSelectionChanged.connect(
self._propSelectionChanged)
self._dataModel.selection.signalComputedPropSelectionChanged.connect(
self._propSelectionChanged)
self._initialSelectPrim = self._dataModel.stage.GetPrimAtPath(
parserData.primPath)
if not self._initialSelectPrim:
print('Could not find prim at path <%s> to select. '\
'Ignoring...' % parserData.primPath)
self._initialSelectPrim = None
try:
self._dataModel.viewSettings.complexity = parserData.complexity
except ValueError:
fallback = RefinementComplexities.LOW
sys.stderr.write(("Error: Invalid complexity '{}'. "
"Using fallback '{}' instead.\n").format(
parserData.complexity, fallback.id))
self._dataModel.viewSettings.complexity = fallback
self._hasPrimResync = False
self._timeSamples = None
self._stageView = None
self._startingPrimCamera = None
if (parserData.camera.IsAbsolutePath() or
parserData.camera.pathElementCount > 1):
self._startingPrimCameraName = None
self._startingPrimCameraPath = parserData.camera
else:
self._startingPrimCameraName = parserData.camera.pathString
self._startingPrimCameraPath = None
settingsPathDir = self._outputBaseDirectory()
if settingsPathDir is None or parserData.defaultSettings:
# Create an ephemeral settings object with a non existent filepath
self._settings = settings.Settings('', seq=None, ephemeral=True)
else:
settingsPath = os.path.join(settingsPathDir, self._statusFileName)
for deprecatedName in self._deprecatedStatusFileNames:
deprecatedSettingsPath = \
os.path.join(settingsPathDir, deprecatedName)
if (os.path.isfile(deprecatedSettingsPath) and
not os.path.isfile(settingsPath)):
warning = ('\nWARNING: The settings file at: '
+ str(deprecatedSettingsPath) + ' is deprecated.\n'
+ 'These settings are not being used, the new '
+ 'settings file will be located at: '
+ str(settingsPath) + '.\n')
print(warning)
break
self._settings = settings.Settings(settingsPath)
try:
self._settings.load()
except IOError:
# try to force out a new settings file
try:
self._settings.save()
except:
settings.EmitWarning(settingsPath)
except EOFError:
# try to force out a new settings file
try:
self._settings.save()
except:
settings.EmitWarning(settingsPath)
except:
settings.EmitWarning(settingsPath)
self._dataModel.viewSettings.signalStyleSettingsChanged.connect(
self._setStyleSheetUsingState)
self._dataModel.signalPrimsChanged.connect(
self._onPrimsChanged)
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
self._timer = QtCore.QTimer(self)
# Timeout interval in ms. We set it to 0 so it runs as fast as
# possible. In advanceFrameForPlayback we use the sleep() call
# to slow down rendering to self.framesPerSecond fps.
self._timer.setInterval(0)
self._lastFrameTime = time()
# Initialize the upper HUD info
self._upperHUDInfo = dict()
# declare dictionary keys for the fps info too
self._fpsHUDKeys = (HUDEntries.RENDER, HUDEntries.PLAYBACK)
# Initialize fps HUD with empty strings
self._fpsHUDInfo = dict(zip(self._fpsHUDKeys,
["N/A", "N/A"]))
self._startTime = self._endTime = time()
# This timer is used to coalesce the primView resizes
# in certain cases. e.g. When you
# deactivate/activate a prim.
self._primViewResizeTimer = QtCore.QTimer(self)
self._primViewResizeTimer.setInterval(0)
self._primViewResizeTimer.setSingleShot(True)
self._primViewResizeTimer.timeout.connect(self._resizePrimView)
# This timer coalesces GUI resets when the USD stage is modified or
# reloaded.
self._guiResetTimer = QtCore.QTimer(self)
self._guiResetTimer.setInterval(0)
self._guiResetTimer.setSingleShot(True)
self._guiResetTimer.timeout.connect(self._resetGUI)
# Idle timer to push off-screen data to the UI.
self._primViewUpdateTimer = QtCore.QTimer(self)
self._primViewUpdateTimer.setInterval(0)
self._primViewUpdateTimer.timeout.connect(self._updatePrimView)
# This creates the _stageView and restores state from settings file
self._resetSettings()
# This is for validating frame values input on the "Frame" line edit
validator = QtGui.QDoubleValidator(self)
self._ui.frameField.setValidator(validator)
self._ui.rangeEnd.setValidator(validator)
self._ui.rangeBegin.setValidator(validator)
stepValidator = QtGui.QDoubleValidator(self)
stepValidator.setRange(0.01, 1e7, 2)
self._ui.stepSize.setValidator(stepValidator)
# This causes the last column of the attribute view (the value)
# to be stretched to fill the available space
self._ui.propertyView.header().setStretchLastSection(True)
self._ui.propertyView.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
self._ui.primView.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
# This allows ctrl and shift clicking for multi-selecting
self._ui.propertyView.setSelectionMode(
QtWidgets.QAbstractItemView.ExtendedSelection)
self._ui.propertyView.setHorizontalScrollMode(
QtWidgets.QAbstractItemView.ScrollPerPixel)
self._ui.frameSlider.setTracking(
self._dataModel.viewSettings.redrawOnScrub)
self._ui.colorGroup = QtWidgets.QActionGroup(self)
self._ui.colorGroup.setExclusive(True)
self._clearColorActions = (
self._ui.actionBlack,
self._ui.actionGrey_Dark,
self._ui.actionGrey_Light,
self._ui.actionWhite)
for action in self._clearColorActions:
self._ui.colorGroup.addAction(action)
self._ui.renderModeActionGroup = QtWidgets.QActionGroup(self)
self._ui.renderModeActionGroup.setExclusive(True)
self._renderModeActions = (
self._ui.actionWireframe,
self._ui.actionWireframeOnSurface,
self._ui.actionSmooth_Shaded,
self._ui.actionFlat_Shaded,
self._ui.actionPoints,
self._ui.actionGeom_Only,
self._ui.actionGeom_Smooth,
self._ui.actionGeom_Flat,
self._ui.actionHidden_Surface_Wireframe)
for action in self._renderModeActions:
self._ui.renderModeActionGroup.addAction(action)
self._ui.colorCorrectionActionGroup = QtWidgets.QActionGroup(self)
self._ui.colorCorrectionActionGroup.setExclusive(True)
self._colorCorrectionActions = (
self._ui.actionNoColorCorrection,
self._ui.actionSRGBColorCorrection,
self._ui.actionOpenColorIO)
for action in self._colorCorrectionActions:
self._ui.colorCorrectionActionGroup.addAction(action)
# XXX This should be a validator in ViewSettingsDataModel.
if self._dataModel.viewSettings.renderMode not in RenderModes:
fallback = str(
self._ui.renderModeActionGroup.actions()[0].text())
print("Warning: Unknown render mode '%s', falling back to '%s'" % (
self._dataModel.viewSettings.renderMode, fallback))
self._dataModel.viewSettings.renderMode = fallback
self._ui.pickModeActionGroup = QtWidgets.QActionGroup(self)
self._ui.pickModeActionGroup.setExclusive(True)
self._pickModeActions = (
self._ui.actionPick_Prims,
self._ui.actionPick_Models,
self._ui.actionPick_Instances,
self._ui.actionPick_Prototypes)
for action in self._pickModeActions:
self._ui.pickModeActionGroup.addAction(action)
# XXX This should be a validator in ViewSettingsDataModel.
if self._dataModel.viewSettings.pickMode not in PickModes:
fallback = str(self._ui.pickModeActionGroup.actions()[0].text())
print("Warning: Unknown pick mode '%s', falling back to '%s'" % (
self._dataModel.viewSettings.pickMode, fallback))
self._dataModel.viewSettings.pickMode = fallback
self._ui.selHighlightModeActionGroup = QtWidgets.QActionGroup(self)
self._ui.selHighlightModeActionGroup.setExclusive(True)
self._selHighlightActions = (
self._ui.actionNever,
self._ui.actionOnly_when_paused,
self._ui.actionAlways)
for action in self._selHighlightActions:
self._ui.selHighlightModeActionGroup.addAction(action)
self._ui.highlightColorActionGroup = QtWidgets.QActionGroup(self)
self._ui.highlightColorActionGroup.setExclusive(True)
self._selHighlightColorActions = (
self._ui.actionSelYellow,
self._ui.actionSelCyan,
self._ui.actionSelWhite)
for action in self._selHighlightColorActions:
self._ui.highlightColorActionGroup.addAction(action)
self._ui.interpolationActionGroup = QtWidgets.QActionGroup(self)
self._ui.interpolationActionGroup.setExclusive(True)
for interpolationType in Usd.InterpolationType.allValues:
action = self._ui.menuInterpolation.addAction(interpolationType.displayName)
action.setCheckable(True)
action.setChecked(
self._dataModel.stage.GetInterpolationType() == interpolationType)
self._ui.interpolationActionGroup.addAction(action)
self._ui.primViewDepthGroup = QtWidgets.QActionGroup(self)
for i in range(1, 9):
action = getattr(self._ui, "actionLevel_" + str(i))
self._ui.primViewDepthGroup.addAction(action)
# setup animation objects for the primView and propertyView
self._propertyLegendAnim = QtCore.QPropertyAnimation(
self._ui.propertyLegendContainer, b"maximumHeight")
self._primLegendAnim = QtCore.QPropertyAnimation(
self._ui.primLegendContainer, b"maximumHeight")
# set the context menu policy for the prim browser and attribute
# inspector headers. This is so we can have a context menu on the
# headers that allows you to select which columns are visible.
self._ui.propertyView.header()\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self._ui.primView.header()\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Set custom context menu for attribute browser
self._ui.propertyView\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Set custom context menu for layer stack browser
self._ui.layerStackView\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Set custom context menu for composition tree browser
self._ui.compositionTreeWidget\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Arc path is the most likely to need stretch.
twh = self._ui.compositionTreeWidget.header()
twh.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
twh.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
twh.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
twh.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
# Set the prim view header to have a fixed size type and vis columns
nvh = self._ui.primView.header()
nvh.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
nvh.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
nvh.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
nvh.resizeSection(3, 116)
nvh.setSectionResizeMode(3, QtWidgets.QHeaderView.Fixed)
pvh = self._ui.propertyView.header()
pvh.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
pvh.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
pvh.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
# XXX:
# To avoid QTBUG-12850 (https://bugreports.qt.io/browse/QTBUG-12850),
# we force the horizontal scrollbar to always be visible for all
# QTableWidget widgets in use.
self._ui.primView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.propertyView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.metadataView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.layerStackView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.attributeValueEditor.setAppController(self)
self._ui.primView.InitControllers(self)
self._ui.currentPathWidget.editingFinished.connect(
self._currentPathChanged)
# XXX:
# To avoid PYSIDE-79 (https://bugreports.qt.io/browse/PYSIDE-79)
# with Qt4/PySide, we must hold the prim view's selectionModel
# in a local variable before connecting its signals.
primViewSelModel = self._ui.primView.selectionModel()
primViewSelModel.selectionChanged.connect(self._selectionChanged)
self._ui.primView.itemClicked.connect(self._itemClicked)
self._ui.primView.itemPressed.connect(self._itemPressed)
self._ui.primView.header().customContextMenuRequested.connect(
self._primViewHeaderContextMenu)
self._timer.timeout.connect(self._advanceFrameForPlayback)
self._ui.primView.customContextMenuRequested.connect(
self._primViewContextMenu)
self._ui.primView.expanded.connect(self._primViewExpanded)
self._ui.frameSlider.valueChanged.connect(self._setFrameIndex)
self._ui.frameSlider.sliderMoved.connect(self._sliderMoved)
self._ui.frameSlider.sliderReleased.connect(self._updateGUIForFrameChange)
self._ui.frameField.editingFinished.connect(self._frameStringChanged)
self._ui.rangeBegin.editingFinished.connect(self._rangeBeginChanged)
self._ui.stepSize.editingFinished.connect(self._stepSizeChanged)
self._ui.rangeEnd.editingFinished.connect(self._rangeEndChanged)
self._ui.actionFrame_Forward.triggered.connect(self._advanceFrame)
self._ui.actionFrame_Backwards.triggered.connect(self._retreatFrame)
self._ui.actionReset_View.triggered.connect(lambda: self._resetView())
self._ui.topBottomSplitter.splitterMoved.connect(self._cacheViewerModeEscapeSizes)
self._ui.primStageSplitter.splitterMoved.connect(self._cacheViewerModeEscapeSizes)
self._ui.actionToggle_Viewer_Mode.triggered.connect(
self._toggleViewerMode)
self._ui.showBBoxes.triggered.connect(self._toggleShowBBoxes)
self._ui.showAABBox.triggered.connect(self._toggleShowAABBox)
self._ui.showOBBox.triggered.connect(self._toggleShowOBBox)
self._ui.showBBoxPlayback.triggered.connect(
self._toggleShowBBoxPlayback)
self._ui.useExtentsHint.triggered.connect(self._setUseExtentsHint)
self._ui.showInterpreter.triggered.connect(self._showInterpreter)
self._ui.showDebugFlags.triggered.connect(self._showDebugFlags)
self._ui.redrawOnScrub.toggled.connect(self._redrawOptionToggled)
if self._stageView:
self._ui.actionAuto_Compute_Clipping_Planes.triggered.connect(
self._toggleAutoComputeClippingPlanes)
self._ui.actionAdjust_Clipping.triggered[bool].connect(
self._adjustClippingPlanes)
self._ui.actionAdjust_Default_Material.triggered[bool].connect(
self._adjustDefaultMaterial)
self._ui.actionPreferences.triggered[bool].connect(
self._togglePreferences)
self._ui.actionOpen.triggered.connect(self._openFile)
self._ui.actionSave_Overrides_As.triggered.connect(
self._saveOverridesAs)
self._ui.actionSave_Flattened_As.triggered.connect(
self._saveFlattenedAs)
self._ui.actionPause.triggered.connect(
self._togglePause)
self._ui.actionStop.triggered.connect(
self._toggleStop)
# Typically, a handler is registered to the 'aboutToQuit' signal
# to handle cleanup. However, with PySide2, stageView's GL context
# is destroyed by then, making it too late in the shutdown process
# to release any GL resources used by the renderer (relevant for
# Storm's GL renderer).
# To work around this, orchestrate shutdown via the main window's
# closeEvent() handler.
self._ui.actionQuit.triggered.connect(QtWidgets.QApplication.instance().closeAllWindows)
# To measure Qt shutdown time, register a handler to stop the timer.
QtWidgets.QApplication.instance().aboutToQuit.connect(self._stopQtShutdownTimer)
self._ui.actionReopen_Stage.triggered.connect(self._reopenStage)
self._ui.actionReload_All_Layers.triggered.connect(self._reloadStage)
self._ui.actionToggle_Framed_View.triggered.connect(self._toggleFramedView)
self._ui.actionAdjust_FOV.triggered.connect(self._adjustFOV)
self._ui.complexityGroup = QtWidgets.QActionGroup(self._mainWindow)
self._ui.complexityGroup.setExclusive(True)
self._complexityActions = (
self._ui.actionLow,
self._ui.actionMedium,
self._ui.actionHigh,
self._ui.actionVery_High)
for action in self._complexityActions:
self._ui.complexityGroup.addAction(action)
self._ui.complexityGroup.triggered.connect(self._changeComplexity)
self._ui.actionDisplay_Guide.triggered.connect(
self._toggleDisplayGuide)
self._ui.actionDisplay_Proxy.triggered.connect(
self._toggleDisplayProxy)
self._ui.actionDisplay_Render.triggered.connect(
self._toggleDisplayRender)
self._ui.actionDisplay_Camera_Oracles.triggered.connect(
self._toggleDisplayCameraOracles)
self._ui.actionDisplay_PrimId.triggered.connect(
self._toggleDisplayPrimId)
self._ui.actionEnable_Scene_Materials.triggered.connect(
self._toggleEnableSceneMaterials)
self._ui.actionCull_Backfaces.triggered.connect(
self._toggleCullBackfaces)
self._ui.propertyInspector.currentChanged.connect(
self._updatePropertyInspector)
self._ui.propertyView.itemSelectionChanged.connect(
self._propertyViewSelectionChanged)
self._ui.propertyView.currentItemChanged.connect(
self._propertyViewCurrentItemChanged)
self._ui.propertyView.header().customContextMenuRequested.\
connect(self._propertyViewHeaderContextMenu)
self._ui.propertyView.customContextMenuRequested.connect(
self._propertyViewContextMenu)
self._ui.layerStackView.customContextMenuRequested.connect(
self._layerStackContextMenu)
self._ui.compositionTreeWidget.customContextMenuRequested.connect(
self._compositionTreeContextMenu)
self._ui.compositionTreeWidget.currentItemChanged.connect(
self._onCompositionSelectionChanged)
self._ui.renderModeActionGroup.triggered.connect(self._changeRenderMode)
self._ui.colorCorrectionActionGroup.triggered.connect(
self._changeColorCorrection)
self._ui.pickModeActionGroup.triggered.connect(self._changePickMode)
self._ui.selHighlightModeActionGroup.triggered.connect(
self._changeSelHighlightMode)
self._ui.highlightColorActionGroup.triggered.connect(
self._changeHighlightColor)
self._ui.interpolationActionGroup.triggered.connect(
self._changeInterpolationType)
self._ui.actionAmbient_Only.triggered[bool].connect(
self._ambientOnlyClicked)
self._ui.actionDomeLight.triggered[bool].connect(self._onDomeLightClicked)
self._ui.colorGroup.triggered.connect(self._changeBgColor)
# Configuring the PrimView's Show menu. In addition to the
# "designed" menu items, we inject a PrimView HeaderContextMenu
self._ui.primViewDepthGroup.triggered.connect(self._changePrimViewDepth)
self._ui.actionExpand_All.triggered.connect(
lambda: self._expandToDepth(1000000))
self._ui.actionCollapse_All.triggered.connect(
self._ui.primView.collapseAll)
self._ui.actionShow_Inactive_Prims.triggered.connect(
self._toggleShowInactivePrims)
self._ui.actionShow_All_Master_Prims.triggered.connect(
self._toggleShowMasterPrims)
self._ui.actionShow_Undefined_Prims.triggered.connect(
self._toggleShowUndefinedPrims)
self._ui.actionShow_Abstract_Prims.triggered.connect(
self._toggleShowAbstractPrims)
# Since setting column visibility is probably not a common
# operation, it's actually good to have Columns at the end.
self._ui.menuShow.addSeparator()
self._ui.menuShow.addMenu(HeaderContextMenu(self._ui.primView))
self._ui.actionRollover_Prim_Info.triggered.connect(
self._toggleRolloverPrimInfo)
self._ui.primViewLineEdit.returnPressed.connect(
self._ui.primViewFindNext.click)
self._ui.primViewFindNext.clicked.connect(self._primViewFindNext)
self._ui.attrViewLineEdit.returnPressed.connect(
self._ui.attrViewFindNext.click)
self._ui.attrViewFindNext.clicked.connect(self._attrViewFindNext)
self._ui.primLegendQButton.clicked.connect(
self._primLegendToggleCollapse)
self._ui.propertyLegendQButton.clicked.connect(
self._propertyLegendToggleCollapse)
self._ui.playButton.clicked.connect(self._playClicked)
self._ui.actionCameraMask_Full.triggered.connect(
self._updateCameraMaskMenu)
self._ui.actionCameraMask_Partial.triggered.connect(
self._updateCameraMaskMenu)
self._ui.actionCameraMask_None.triggered.connect(
self._updateCameraMaskMenu)
self._ui.actionCameraMask_Outline.triggered.connect(
self._updateCameraMaskOutlineMenu)
self._ui.actionCameraMask_Color.triggered.connect(
self._pickCameraMaskColor)
self._ui.actionCameraReticles_Inside.triggered.connect(
self._updateCameraReticlesInsideMenu)
self._ui.actionCameraReticles_Outside.triggered.connect(
self._updateCameraReticlesOutsideMenu)
self._ui.actionCameraReticles_Color.triggered.connect(
self._pickCameraReticlesColor)
self._ui.actionHUD.triggered.connect(self._showHUDChanged)
self._ui.actionHUD_Info.triggered.connect(self._showHUD_InfoChanged)
self._ui.actionHUD_Complexity.triggered.connect(
self._showHUD_ComplexityChanged)
self._ui.actionHUD_Performance.triggered.connect(
self._showHUD_PerformanceChanged)
self._ui.actionHUD_GPUstats.triggered.connect(
self._showHUD_GPUstatsChanged)
self._mainWindow.addAction(self._ui.actionIncrementComplexity1)
self._mainWindow.addAction(self._ui.actionIncrementComplexity2)
self._mainWindow.addAction(self._ui.actionDecrementComplexity)
self._ui.actionIncrementComplexity1.triggered.connect(
self._incrementComplexity)
self._ui.actionIncrementComplexity2.triggered.connect(
self._incrementComplexity)
self._ui.actionDecrementComplexity.triggered.connect(
self._decrementComplexity)
self._ui.attributeValueEditor.editComplete.connect(self.editComplete)
# Edit Prim menu
self._ui.menuEdit.aboutToShow.connect(self._updateEditMenu)
self._ui.menuNavigation.aboutToShow.connect(self._updateNavigationMenu)
self._ui.actionFind_Prims.triggered.connect(
self._ui.primViewLineEdit.setFocus)
self._ui.actionSelect_Stage_Root.triggered.connect(
self.selectPseudoroot)
self._ui.actionSelect_Model_Root.triggered.connect(
self.selectEnclosingModel)
self._ui.actionSelect_Bound_Preview_Material.triggered.connect(
self.selectBoundPreviewMaterial)
self._ui.actionSelect_Bound_Full_Material.triggered.connect(
self.selectBoundFullMaterial)
self._ui.actionSelect_Preview_Binding_Relationship.triggered.connect(
self.selectPreviewBindingRel)
self._ui.actionSelect_Full_Binding_Relationship.triggered.connect(
self.selectFullBindingRel)
self._ui.actionMake_Visible.triggered.connect(self.visSelectedPrims)
# Add extra, Presto-inspired shortcut for Make Visible
self._ui.actionMake_Visible.setShortcuts(["Shift+H", "Ctrl+Shift+H"])
self._ui.actionMake_Invisible.triggered.connect(self.invisSelectedPrims)
self._ui.actionVis_Only.triggered.connect(self.visOnlySelectedPrims)
self._ui.actionRemove_Session_Visibility.triggered.connect(
self.removeVisSelectedPrims)
self._ui.actionReset_All_Session_Visibility.triggered.connect(
self.resetSessionVisibility)
self._ui.actionLoad.triggered.connect(self.loadSelectedPrims)
self._ui.actionUnload.triggered.connect(self.unloadSelectedPrims)
self._ui.actionActivate.triggered.connect(self.activateSelectedPrims)
self._ui.actionDeactivate.triggered.connect(self.deactivateSelectedPrims)
# We refresh as if all view settings changed. In the future, we
# should do more granular refreshes. This first requires more
# granular signals from ViewSettingsDataModel.
self._dataModel.viewSettings.signalSettingChanged.connect(
self._viewSettingChanged)
# Update view menu actions and submenus with initial state.
self._refreshViewMenubar()
# We manually call processEvents() here to make sure that the prim
# browser and other widgetry get drawn before we draw the first image in
# the viewer, which might take a long time.
if self._stageView:
self._stageView.setUpdatesEnabled(False)
self._mainWindow.update()
QtWidgets.QApplication.processEvents()
if self._printTiming:
uiOpenTimer.PrintTime('bring up the UI')
self._drawFirstImage()
QtWidgets.QApplication.restoreOverrideCursor()
def _drawFirstImage(self):
if self._stageView:
self._stageView.setUpdatesEnabled(True)
with BusyContext():
try:
self._resetView(self._initialSelectPrim)
except Exception:
pass
QtWidgets.QApplication.processEvents()
# configure render plugins after stageView initialized its renderer.
self._configureRendererPlugins()
self._configureColorManagement()
if self._mallocTags == 'stageAndImaging':
DumpMallocTags(self._dataModel.stage,
"stage-loading and imaging")
def statusMessage(self, msg, timeout = 0):
self._statusBar.showMessage(msg, timeout * 1000)
def editComplete(self, msg):
title = self._mainWindow.windowTitle()
if title[-1] != '*':
self._mainWindow.setWindowTitle(title + ' *')
self.statusMessage(msg, 12)
with Timer() as t:
if self._stageView:
self._stageView.updateView(resetCam=False, forceComputeBBox=True)
if self._printTiming:
t.PrintTime("'%s'" % msg)
def _openStage(self, usdFilePath, sessionFilePath, populationMaskPaths):
def _GetFormattedError(reasons=None):
err = ("Error: Unable to open stage '{0}'\n".format(usdFilePath))
if reasons:
err += "\n".join(reasons) + "\n"
return err
if not Ar.GetResolver().Resolve(usdFilePath):
sys.stderr.write(_GetFormattedError(["File not found"]))
sys.exit(1)
if self._mallocTags != 'none':
Tf.MallocTag.Initialize()
with Timer() as t:
loadSet = Usd.Stage.LoadNone if self._unloaded else Usd.Stage.LoadAll
popMask = (None if populationMaskPaths is None else
Usd.StagePopulationMask())
# Open as a layer first to make sure its a valid file format
try:
layer = Sdf.Layer.FindOrOpen(usdFilePath)
except Tf.ErrorException as e:
sys.stderr.write(_GetFormattedError(
[err.commentary.strip() for err in e.args]))
sys.exit(1)
if sessionFilePath:
try:
sessionLayer = Sdf.Layer.Find(sessionFilePath)
if sessionLayer:
sessionLayer.Reload()
else:
sessionLayer = Sdf.Layer.FindOrOpen(sessionFilePath)
except Tf.ErrorException as e:
sys.stderr.write(_GetFormattedError(
[err.commentary.strip() for err in e.args]))
sys.exit(1)
else:
sessionLayer = Sdf.Layer.CreateAnonymous()
if popMask:
for p in populationMaskPaths:
popMask.Add(p)
stage = Usd.Stage.OpenMasked(layer,
sessionLayer,
self._resolverContextFn(usdFilePath),
popMask, loadSet)
else:
stage = Usd.Stage.Open(layer,
sessionLayer,
self._resolverContextFn(usdFilePath),
loadSet)
if not stage:
sys.stderr.write(_GetFormattedError())
else:
if self._printTiming:
t.PrintTime('open stage "%s"' % usdFilePath)
stage.SetEditTarget(stage.GetSessionLayer())
if self._mallocTags == 'stage':
DumpMallocTags(stage, "stage-loading")
return stage
def _closeStage(self):
# Close the USD stage.
if self._stageView:
self._stageView.closeRenderer()
self._dataModel.stage = None
def _startQtShutdownTimer(self):
self._qtShutdownTimer = Timer()
self._qtShutdownTimer.__enter__()
def _stopQtShutdownTimer(self):
self._qtShutdownTimer.__exit__()
if self._printTiming:
self._qtShutdownTimer.PrintTime('tear down the UI')
def _setPlayShortcut(self):
self._ui.playButton.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Space))
# Non-topology dependent UI changes
def _reloadFixedUI(self, resetStageDataOnly=False):
# If animation is playing, stop it.
if self._dataModel.playing:
self._ui.playButton.click()
# frame range supplied by user
ff = self._parserData.firstframe
lf = self._parserData.lastframe
# frame range supplied by stage
stageStartTimeCode = self._dataModel.stage.GetStartTimeCode()
stageEndTimeCode = self._dataModel.stage.GetEndTimeCode()
# final range results
self.realStartTimeCode = None
self.realEndTimeCode = None
self.framesPerSecond = self._dataModel.stage.GetFramesPerSecond()
if self.framesPerSecond < 1:
err = ("Error: Invalid value for field framesPerSecond of %.2f. Using default value of 24 \n" % self.framesPerSecond)
sys.stderr.write(err)
self.statusMessage(err)
self.framesPerSecond = 24.0
if not resetStageDataOnly:
self.step = self._dataModel.stage.GetTimeCodesPerSecond() / self.framesPerSecond
self._ui.stepSize.setText(str(self.step))
# if one option is provided(lastframe or firstframe), we utilize it
if ff is not None and lf is not None:
self.realStartTimeCode = ff
self.realEndTimeCode = lf
elif ff is not None:
self.realStartTimeCode = ff
self.realEndTimeCode = stageEndTimeCode
elif lf is not None:
self.realStartTimeCode = stageStartTimeCode
self.realEndTimeCode = lf
elif self._dataModel.stage.HasAuthoredTimeCodeRange():
self.realStartTimeCode = stageStartTimeCode
self.realEndTimeCode = stageEndTimeCode
self._ui.stageBegin.setText(str(stageStartTimeCode))
self._ui.stageEnd.setText(str(stageEndTimeCode))
# Use a valid current frame supplied by user, or allow _UpdateTimeSamples
# to set the current frame.
cf = self._parserData.currentframe
if cf:
if (cf < self.realStartTimeCode or cf > self.realEndTimeCode):
sys.stderr.write('Warning: Invalid current frame specified (%s)\n' % (cf))
else:
self._dataModel.currentFrame = Usd.TimeCode(cf)
self._UpdateTimeSamples(resetStageDataOnly)
def _UpdateTimeSamples(self, resetStageDataOnly=False):
if self.realStartTimeCode is not None and self.realEndTimeCode is not None:
if self.realStartTimeCode > self.realEndTimeCode:
sys.stderr.write('Warning: Invalid frame range (%s, %s)\n'
% (self.realStartTimeCode, self.realEndTimeCode))
self._timeSamples = []
else:
self._timeSamples = Drange(self.realStartTimeCode,
self.realEndTimeCode,
self.step)
else:
self._timeSamples = []
self._geomCounts = dict()
self._hasTimeSamples = (len(self._timeSamples) > 0)
self._setPlaybackAvailability() # this sets self._playbackAvailable
if self._hasTimeSamples:
self._ui.rangeBegin.setText(str(self._timeSamples[0]))
self._ui.rangeEnd.setText(str(self._timeSamples[-1]))
if ( self._dataModel.currentFrame.IsDefault() or
self._dataModel.currentFrame < self._timeSamples[0] ):
self._dataModel.currentFrame = Usd.TimeCode(self._timeSamples[0])
if self._dataModel.currentFrame > self._timeSamples[-1]:
self._dataModel.currentFrame = Usd.TimeCode(self._timeSamples[-1])
else:
self._dataModel.currentFrame = Usd.TimeCode(0.0)
if not resetStageDataOnly:
self._ui.frameField.setText(
str(self._dataModel.currentFrame.GetValue()))
if self._playbackAvailable:
if not resetStageDataOnly:
self._ui.frameSlider.setRange(0, len(self._timeSamples) - 1)
self._ui.frameSlider.setValue(0)
self._setPlayShortcut()
self._ui.playButton.setCheckable(True)
# Ensure the play button state respects the current playback state
self._ui.playButton.setChecked(self._dataModel.playing)
def _clearCaches(self, preserveCamera=False):
"""Clears value and computation caches maintained by the controller.
Does NOT initiate any GUI updates"""
self._geomCounts = dict()
self._dataModel._clearCaches()
self._refreshCameraListAndMenu(preserveCurrCamera = preserveCamera)
@staticmethod
def GetRendererOptionChoices():
ids = UsdImagingGL.Engine.GetRendererPlugins()
choices = []
if ids:
choices = [UsdImagingGL.Engine.GetRendererDisplayName(x)
for x in ids]
choices.append(AppController.HYDRA_DISABLED_OPTION_STRING)
else:
choices = [AppController.HYDRA_DISABLED_OPTION_STRING]
return choices
# Render plugin support
def _rendererPluginChanged(self, plugin):
if self._stageView:
if not self._stageView.SetRendererPlugin(plugin):
# If SetRendererPlugin failed, we need to reset the check mark
# to whatever the currently loaded renderer is.
for action in self._ui.rendererPluginActionGroup.actions():
if action.text() == self._stageView.rendererDisplayName:
action.setChecked(True)
break
# Then display an error message to let the user know something
# went wrong, and disable the menu item so it can't be selected
# again.
for action in self._ui.rendererPluginActionGroup.actions():
if action.pluginType == plugin:
self.statusMessage(
'Renderer not supported: %s' % action.text())
action.setText(action.text() + " (unsupported)")
action.setDisabled(True)
break
else:
# Refresh the AOV menu, settings menu, and pause menu item
self._configureRendererAovs()
self._configureRendererSettings()
self._configurePauseAction()
self._configureStopAction()
def _configureRendererPlugins(self):
if self._stageView:
self._ui.rendererPluginActionGroup = QtWidgets.QActionGroup(self)
self._ui.rendererPluginActionGroup.setExclusive(True)
pluginTypes = self._stageView.GetRendererPlugins()
for pluginType in pluginTypes:
name = self._stageView.GetRendererDisplayName(pluginType)
action = self._ui.menuRendererPlugin.addAction(name)
action.setCheckable(True)
action.pluginType = pluginType
self._ui.rendererPluginActionGroup.addAction(action)
action.triggered[bool].connect(lambda _, pluginType=pluginType:
self._rendererPluginChanged(pluginType))
# Now set the checked box on the current renderer (it should
# have been set by now).
currentRendererId = self._stageView.GetCurrentRendererId()
foundPlugin = False
for action in self._ui.rendererPluginActionGroup.actions():
if action.pluginType == currentRendererId:
action.setChecked(True)
foundPlugin = True
break
# Disable the menu if no plugins were found
self._ui.menuRendererPlugin.setEnabled(foundPlugin)
# Refresh the AOV menu, settings menu, and pause menu item
self._configureRendererAovs()
self._configureRendererSettings()
self._configurePauseAction()
self._configureStopAction()
# Renderer AOV support
def _rendererAovChanged(self, aov):
if self._stageView:
self._stageView.SetRendererAov(aov)
self._ui.aovOtherAction.setText("Other...")
def _configureRendererAovs(self):
if self._stageView:
self._ui.rendererAovActionGroup = QtWidgets.QActionGroup(self)
self._ui.rendererAovActionGroup.setExclusive(True)
self._ui.menuRendererAovs.clear()
aovs = self._stageView.GetRendererAovs()
for aov in aovs:
action = self._ui.menuRendererAovs.addAction(aov)
action.setCheckable(True)
if (aov == "color"):
action.setChecked(True)
action.aov = aov
self._ui.rendererAovActionGroup.addAction(action)
action.triggered[bool].connect(lambda _, aov=aov:
self._rendererAovChanged(aov))
self._ui.menuRendererAovs.addSeparator()
self._ui.aovOtherAction = self._ui.menuRendererAovs.addAction("Other...")
self._ui.aovOtherAction.setCheckable(True)
self._ui.aovOtherAction.aov = "Other"
self._ui.rendererAovActionGroup.addAction(self._ui.aovOtherAction)
self._ui.aovOtherAction.triggered[bool].connect(self._otherAov)
self._ui.menuRendererAovs.setEnabled(len(aovs) != 0)
def _otherAov(self):
# If we've already selected "Other..." as an AOV, populate the current
# AOV name.
initial = ""
if self._ui.aovOtherAction.text() != "Other...":
initial = self._stageView.rendererAovName
aov, ok = QtWidgets.QInputDialog.getText(self._mainWindow, "Other AOVs",
"Enter the aov name. Visualize primvars with \"primvars:name\".",
QtWidgets.QLineEdit.Normal, initial)
if (ok and len(aov) > 0):
self._rendererAovChanged(str(aov))
self._ui.aovOtherAction.setText("Other (%r)..." % str(aov))
else:
for action in self._ui.rendererAovActionGroup.actions():
if action.text() == self._stageView.rendererAovName:
action.setChecked(True)
break
def _rendererSettingsFlagChanged(self, action):
if self._stageView:
self._stageView.SetRendererSetting(action.key, action.isChecked())
def _configureRendererSettings(self):
if self._stageView:
self._ui.menuRendererSettings.clear()
self._ui.settingsFlagActions = []
settings = self._stageView.GetRendererSettingsList()
moreSettings = False
for setting in settings:
if setting.type != UsdImagingGL.RendererSettingType.FLAG:
moreSettings = True
continue
action = self._ui.menuRendererSettings.addAction(setting.name)
action.setCheckable(True)
action.key = str(setting.key)
action.setChecked(self._stageView.GetRendererSetting(setting.key))
action.triggered[bool].connect(lambda _, action=action:
self._rendererSettingsFlagChanged(action))
self._ui.settingsFlagActions.append(action)
if moreSettings:
self._ui.menuRendererSettings.addSeparator()
self._ui.settingsMoreAction = self._ui.menuRendererSettings.addAction("More...")
self._ui.settingsMoreAction.setCheckable(False)
self._ui.settingsMoreAction.triggered[bool].connect(self._moreRendererSettings)
self._ui.menuRendererSettings.setEnabled(len(settings) != 0)
# Close the old "More..." dialog if it's still open
if hasattr(self._ui, 'settingsMoreDialog'):
self._ui.settingsMoreDialog.reject()
def _moreRendererSettings(self):
# Recreate the settings dialog
self._ui.settingsMoreDialog = QtWidgets.QDialog(self._mainWindow)
self._ui.settingsMoreDialog.setWindowTitle("Hydra Settings")
self._ui.settingsMoreWidgets = []
layout = QtWidgets.QVBoxLayout()
# Add settings
groupBox = QtWidgets.QGroupBox()
formLayout = QtWidgets.QFormLayout()
groupBox.setLayout(formLayout)
layout.addWidget(groupBox)
formLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
formLayout.setFormAlignment(QtCore.Qt.AlignRight)
settings = self._stageView.GetRendererSettingsList()
for setting in settings:
if setting.type == UsdImagingGL.RendererSettingType.FLAG:
checkBox = QtWidgets.QCheckBox()
checkBox.setChecked(self._stageView.GetRendererSetting(setting.key))
checkBox.key = str(setting.key)
checkBox.defValue = setting.defValue
formLayout.addRow(setting.name, checkBox)
self._ui.settingsMoreWidgets.append(checkBox)
if setting.type == UsdImagingGL.RendererSettingType.INT:
spinBox = QtWidgets.QSpinBox()
spinBox.setMinimum(-2 ** 31)
spinBox.setMaximum(2 ** 31 - 1)
spinBox.setValue(self._stageView.GetRendererSetting(setting.key))
spinBox.key = str(setting.key)
spinBox.defValue = setting.defValue
formLayout.addRow(setting.name, spinBox)
self._ui.settingsMoreWidgets.append(spinBox)
if setting.type == UsdImagingGL.RendererSettingType.FLOAT:
spinBox = QtWidgets.QDoubleSpinBox()
spinBox.setDecimals(10)
spinBox.setMinimum(-2 ** 31)
spinBox.setMaximum(2 ** 31 - 1)
spinBox.setValue(self._stageView.GetRendererSetting(setting.key))
spinBox.key = str(setting.key)
spinBox.defValue = setting.defValue
formLayout.addRow(setting.name, spinBox)
self._ui.settingsMoreWidgets.append(spinBox)
if setting.type == UsdImagingGL.RendererSettingType.STRING:
lineEdit = QtWidgets.QLineEdit()
lineEdit.setText(self._stageView.GetRendererSetting(setting.key))
lineEdit.key = str(setting.key)
lineEdit.defValue = setting.defValue
formLayout.addRow(setting.name, lineEdit)
self._ui.settingsMoreWidgets.append(lineEdit)
# Add buttons
buttonBox = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Ok |
QtWidgets.QDialogButtonBox.Cancel |
QtWidgets.QDialogButtonBox.RestoreDefaults |
QtWidgets.QDialogButtonBox.Apply)
layout.addWidget(buttonBox)
buttonBox.rejected.connect(self._ui.settingsMoreDialog.reject)
buttonBox.accepted.connect(self._ui.settingsMoreDialog.accept)
self._ui.settingsMoreDialog.accepted.connect(self._applyMoreRendererSettings)
defaultButton = buttonBox.button(QtWidgets.QDialogButtonBox.RestoreDefaults)
defaultButton.clicked.connect(self._resetMoreRendererSettings)
applyButton = buttonBox.button(QtWidgets.QDialogButtonBox.Apply)
applyButton.clicked.connect(self._applyMoreRendererSettings)
self._ui.settingsMoreDialog.setLayout(layout)
self._ui.settingsMoreDialog.show()
def _applyMoreRendererSettings(self):
for widget in self._ui.settingsMoreWidgets:
if isinstance(widget, QtWidgets.QCheckBox):
self._stageView.SetRendererSetting(widget.key, widget.isChecked())
if isinstance(widget, QtWidgets.QSpinBox):
self._stageView.SetRendererSetting(widget.key, widget.value())
if isinstance(widget, QtWidgets.QDoubleSpinBox):
self._stageView.SetRendererSetting(widget.key, widget.value())
if isinstance(widget, QtWidgets.QLineEdit):
self._stageView.SetRendererSetting(widget.key, widget.text())
for action in self._ui.settingsFlagActions:
action.setChecked(self._stageView.GetRendererSetting(action.key))
def _resetMoreRendererSettings(self):
for widget in self._ui.settingsMoreWidgets:
if isinstance(widget, QtWidgets.QCheckBox):
widget.setChecked(widget.defValue)
if isinstance(widget, QtWidgets.QSpinBox):
widget.setValue(widget.defValue)
if isinstance(widget, QtWidgets.QDoubleSpinBox):
widget.setValue(widget.defValue)
if isinstance(widget, QtWidgets.QLineEdit):
widget.setText(widget.defValue)
def _configurePauseAction(self):
if self._stageView:
# This is called when the user picks a new renderer, which
# always starts in an unpaused state.
self._paused = False
self._ui.actionPause.setEnabled(
self._stageView.IsPauseRendererSupported())
self._ui.actionPause.setChecked(self._paused and
self._stageView.IsPauseRendererSupported())
def _configureStopAction(self):
if self._stageView:
# This is called when the user picks a new renderer, which
# always starts in an unstopped state.
self._stopped = False
self._ui.actionStop.setEnabled(
self._stageView.IsStopRendererSupported())
self._ui.actionStop.setChecked(self._stopped and
self._stageView.IsStopRendererSupported())
def _configureColorManagement(self):
enableMenu = (not self._noRender and
UsdImagingGL.Engine.IsColorCorrectionCapable())
self._ui.menuColorCorrection.setEnabled(enableMenu)
# Topology-dependent UI changes
def _reloadVaryingUI(self):
self._clearCaches()
if self._debug:
cProfile.runctx('self._resetPrimView(restoreSelection=False)', globals(), locals(), 'resetPrimView')
p = pstats.Stats('resetPrimView')
p.strip_dirs().sort_stats(-1).print_stats()
else:
self._resetPrimView(restoreSelection=False)
if not self._stageView:
# The second child is self._ui.glFrame, which disappears if
# its size is set to zero.
if self._noRender:
# remove glFrame from the ui
self._ui.glFrame.setParent(None)
# move the attributeBrowser into the primSplitter instead
self._ui.primStageSplitter.addWidget(self._ui.attributeBrowserFrame)
else:
self._stageView = StageView(parent=self._mainWindow,
dataModel=self._dataModel,
printTiming=self._printTiming)
self._stageView.fpsHUDInfo = self._fpsHUDInfo
self._stageView.fpsHUDKeys = self._fpsHUDKeys
self._stageView.signalPrimSelected.connect(self.onPrimSelected)
self._stageView.signalPrimRollover.connect(self.onRollover)
self._stageView.signalMouseDrag.connect(self.onStageViewMouseDrag)
self._stageView.signalErrorMessage.connect(self.statusMessage)
layout = QtWidgets.QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self._ui.glFrame.setLayout(layout)
layout.addWidget(self._stageView)
self._primSearchResults = deque([])
self._attrSearchResults = deque([])
self._primSearchString = ""
self._attrSearchString = ""
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
if self._stageView:
self._stageView.setFocus(QtCore.Qt.TabFocusReason)
self._stageView.rolloverPicking = self._dataModel.viewSettings.rolloverPrimInfo
def _scheduleResizePrimView(self):
""" Schedules a resize of the primView widget.
This will call _resizePrimView when the timer expires
(uses timer coalescing to prevent redundant resizes from occurring).
"""
self._primViewResizeTimer.start(0)
def _resizePrimView(self):
""" Used to coalesce excess calls to resizeColumnToContents.
"""
self._ui.primView.resizeColumnToContents(0)
# Retrieve the list of prims currently expanded in the primTreeWidget
def _getExpandedPrimViewPrims(self):
rootItem = self._ui.primView.invisibleRootItem()
expandedItems = list()
# recursive function for adding all expanded items to expandedItems
def findExpanded(item):
if item.isExpanded():
expandedItems.append(item)
for i in range(item.childCount()):
findExpanded(item.child(i))
findExpanded(rootItem)
expandedPrims = [item.prim for item in expandedItems]
return expandedPrims
# This appears to be "reasonably" performant in normal sized pose caches.
# If it turns out to be too slow, or if we want to do a better job of
# preserving the view the user currently has, we could look into ways of
# reconstructing just the prim tree under the "changed" prim(s). The
# (far and away) faster solution would be to implement our own TreeView
# and model in C++.
def _resetPrimView(self, restoreSelection=True):
expandedPrims = self._getExpandedPrimViewPrims()
with Timer() as t, BusyContext():
startingDepth = 3
self._computeDisplayPredicate()
with self._primViewSelectionBlocker:
self._ui.primView.setUpdatesEnabled(False)
self._ui.primView.clear()
self._primToItemMap.clear()
self._itemsToPush = []
# force new search since we are blowing away the primViewItems
# that may be cached in _primSearchResults
self._primSearchResults = []
self._populateRoots()
# it's confusing to see timing for expand followed by reset with
# the times being similar (esp when they are large)
if not expandedPrims:
self._expandToDepth(startingDepth, suppressTiming=True)
if restoreSelection:
self._refreshPrimViewSelection(expandedPrims)
self._ui.primView.setUpdatesEnabled(True)
self._refreshCameraListAndMenu(preserveCurrCamera = True)
if self._printTiming:
t.PrintTime("reset Prim Browser to depth %d" % startingDepth)
def _resetGUI(self):
"""Perform a full refresh/resync of all GUI contents. This should be
called whenever the USD stage is modified, and assumes that all data
previously fetched from the stage is invalid. In the future, more
granular updates will be supported by listening to UsdNotice objects on
the active stage.
If a prim resync is needed then we fully update the prim view,
otherwise can just do a simplified update to the prim view.
"""
with BusyContext():
if self._hasPrimResync:
self._resetPrimView()
self._hasPrimResync = False
else:
self._resetPrimViewVis(selItemsOnly=False)
self._updatePropertyView()
self._populatePropertyInspector()
self._updateMetadataView()
self._updateLayerStackView()
self._updateCompositionView()
if self._stageView:
self._stageView.update()
def updateGUI(self):
"""Will schedule a full refresh/resync of the GUI contents.
Prefer this to calling _resetGUI() directly, since it will
coalesce multiple calls to this method in to a single refresh.
"""
self._guiResetTimer.start()
def _resetPrimViewVis(self, selItemsOnly=True,
authoredVisHasChanged=True):
"""Updates browser rows' Vis columns... can update just selected
items (and their descendants and ancestors), or all items in the
primView. When authoredVisHasChanged is True, we force each item
to discard any value caches it may be holding onto."""
with Timer() as t:
self._ui.primView.setUpdatesEnabled(False)
rootsToProcess = self.getSelectedItems() if selItemsOnly else \
[self._ui.primView.invisibleRootItem()]
for item in rootsToProcess:
PrimViewItem.propagateVis(item, authoredVisHasChanged)
self._ui.primView.setUpdatesEnabled(True)
if self._printTiming:
t.PrintTime("update vis column")
def _updatePrimView(self):
# Process some more prim view items.
n = min(100, len(self._itemsToPush))
if n:
items = self._itemsToPush[-n:]
del self._itemsToPush[-n:]
for item in items:
item.push()
else:
self._primViewUpdateTimer.stop()
# Option windows ==========================================================
def _setComplexity(self, complexity):
"""Set the complexity and update the UI."""
self._dataModel.viewSettings.complexity = complexity
def _incrementComplexity(self):
"""Jump up to the next level of complexity."""
self._setComplexity(RefinementComplexities.next(
self._dataModel.viewSettings.complexity))
def _decrementComplexity(self):
"""Jump back to the previous level of complexity."""
self._setComplexity(RefinementComplexities.prev(
self._dataModel.viewSettings.complexity))
def _changeComplexity(self, action):
"""Update the complexity from a selected QAction."""
self._setComplexity(RefinementComplexities.fromName(action.text()))
def _adjustFOV(self):
fov = QtWidgets.QInputDialog.getDouble(self._mainWindow, "Adjust FOV",
"Enter a value between 0 and 180", self._dataModel.viewSettings.freeCameraFOV, 0, 180)
if (fov[1]):
self._dataModel.viewSettings.freeCameraFOV = fov[0]
def _adjustClippingPlanes(self, checked):
# Eventually, this will not be accessible when _stageView is None.
# Until then, silently ignore.
if self._stageView:
if (checked):
self._adjustClippingDlg = adjustClipping.AdjustClipping(self._mainWindow,
self._stageView)
self._adjustClippingDlg.finished.connect(
lambda status : self._ui.actionAdjust_Clipping.setChecked(False))
self._adjustClippingDlg.show()
else:
self._adjustClippingDlg.close()
def _adjustDefaultMaterial(self, checked):
if (checked):
self._adjustDefaultMaterialDlg = adjustDefaultMaterial.AdjustDefaultMaterial(
self._mainWindow, self._dataModel.viewSettings)
self._adjustDefaultMaterialDlg.finished.connect(lambda status :
self._ui.actionAdjust_Default_Material.setChecked(False))
self._adjustDefaultMaterialDlg.show()
else:
self._adjustDefaultMaterialDlg.close()
def _togglePreferences(self, checked):
if (checked):
self._preferencesDlg = preferences.Preferences(
self._mainWindow, self._dataModel)
self._preferencesDlg.finished.connect(lambda status :
self._ui.actionPreferences.setChecked(False))
self._preferencesDlg.show()
else:
self._preferencesDlg.close()
def _redrawOptionToggled(self, checked):
self._dataModel.viewSettings.redrawOnScrub = checked
self._ui.frameSlider.setTracking(
self._dataModel.viewSettings.redrawOnScrub)
# Frame-by-frame/Playback functionality ===================================
def _setPlaybackAvailability(self, enabled = True):
isEnabled = len(self._timeSamples) > 1 and enabled
self._playbackAvailable = isEnabled
#If playback is disabled, but the animation is playing...
if not isEnabled and self._dataModel.playing:
self._ui.playButton.click()
self._ui.playButton.setEnabled(isEnabled)
self._ui.frameSlider.setEnabled(isEnabled)
self._ui.actionFrame_Forward.setEnabled(isEnabled)
self._ui.actionFrame_Backwards.setEnabled(isEnabled)
self._ui.frameField.setEnabled(isEnabled
if self._hasTimeSamples else False)
self._ui.frameLabel.setEnabled(isEnabled
if self._hasTimeSamples else False)
self._ui.stageBegin.setEnabled(isEnabled)
self._ui.stageEnd.setEnabled(isEnabled)
self._ui.redrawOnScrub.setEnabled(isEnabled)
self._ui.stepSizeLabel.setEnabled(isEnabled)
self._ui.stepSize.setEnabled(isEnabled)
def _playClicked(self):
if self._ui.playButton.isChecked():
# Enable tracking whilst playing
self._ui.frameSlider.setTracking(True)
# Start playback.
self._dataModel.playing = True
self._ui.playButton.setText("Stop")
# setText() causes the shortcut to be reset to whatever
# Qt thinks it should be based on the text. We know better.
self._setPlayShortcut()
self._fpsHUDInfo[HUDEntries.PLAYBACK] = "..."
self._timer.start()
# For performance, don't update the prim tree view while playing.
self._primViewUpdateTimer.stop()
self._playbackIndex = 0
else:
self._ui.frameSlider.setTracking(self._ui.redrawOnScrub.isChecked())
# Stop playback.
self._dataModel.playing = False
self._ui.playButton.setText("Play")
# setText() causes the shortcut to be reset to whatever
# Qt thinks it should be based on the text. We know better.
self._setPlayShortcut()
self._fpsHUDInfo[HUDEntries.PLAYBACK] = "N/A"
self._timer.stop()
self._primViewUpdateTimer.start()
self._updateOnFrameChange()
def _advanceFrameForPlayback(self):
sleep(max(0, 1. / self.framesPerSecond - (time() - self._lastFrameTime)))
self._lastFrameTime = time()
if self._playbackIndex == 0:
self._startTime = time()
if self._playbackIndex == 4:
self._endTime = time()
delta = (self._endTime - self._startTime)/4.
ms = delta * 1000.
fps = 1. / delta
self._fpsHUDInfo[HUDEntries.PLAYBACK] = "%.2f ms (%.2f FPS)" % (ms, fps)
self._playbackIndex = (self._playbackIndex + 1) % 5
self._advanceFrame()
def _advanceFrame(self):
if self._playbackAvailable:
value = self._ui.frameSlider.value() + 1
if value > self._ui.frameSlider.maximum():
value = self._ui.frameSlider.minimum()
self._ui.frameSlider.setValue(value)
def _retreatFrame(self):
if self._playbackAvailable:
value = self._ui.frameSlider.value() - 1
if value < self._ui.frameSlider.minimum():
value = self._ui.frameSlider.maximum()
self._ui.frameSlider.setValue(value)
def _findClosestFrameIndex(self, timeSample):
"""Find the closest frame index for the given `timeSample`.
Args:
timeSample (float): A time sample value.
Returns:
int: The closest matching frame index or 0 if one cannot be
found.
"""
closestIndex = int(round((timeSample - self._timeSamples[0]) / self.step))
# Bounds checking
# 0 <= closestIndex <= number of time samples - 1
closestIndex = max(0, closestIndex)
closestIndex = min(len(self._timeSamples) - 1, closestIndex)
return closestIndex
def _rangeBeginChanged(self):
value = float(self._ui.rangeBegin.text())
if value != self.realStartTimeCode:
self.realStartTimeCode = value
self._UpdateTimeSamples(resetStageDataOnly=False)
def _stepSizeChanged(self):
value = float(self._ui.stepSize.text())
if value != self.step:
self.step = value
self._UpdateTimeSamples(resetStageDataOnly=False)
def _rangeEndChanged(self):
value = float(self._ui.rangeEnd.text())
if value != self.realEndTimeCode:
self.realEndTimeCode = value
self._UpdateTimeSamples(resetStageDataOnly=False)
def _frameStringChanged(self):
value = float(self._ui.frameField.text())
self.setFrame(value)
def _sliderMoved(self, frameIndex):
"""Slot called when the frame slider is moved by a user.
Args:
frameIndex (int): The new frame index value.
"""
# If redraw on scrub is disabled, ensure we still update the
# frame field.
if not self._ui.redrawOnScrub.isChecked():
self.setFrameField(self._timeSamples[frameIndex])
def setFrameField(self, frame):
"""Set the frame field to the given `frame`.
Args:
frame (str|int|float): The new frame value.
"""
frame = round(float(frame), ndigits=2)
self._ui.frameField.setText(str(frame))
# Prim/Attribute search functionality =====================================
def _findPrims(self, pattern, useRegex=True):
"""Search the Usd Stage for matching prims
"""
# If pattern doesn't contain regexp special chars, drop
# down to simple search, as it's faster
if useRegex and re.match("^[0-9_A-Za-z]+$", pattern):
useRegex = False
if useRegex:
isMatch = re.compile(pattern, re.IGNORECASE).search
else:
pattern = pattern.lower()
isMatch = lambda x: pattern in x.lower()
matches = [prim.GetPath() for prim
in Usd.PrimRange.Stage(self._dataModel.stage,
self._displayPredicate)
if isMatch(prim.GetName())]
if self._dataModel.viewSettings.showAllMasterPrims:
for master in self._dataModel.stage.GetMasters():
matches += [prim.GetPath() for prim
in Usd.PrimRange(master, self._displayPredicate)
if isMatch(prim.GetName())]
return matches
def _primViewFindNext(self):
if (self._primSearchString == self._ui.primViewLineEdit.text() and
len(self._primSearchResults) > 0 and
self._lastPrimSearched == self._dataModel.selection.getFocusPrim()):
# Go to the next result of the currently ongoing search.
# First time through, we'll be converting from SdfPaths
# to items (see the append() below)
nextResult = self._primSearchResults.popleft()
if isinstance(nextResult, Sdf.Path):
nextResult = self._getItemAtPath(nextResult)
if nextResult:
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
self._dataModel.selection.addPrim(nextResult.prim)
self._primSearchResults.append(nextResult)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
self._ui.primView.setCurrentItem(nextResult)
# The path is effectively pruned if we couldn't map the
# path to an item
else:
# Begin a new search
with Timer() as t:
self._primSearchString = self._ui.primViewLineEdit.text()
self._primSearchResults = self._findPrims(str(self._ui.primViewLineEdit.text()))
self._primSearchResults = deque(self._primSearchResults)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
selectedPrim = self._dataModel.selection.getFocusPrim()
# reorders search results so results are centered on selected
# prim. this could be optimized, but a binary search with a
# custom operator for the result closest to and after the
# selected prim is messier to implement.
if (selectedPrim != None and
selectedPrim != self._dataModel.stage.GetPseudoRoot() and
len(self._primSearchResults) > 0):
for i in range(len(self._primSearchResults)):
searchResultPath = self._primSearchResults[0]
selectedPath = selectedPrim.GetPath()
if self._comparePaths(searchResultPath, selectedPath) < 1:
self._primSearchResults.rotate(-1)
else:
break
if (len(self._primSearchResults) > 0):
self._primViewFindNext()
if self._printTiming:
t.PrintTime("match '%s' (%d matches)" %
(self._primSearchString,
len(self._primSearchResults)))
# returns -1 if path1 appears before path2 in flattened tree
# returns 0 if path1 and path2 are equal
# returns 1 if path2 appears before path1 in flattened tree
def _comparePaths(self, path1, path2):
# function for removing a certain number of elements from a path
def stripPath(path, numElements):
strippedPath = path
for i in range(numElements):
strippedPath = strippedPath.GetParentPath()
return strippedPath
lca = path1.GetCommonPrefix(path2)
path1NumElements = path1.pathElementCount
path2NumElements = path2.pathElementCount
lcaNumElements = lca.pathElementCount
if path1 == path2:
return 0
if lca == path1:
return -1
if lca == path2:
return 1
path1Stripped = stripPath(path1, path1NumElements - (lcaNumElements + 1))
path2Stripped = stripPath(path2, path2NumElements - (lcaNumElements + 1))
lcaChildrenPrims = self._getFilteredChildren(self._dataModel.stage.GetPrimAtPath(lca))
lcaChildrenPaths = [prim.GetPath() for prim in lcaChildrenPrims]
indexPath1 = lcaChildrenPaths.index(path1Stripped)
indexPath2 = lcaChildrenPaths.index(path2Stripped)
if (indexPath1 < indexPath2):
return -1
if (indexPath1 > indexPath2):
return 1
else:
return 0
def _primLegendToggleCollapse(self):
ToggleLegendWithBrowser(self._ui.primLegendContainer,
self._ui.primLegendQButton,
self._primLegendAnim)
def _propertyLegendToggleCollapse(self):
ToggleLegendWithBrowser(self._ui.propertyLegendContainer,
self._ui.propertyLegendQButton,
self._propertyLegendAnim)
def _attrViewFindNext(self):
if (self._attrSearchString == self._ui.attrViewLineEdit.text() and
len(self._attrSearchResults) > 0 and
self._lastPrimSearched == self._dataModel.selection.getFocusPrim()):
# Go to the next result of the currently ongoing search
nextResult = self._attrSearchResults.popleft()
itemName = str(nextResult.text(PropertyViewIndex.NAME))
selectedProp = self._propertiesDict[itemName]
if isinstance(selectedProp, CustomAttribute):
self._dataModel.selection.clearProps()
self._dataModel.selection.setComputedProp(selectedProp)
else:
self._dataModel.selection.setProp(selectedProp)
self._dataModel.selection.clearComputedProps()
self._ui.propertyView.scrollToItem(nextResult)
self._attrSearchResults.append(nextResult)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
self._ui.attributeValueEditor.populate(
self._dataModel.selection.getFocusPrim().GetPath(), itemName)
self._updateMetadataView(self._getSelectedObject())
self._updateLayerStackView(self._getSelectedObject())
else:
# Begin a new search
self._attrSearchString = self._ui.attrViewLineEdit.text()
attrSearchItems = self._ui.propertyView.findItems(
self._ui.attrViewLineEdit.text(),
QtCore.Qt.MatchRegExp,
PropertyViewIndex.NAME)
# Now just search for the string itself
otherSearch = self._ui.propertyView.findItems(
self._ui.attrViewLineEdit.text(),
QtCore.Qt.MatchContains,
PropertyViewIndex.NAME)
combinedItems = attrSearchItems + otherSearch
# We find properties first, then connections/targets
# Based on the default recursive match finding in Qt.
combinedItems.sort()
self._attrSearchResults = deque(combinedItems)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
if (len(self._attrSearchResults) > 0):
self._attrViewFindNext()
@classmethod
def _outputBaseDirectory(cls):
if os.getenv('PXR_USDVIEW_SUPPRESS_STATE_SAVING', "0") == "1":
return None
homeDirRoot = os.getenv('HOME') or os.path.expanduser('~')
baseDir = os.path.join(homeDirRoot, '.usdview')
try:
if not os.path.exists(baseDir):
os.makedirs(baseDir)
return baseDir
except OSError:
sys.stderr.write("ERROR: Unable to create base directory '%s' "
"for settings file, settings will not be saved.\n"
% baseDir)
return None
# View adjustment functionality ===========================================
def _storeAndReturnViewState(self):
lastView = self._lastViewContext
self._lastViewContext = self._stageView.copyViewState()
return lastView
def _frameSelection(self):
if self._stageView:
# Save all the pertinent attribute values (for _toggleFramedView)
self._storeAndReturnViewState() # ignore return val - we're stomping it
self._stageView.updateView(True, True) # compute bbox on frame selection
def _toggleFramedView(self):
if self._stageView:
self._stageView.restoreViewState(self._storeAndReturnViewState())
def _resetSettings(self):
"""Reloads the UI and Sets up the initial settings for the
_stageView object created in _reloadVaryingUI"""
# Seems like a good time to clear the texture registry
Glf.TextureRegistry.Reset()
# RELOAD fixed and varying UI
self._reloadFixedUI()
self._reloadVaryingUI()
if self._stageView:
self._stageView.update()
self._ui.actionFreeCam._prim = None
self._ui.actionFreeCam.triggered.connect(
lambda : self._cameraSelectionChanged(None))
if self._stageView:
self._stageView.signalSwitchedToFreeCam.connect(
lambda : self._cameraSelectionChanged(None))
self._refreshCameraListAndMenu(preserveCurrCamera = False)
def _updateForStageChanges(self, hasPrimResync=True):
"""Assuming there have been authoring changes to the already-loaded
stage, make the minimal updates to the UI required to maintain a
consistent state. This may still be over-zealous until we know
what actually changed, but we should be able to preserve camera and
playback positions (unless viewing through a stage camera that no
longer exists"""
self._hasPrimResync = hasPrimResync or self._hasPrimResync
self._clearCaches(preserveCamera=True)
# Update the UIs (it gets all of them) and StageView on a timer
self.updateGUI()
def _cacheViewerModeEscapeSizes(self, pos=None, index=None):
topHeight, bottomHeight = self._ui.topBottomSplitter.sizes()
primViewWidth, stageViewWidth = self._ui.primStageSplitter.sizes()
if bottomHeight > 0 or primViewWidth > 0:
self._viewerModeEscapeSizes = topHeight, bottomHeight, primViewWidth, stageViewWidth
else:
self._viewerModeEscapeSizes = None
def _toggleViewerMode(self):
topHeight, bottomHeight = self._ui.topBottomSplitter.sizes()
primViewWidth, stageViewWidth = self._ui.primStageSplitter.sizes()
if bottomHeight > 0 or primViewWidth > 0:
topHeight += bottomHeight
bottomHeight = 0
stageViewWidth += primViewWidth
primViewWidth = 0
else:
if self._viewerModeEscapeSizes is not None:
topHeight, bottomHeight, primViewWidth, stageViewWidth = self._viewerModeEscapeSizes
else:
bottomHeight = UIDefaults.BOTTOM_HEIGHT
topHeight = UIDefaults.TOP_HEIGHT
primViewWidth = UIDefaults.PRIM_VIEW_WIDTH
stageViewWidth = UIDefaults.STAGE_VIEW_WIDTH
self._ui.topBottomSplitter.setSizes([topHeight, bottomHeight])
self._ui.primStageSplitter.setSizes([primViewWidth, stageViewWidth])
def _resetView(self,selectPrim = None):
""" Reverts the GL frame to the initial camera view,
and clears selection (sets to pseudoRoot), UNLESS 'selectPrim' is
not None, in which case we'll select and frame it."""
self._ui.primView.clearSelection()
pRoot = self._dataModel.stage.GetPseudoRoot()
if selectPrim is None:
# if we had a command-line specified selection, re-frame it
selectPrim = self._initialSelectPrim or pRoot
item = self._getItemAtPath(selectPrim.GetPath())
# Our response to selection-change includes redrawing. We do NOT
# want that to happen here, since we are subsequently going to
# change the camera framing (and redraw, again), which can cause
# flickering. So make sure we don't redraw!
self._allowViewUpdates = False
self._ui.primView.setCurrentItem(item)
self._allowViewUpdates = True
if self._stageView:
if (selectPrim and selectPrim != pRoot) or not self._startingPrimCamera:
# _frameSelection translates the camera from wherever it happens
# to be at the time. If we had a starting selection AND a
# primCam, then before framing, switch back to the prim camera
if selectPrim == self._initialSelectPrim and self._startingPrimCamera:
self._dataModel.viewSettings.cameraPrim = self._startingPrimCamera
self._frameSelection()
else:
self._dataModel.viewSettings.cameraPrim = self._startingPrimCamera
self._stageView.updateView()
def _changeRenderMode(self, mode):
self._dataModel.viewSettings.renderMode = str(mode.text())
def _changeColorCorrection(self, mode):
self._dataModel.viewSettings.colorCorrectionMode = str(mode.text())
def _changePickMode(self, mode):
self._dataModel.viewSettings.pickMode = str(mode.text())
def _changeSelHighlightMode(self, mode):
self._dataModel.viewSettings.selHighlightMode = str(mode.text())
def _changeHighlightColor(self, color):
self._dataModel.viewSettings.highlightColorName = str(color.text())
def _changeInterpolationType(self, interpolationType):
for t in Usd.InterpolationType.allValues:
if t.displayName == str(interpolationType.text()):
self._dataModel.stage.SetInterpolationType(t)
self._resetSettings()
break
def _ambientOnlyClicked(self, checked=None):
if self._stageView and checked is not None:
self._dataModel.viewSettings.ambientLightOnly = checked
def _onDomeLightClicked(self, checked=None):
if self._stageView and checked is not None:
self._dataModel.viewSettings.domeLightEnabled = checked
def _changeBgColor(self, mode):
self._dataModel.viewSettings.clearColorText = str(mode.text())
def _toggleShowBBoxPlayback(self):
"""Called when the menu item for showing BBoxes
during playback is activated or deactivated."""
self._dataModel.viewSettings.showBBoxPlayback = (
self._ui.showBBoxPlayback.isChecked())
def _toggleAutoComputeClippingPlanes(self):
autoClip = self._ui.actionAuto_Compute_Clipping_Planes.isChecked()
self._dataModel.viewSettings.autoComputeClippingPlanes = autoClip
if autoClip:
self._stageView.detachAndReClipFromCurrentCamera()
def _setUseExtentsHint(self):
self._dataModel.useExtentsHint = self._ui.useExtentsHint.isChecked()
self._updatePropertyView()
#recompute and display bbox
self._refreshBBox()
def _toggleShowBBoxes(self):
"""Called when the menu item for showing BBoxes
is activated."""
self._dataModel.viewSettings.showBBoxes = self._ui.showBBoxes.isChecked()
#recompute and display bbox
self._refreshBBox()
def _toggleShowAABBox(self):
"""Called when Axis-Aligned bounding boxes
are activated/deactivated via menu item"""
self._dataModel.viewSettings.showAABBox = self._ui.showAABBox.isChecked()
# recompute and display bbox
self._refreshBBox()
def _toggleShowOBBox(self):
"""Called when Oriented bounding boxes
are activated/deactivated via menu item"""
self._dataModel.viewSettings.showOBBox = self._ui.showOBBox.isChecked()
# recompute and display bbox
self._refreshBBox()
def _refreshBBox(self):
"""Recompute and hide/show Bounding Box."""
if self._stageView:
self._stageView.updateView(forceComputeBBox=True)
def _toggleDisplayGuide(self):
self._dataModel.viewSettings.displayGuide = (
self._ui.actionDisplay_Guide.isChecked())
def _toggleDisplayProxy(self):
self._dataModel.viewSettings.displayProxy = (
self._ui.actionDisplay_Proxy.isChecked())
def _toggleDisplayRender(self):
self._dataModel.viewSettings.displayRender = (
self._ui.actionDisplay_Render.isChecked())
def _toggleDisplayCameraOracles(self):
self._dataModel.viewSettings.displayCameraOracles = (
self._ui.actionDisplay_Camera_Oracles.isChecked())
def _toggleDisplayPrimId(self):
self._dataModel.viewSettings.displayPrimId = (
self._ui.actionDisplay_PrimId.isChecked())
def _toggleEnableSceneMaterials(self):
self._dataModel.viewSettings.enableSceneMaterials = (
self._ui.actionEnable_Scene_Materials.isChecked())
def _toggleCullBackfaces(self):
self._dataModel.viewSettings.cullBackfaces = (
self._ui.actionCull_Backfaces.isChecked())
def _showInterpreter(self):
if self._interpreter is None:
self._interpreter = QtWidgets.QDialog(self._mainWindow)
self._interpreter.setObjectName("Interpreter")
self._console = Myconsole(self._interpreter, self._usdviewApi)
self._interpreter.setFocusProxy(self._console) # this is important!
lay = QtWidgets.QVBoxLayout()
lay.addWidget(self._console)
self._interpreter.setLayout(lay)
# dock the interpreter window next to the main usdview window
self._interpreter.move(self._mainWindow.x() + self._mainWindow.frameGeometry().width(),
self._mainWindow.y())
self._interpreter.resize(600, self._mainWindow.size().height()//2)
self._interpreter.show()
self._interpreter.activateWindow()
self._interpreter.setFocus()
def _showDebugFlags(self):
if self._debugFlagsWindow is None:
from .debugFlagsWidget import DebugFlagsWidget
self._debugFlagsWindow = DebugFlagsWidget()
self._debugFlagsWindow.show()
# Screen capture functionality ===========================================
def GrabWindowShot(self):
'''Returns a QImage of the full usdview window '''
# generate an image of the window. Due to how Qt's rendering
# works, this will not pick up the GL Widget(_stageView)'s
# contents, and we'll need to compose it separately.
windowShot = QtGui.QImage(self._mainWindow.size(),
QtGui.QImage.Format_ARGB32_Premultiplied)
painter = QtGui.QPainter(windowShot)
self._mainWindow.render(painter, QtCore.QPoint())
if self._stageView:
# overlay the QGLWidget on and return the composed image
# we offset by a single point here because of Qt.Pos funkyness
offset = QtCore.QPoint(0,1)
pos = self._stageView.mapTo(self._mainWindow, self._stageView.pos()) - offset
painter.drawImage(pos, self.GrabViewportShot())
return windowShot
def GrabViewportShot(self):
'''Returns a QImage of the current stage view in usdview.'''
if self._stageView:
return self._stageView.grabFrameBuffer()
else:
return None
# File handling functionality =============================================
def _cleanAndClose(self):
# This function is called by the main window's closeEvent handler.
self._settings2.save()
# If the current path widget is focused when closing usdview, it can
# trigger an "editingFinished()" signal, which will look for a prim in
# the scene (which is already deleted). This prevents that.
# XXX:
# This method is reentrant and calling disconnect twice on a signal
# causes an exception to be thrown.
try:
self._ui.currentPathWidget.editingFinished.disconnect(
self._currentPathChanged)
except RuntimeError:
pass
# Shut down some timers and our eventFilter
self._primViewUpdateTimer.stop()
self._guiResetTimer.stop()
QtWidgets.QApplication.instance().removeEventFilter(self._filterObj)
# If the timer is currently active, stop it from being invoked while
# the USD stage is being torn down.
if self._timer.isActive():
self._timer.stop()
# Close stage and release renderer resources (if applicable).
self._closeStage()
# Start timer to measure Qt shutdown time
self._startQtShutdownTimer()
def _openFile(self):
extensions = Sdf.FileFormat.FindAllFileFormatExtensions()
builtInFiles = lambda f: f.startswith(".usd")
notBuiltInFiles = lambda f: not f.startswith(".usd")
extensions = list(filter(builtInFiles, extensions)) + \
list(filter(notBuiltInFiles, extensions))
fileFilter = "USD Compatible Files (" + " ".join("*." + e for e in extensions) + ")"
(filename, _) = QtWidgets.QFileDialog.getOpenFileName(
self._mainWindow,
caption="Select file",
dir=".",
filter=fileFilter,
selectedFilter=fileFilter)
if len(filename) > 0:
self._parserData.usdFile = str(filename)
self._mainWindow.setWindowTitle(filename)
self._reopenStage()
def _getSaveFileName(self, caption, recommendedFilename):
(saveName, _) = QtWidgets.QFileDialog.getSaveFileName(
self._mainWindow,
caption,
'./' + recommendedFilename,
'USD Files (*.usd)'
';;USD ASCII Files (*.usda)'
';;USD Crate Files (*.usdc)'
';;Any USD File (*.usd *.usda *.usdc)',
'Any USD File (*.usd *.usda *.usdc)')
if len(saveName) == 0:
return ''
_, ext = os.path.splitext(saveName)
if ext not in ('.usd', '.usda', '.usdc'):
saveName += '.usd'
return saveName
def _saveOverridesAs(self):
recommendedFilename = self._parserData.usdFile.rsplit('.', 1)[0]
recommendedFilename += '_overrides.usd'
saveName = self._getSaveFileName(
'Save Overrides As', recommendedFilename)
if len(saveName) == 0:
return
if not self._dataModel.stage:
return
with BusyContext():
# In the future, we may allow usdview to be brought up with no file,
# in which case it would create an in-memory root layer, to which
# all edits will be targeted. In order to future proof
# this, first fetch the root layer, and if it is anonymous, just
# export it to the given filename. If it isn't anonmyous (i.e., it
# is a regular usd file on disk), export the session layer and add
# the stage root file as a sublayer.
rootLayer = self._dataModel.stage.GetRootLayer()
if not rootLayer.anonymous:
self._dataModel.stage.GetSessionLayer().Export(
saveName, 'Created by UsdView')
targetLayer = Sdf.Layer.FindOrOpen(saveName)
UsdUtils.CopyLayerMetadata(rootLayer, targetLayer,
skipSublayers=True)
# We don't ever store self.realStartTimeCode or
# self.realEndTimeCode in a layer, so we need to author them
# here explicitly.
if self.realStartTimeCode:
targetLayer.startTimeCode = self.realStartTimeCode
if self.realEndTimeCode:
targetLayer.endTimeCode = self.realEndTimeCode
targetLayer.subLayerPaths.append(
self._dataModel.stage.GetRootLayer().realPath)
targetLayer.RemoveInertSceneDescription()
targetLayer.Save()
else:
self._dataModel.stage.GetRootLayer().Export(
saveName, 'Created by UsdView')
def _saveFlattenedAs(self):
recommendedFilename = self._parserData.usdFile.rsplit('.', 1)[0]
recommendedFilename += '_flattened.usd'
saveName = self._getSaveFileName(
'Save Flattened As', recommendedFilename)
if len(saveName) == 0:
return
with BusyContext():
self._dataModel.stage.Export(saveName)
def _togglePause(self):
if self._stageView.IsPauseRendererSupported():
self._paused = not self._paused
self._stageView.SetRendererPaused(self._paused)
self._ui.actionPause.setChecked(self._paused)
def _toggleStop(self):
if self._stageView.IsStopRendererSupported():
# Ask the renderer whether its currently stopped or not
# as the value of the _stopped variable can become out of
# date if for example any camera munging happens
self._stopped = self._stageView.IsRendererConverged()
self._stopped = not self._stopped
self._stageView.SetRendererStopped(self._stopped)
self._ui.actionStop.setChecked(self._stopped)
def _reopenStage(self):
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
# Pause the stage view while we update
if self._stageView:
self._stageView.setUpdatesEnabled(False)
try:
# Clear out any Usd objects that may become invalid.
self._dataModel.selection.clear()
self._currentSpec = None
self._currentLayer = None
# Close the current stage so that we don't keep it in memory
# while trying to open another stage.
self._closeStage()
stage = self._openStage(
self._parserData.usdFile, self._parserData.sessionLayer,
self._parserData.populationMask)
# We need this for layers which were cached in memory but changed on
# disk. The additional Reload call should be cheap when nothing
# actually changed.
stage.Reload()
self._dataModel.stage = stage
self._resetSettings()
self._resetView()
self._stepSizeChanged()
except Exception as err:
self.statusMessage('Error occurred reopening Stage: %s' % err)
traceback.print_exc()
finally:
if self._stageView:
self._stageView.setUpdatesEnabled(True)
QtWidgets.QApplication.restoreOverrideCursor()
self.statusMessage('Stage Reopened')
def _reloadStage(self):
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
try:
self._dataModel.stage.Reload()
# Seems like a good time to clear the texture registry
Glf.TextureRegistry.Reset()
# reset timeline, and playback settings from stage metadata
self._reloadFixedUI(resetStageDataOnly=True)
except Exception as err:
self.statusMessage('Error occurred rereading all layers for Stage: %s' % err)
finally:
QtWidgets.QApplication.restoreOverrideCursor()
self.statusMessage('All Layers Reloaded.')
def _cameraSelectionChanged(self, camera):
self._dataModel.viewSettings.cameraPrim = camera
def _refreshCameraListAndMenu(self, preserveCurrCamera):
self._allSceneCameras = Utils._GetAllPrimsOfType(
self._dataModel.stage, Tf.Type.Find(UsdGeom.Camera))
currCamera = self._startingPrimCamera
if self._stageView:
currCamera = self._dataModel.viewSettings.cameraPrim
self._stageView.allSceneCameras = self._allSceneCameras
# if the stageView is holding an expired camera, clear it first
# and force search for a new one
if currCamera != None and not (currCamera and currCamera.IsActive()):
currCamera = None
self._dataModel.viewSettings.cameraPrim = None
preserveCurrCamera = False
if not preserveCurrCamera:
cameraWasSet = False
def setCamera(camera):
self._startingPrimCamera = currCamera = camera
self._dataModel.viewSettings.cameraPrim = camera
cameraWasSet = True
if self._startingPrimCameraPath:
prim = self._dataModel.stage.GetPrimAtPath(
self._startingPrimCameraPath)
if not prim.IsValid():
msg = sys.stderr
print("WARNING: Camera path %r did not exist in stage"
% self._startingPrimCameraPath, file=msg)
self._startingPrimCameraPath = None
elif not prim.IsA(UsdGeom.Camera):
msg = sys.stderr
print("WARNING: Camera path %r was not a UsdGeom.Camera"
% self._startingPrimCameraPath, file=msg)
self._startingPrimCameraPath = None
else:
setCamera(prim)
if not cameraWasSet and self._startingPrimCameraName:
for camera in self._allSceneCameras:
if camera.GetName() == self._startingPrimCameraName:
setCamera(camera)
break
# Now that we have the current camera and all cameras, build the menu
self._ui.menuCamera.clear()
if len(self._allSceneCameras) == 0:
self._ui.menuCamera.setEnabled(False)
else:
self._ui.menuCamera.setEnabled(True)
currCameraPath = None
if currCamera:
currCameraPath = currCamera.GetPath()
for camera in self._allSceneCameras:
action = self._ui.menuCamera.addAction(camera.GetName())
action.setData(camera.GetPath())
action.setToolTip(str(camera.GetPath()))
action.setCheckable(True)
action.triggered[bool].connect(
lambda _, cam = camera: self._cameraSelectionChanged(cam))
action.setChecked(action.data() == currCameraPath)
def _updatePropertiesFromPropertyView(self):
"""Update the data model's property selection to match property view's
current selection.
"""
selectedProperties = dict()
for item in self._ui.propertyView.selectedItems():
# We define data 'roles' in the property viewer to distinguish between things
# like attributes and attributes with connections, relationships and relationships
# with targets etc etc.
role = item.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
if role in (PropertyViewDataRoles.CONNECTION, PropertyViewDataRoles.TARGET):
# Get the owning property's set of selected targets.
propName = str(item.parent().text(PropertyViewIndex.NAME))
prop = self._propertiesDict[propName]
targets = selectedProperties.setdefault(prop, set())
# Add the target to the set of targets.
targetPath = Sdf.Path(str(item.text(PropertyViewIndex.NAME)))
if role == PropertyViewDataRoles.CONNECTION:
prim = self._dataModel.stage.GetPrimAtPath(
targetPath.GetPrimPath())
target = prim.GetProperty(targetPath.name)
else: # role == PropertyViewDataRoles.TARGET
target = self._dataModel.stage.GetPrimAtPath(
targetPath)
targets.add(target)
else:
propName = str(item.text(PropertyViewIndex.NAME))
prop = self._propertiesDict[propName]
selectedProperties.setdefault(prop, set())
with self._dataModel.selection.batchPropChanges:
self._dataModel.selection.clearProps()
for prop, targets in selectedProperties.items():
if not isinstance(prop, CustomAttribute):
self._dataModel.selection.addProp(prop)
for target in targets:
self._dataModel.selection.addPropTarget(prop, target)
with self._dataModel.selection.batchComputedPropChanges:
self._dataModel.selection.clearComputedProps()
for prop, targets in selectedProperties.items():
if isinstance(prop, CustomAttribute):
self._dataModel.selection.addComputedProp(prop)
def _propertyViewSelectionChanged(self):
"""Called whenever property view's selection changes."""
if self._propertyViewSelectionBlocker.blocked():
return
self._updatePropertiesFromPropertyView()
def _propertyViewCurrentItemChanged(self, currentItem, lastItem):
"""Called whenever property view's current item changes."""
if self._propertyViewSelectionBlocker.blocked():
return
# If a selected item becomes the current item, it will not fire a
# selection changed signal but we still want to change the property
# selection.
if currentItem is not None and currentItem.isSelected():
self._updatePropertiesFromPropertyView()
def _propSelectionChanged(self):
"""Called whenever the property selection in the data model changes.
Updates any UI that relies on the selection state.
"""
self._updatePropertyViewSelection()
self._populatePropertyInspector()
self._updatePropertyInspector()
def _populatePropertyInspector(self):
focusPrimPath = None
focusPropName = None
focusProp = self._dataModel.selection.getFocusProp()
if focusProp is None:
focusPrimPath, focusPropName = (
self._dataModel.selection.getFocusComputedPropPath())
else:
focusPrimPath = focusProp.GetPrimPath()
focusPropName = focusProp.GetName()
if focusPropName is not None:
# inform the value editor that we selected a new attribute
self._ui.attributeValueEditor.populate(focusPrimPath, focusPropName)
else:
self._ui.attributeValueEditor.clear()
def _onCompositionSelectionChanged(self, curr=None, prev=None):
self._currentSpec = getattr(curr, 'spec', None)
self._currentLayer = getattr(curr, 'layer', None)
def _updatePropertyInspector(self, index=None, obj=None):
# index must be the first parameter since this method is used as
# propertyInspector tab widget's currentChanged(int) signal callback
if index is None:
index = self._ui.propertyInspector.currentIndex()
if obj is None:
obj = self._getSelectedObject()
if index == PropertyIndex.METADATA:
self._updateMetadataView(obj)
elif index == PropertyIndex.LAYERSTACK:
self._updateLayerStackView(obj)
elif index == PropertyIndex.COMPOSITION:
self._updateCompositionView(obj)
def _refreshAttributeValue(self):
self._ui.attributeValueEditor.refresh()
def _propertyViewContextMenu(self, point):
item = self._ui.propertyView.itemAt(point)
if item:
self.contextMenu = AttributeViewContextMenu(self._mainWindow,
item, self._dataModel)
self.contextMenu.exec_(QtGui.QCursor.pos())
def _layerStackContextMenu(self, point):
item = self._ui.layerStackView.itemAt(point)
if item:
self.contextMenu = LayerStackContextMenu(self._mainWindow, item)
self.contextMenu.exec_(QtGui.QCursor.pos())
def _compositionTreeContextMenu(self, point):
item = self._ui.compositionTreeWidget.itemAt(point)
self.contextMenu = LayerStackContextMenu(self._mainWindow, item)
self.contextMenu.exec_(QtGui.QCursor.pos())
# Headers & Columns =================================================
def _propertyViewHeaderContextMenu(self, point):
self.contextMenu = HeaderContextMenu(self._ui.propertyView)
self.contextMenu.exec_(QtGui.QCursor.pos())
def _primViewHeaderContextMenu(self, point):
self.contextMenu = HeaderContextMenu(self._ui.primView)
self.contextMenu.exec_(QtGui.QCursor.pos())
# Widget management =================================================
def _changePrimViewDepth(self, action):
"""Signal handler for view-depth menu items
"""
actionTxt = str(action.text())
# recover the depth factor from the action's name
depth = int(actionTxt[actionTxt.find(" ")+1])
self._expandToDepth(depth)
def _expandToDepth(self, depth, suppressTiming=False):
"""Expands treeview prims to the given depth
"""
with Timer() as t, BusyContext():
# Populate items down to depth. Qt will expand items at depth
# depth-1 so we need to have items at depth. We know something
# changed if any items were added to _itemsToPush.
n = len(self._itemsToPush)
self._populateItem(self._dataModel.stage.GetPseudoRoot(),
maxDepth=depth)
changed = (n != len(self._itemsToPush))
# Expand the tree to depth.
self._ui.primView.expandToDepth(depth-1)
if changed:
# Resize column.
self._scheduleResizePrimView()
# Start pushing prim data to the UI during idle cycles.
# Qt doesn't need the data unless the item is actually
# visible (or affects what's visible) but to avoid
# jerky scrolling when that data is pulled during the
# scroll, we can do it ahead of time. But don't do it
# if we're currently playing to maximize playback
# performance.
if not self._dataModel.playing:
self._primViewUpdateTimer.start()
if self._printTiming and not suppressTiming:
t.PrintTime("expand Prim browser to depth %d" % depth)
def _primViewExpanded(self, index):
"""Signal handler for expanded(index), facilitates lazy tree population
"""
self._populateChildren(self._ui.primView.itemFromIndex(index))
self._scheduleResizePrimView()
def _toggleShowInactivePrims(self):
self._dataModel.viewSettings.showInactivePrims = (
self._ui.actionShow_Inactive_Prims.isChecked())
# Note: _toggleShowInactivePrims, _toggleShowMasterPrims,
# _toggleShowUndefinedPrims, and _toggleShowAbstractPrims all call
# _resetPrimView after being toggled, but only from menu items.
# In the future, we should do this when a signal from
# ViewSettingsDataModel is emitted so the prim view always updates
# when they are changed.
self._dataModel.selection.removeInactivePrims()
self._resetPrimView()
def _toggleShowMasterPrims(self):
self._dataModel.viewSettings.showAllMasterPrims = (
self._ui.actionShow_All_Master_Prims.isChecked())
self._dataModel.selection.removeMasterPrims()
self._resetPrimView()
def _toggleShowUndefinedPrims(self):
self._dataModel.viewSettings.showUndefinedPrims = (
self._ui.actionShow_Undefined_Prims.isChecked())
self._dataModel.selection.removeUndefinedPrims()
self._resetPrimView()
def _toggleShowAbstractPrims(self):
self._dataModel.viewSettings.showAbstractPrims = (
self._ui.actionShow_Abstract_Prims.isChecked())
self._dataModel.selection.removeAbstractPrims()
self._resetPrimView()
def _toggleRolloverPrimInfo(self):
self._dataModel.viewSettings.rolloverPrimInfo = (
self._ui.actionRollover_Prim_Info.isChecked())
if self._stageView:
self._stageView.rolloverPicking = self._dataModel.viewSettings.rolloverPrimInfo
def _tallyPrimStats(self, prim):
def _GetType(prim):
typeString = prim.GetTypeName()
return HUDEntries.NOTYPE if not typeString else typeString
childTypeDict = {}
primCount = 0
for child in Usd.PrimRange(prim):
typeString = _GetType(child)
# skip pseudoroot
if typeString is HUDEntries.NOTYPE and not prim.GetParent():
continue
primCount += 1
childTypeDict[typeString] = 1 + childTypeDict.get(typeString, 0)
return (primCount, childTypeDict)
def _populateChildren(self, item, depth=0, maxDepth=1, childrenToAdd=None):
"""Populates the children of the given item in the prim viewer.
If childrenToAdd is given its a list of prims to add as
children."""
if depth < maxDepth and item.prim.IsActive():
if item.needsChildrenPopulated() or childrenToAdd:
# Populate all the children.
if not childrenToAdd:
childrenToAdd = self._getFilteredChildren(item.prim)
item.addChildren([self._populateItem(child, depth+1, maxDepth)
for child in childrenToAdd])
elif depth + 1 < maxDepth:
# The children already exist but we're recursing deeper.
for i in range(item.childCount()):
self._populateChildren(item.child(i), depth+1, maxDepth)
def _populateItem(self, prim, depth=0, maxDepth=0):
"""Populates a prim viewer item."""
item = self._primToItemMap.get(prim)
if not item:
# Create a new item. If we want its children we obviously
# have to create those too.
children = self._getFilteredChildren(prim)
item = PrimViewItem(prim, self, len(children) != 0)
self._primToItemMap[prim] = item
self._populateChildren(item, depth, maxDepth, children)
# Push the item after the children so ancestors are processed
# before descendants.
self._itemsToPush.append(item)
else:
# Item already exists. Its children may or may not exist.
# Either way, we need to have them to get grandchildren.
self._populateChildren(item, depth, maxDepth)
return item
def _populateRoots(self):
invisibleRootItem = self._ui.primView.invisibleRootItem()
rootPrim = self._dataModel.stage.GetPseudoRoot()
rootItem = self._populateItem(rootPrim)
self._populateChildren(rootItem)
if self._dataModel.viewSettings.showAllMasterPrims:
self._populateChildren(rootItem,
childrenToAdd=self._dataModel.stage.GetMasters())
# Add all descendents all at once.
invisibleRootItem.addChild(rootItem)
def _getFilteredChildren(self, prim):
return prim.GetFilteredChildren(self._displayPredicate)
def _computeDisplayPredicate(self):
# Take current browser filtering into account when discovering
# prims while traversing
self._displayPredicate = None
if not self._dataModel.viewSettings.showInactivePrims:
self._displayPredicate = Usd.PrimIsActive \
if self._displayPredicate is None \
else self._displayPredicate & Usd.PrimIsActive
if not self._dataModel.viewSettings.showUndefinedPrims:
self._displayPredicate = Usd.PrimIsDefined \
if self._displayPredicate is None \
else self._displayPredicate & Usd.PrimIsDefined
if not self._dataModel.viewSettings.showAbstractPrims:
self._displayPredicate = ~Usd.PrimIsAbstract \
if self._displayPredicate is None \
else self._displayPredicate & ~Usd.PrimIsAbstract
if self._displayPredicate is None:
self._displayPredicate = Usd._PrimFlagsPredicate.Tautology()
# Unless user experience indicates otherwise, we think we always
# want to show instance proxies
self._displayPredicate = Usd.TraverseInstanceProxies(self._displayPredicate)
def _getItemAtPath(self, path, ensureExpanded=False):
# If the prim hasn't been expanded yet, drill down into it.
# Note the explicit str(path) in the following expr is necessary
# because path may be a QString.
path = path if isinstance(path, Sdf.Path) else Sdf.Path(str(path))
parent = self._dataModel.stage.GetPrimAtPath(path)
if not parent:
raise RuntimeError("Prim not found at path in stage: %s" % str(path))
pseudoRoot = self._dataModel.stage.GetPseudoRoot()
if parent not in self._primToItemMap:
# find the first loaded parent
childList = []
while parent != pseudoRoot \
and not parent in self._primToItemMap:
childList.append(parent)
parent = parent.GetParent()
# go one step further, since the first item found could be hidden
# under a norgie and we would want to populate its siblings as well
if parent != pseudoRoot:
childList.append(parent)
# now populate down to the child
for parent in reversed(childList):
try:
item = self._primToItemMap[parent]
self._populateChildren(item)
if ensureExpanded:
item.setExpanded(True)
except:
item = None
# finally, return the requested item, which now should be in
# the map. If something has been added, this can fail. Not
# sure how to rebuild or add this to the map in a minimal way,
# but after the first hiccup, I don't see any ill
# effects. Would love to know a better way...
# - wave 04.17.2018
prim = self._dataModel.stage.GetPrimAtPath(path)
try:
item = self._primToItemMap[prim]
except:
item = None
return item
def selectPseudoroot(self):
"""Selects only the pseudoroot."""
self._dataModel.selection.clearPrims()
def selectEnclosingModel(self):
"""Iterates through all selected prims, selecting their containing model
instead if they are not a model themselves.
"""
oldPrims = self._dataModel.selection.getPrims()
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in oldPrims:
model = GetEnclosingModelPrim(prim)
if model:
self._dataModel.selection.addPrim(model)
else:
self._dataModel.selection.addPrim(prim)
def selectBoundMaterialForPurpose(self, materialPurpose):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
oldPrims = self._dataModel.selection.getPrims()
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in oldPrims:
(boundMaterial, bindingRel) = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=materialPurpose)
if boundMaterial:
self._dataModel.selection.addPrim(boundMaterial.GetPrim())
def selectBindingRelForPurpose(self, materialPurpose):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
relsToSelect = []
oldPrims = self._dataModel.selection.getPrims()
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in oldPrims:
(boundMaterial, bindingRel) = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=materialPurpose)
if boundMaterial and bindingRel:
self._dataModel.selection.addPrim(bindingRel.GetPrim())
relsToSelect.append(bindingRel)
with self._dataModel.selection.batchPropChanges:
self._dataModel.selection.clearProps()
for rel in relsToSelect:
self._dataModel.selection.addProp(rel)
def selectBoundPreviewMaterial(self):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
self.selectBoundMaterialForPurpose(
materialPurpose=UsdShade.Tokens.preview)
def selectBoundFullMaterial(self):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
self.selectBoundMaterialForPurpose(
materialPurpose=UsdShade.Tokens.full)
def selectPreviewBindingRel(self):
"""Iterates through all selected prims, computing their resolved
"preview" bindings and selecting the cooresponding binding relationship.
"""
self.selectBindingRelForPurpose(materialPurpose=UsdShade.Tokens.preview)
def selectFullBindingRel(self):
"""Iterates through all selected prims, computing their resolved
"full" bindings and selecting the cooresponding binding relationship.
"""
self.selectBindingRelForPurpose(materialPurpose=UsdShade.Tokens.full)
def _getCommonPrims(self, pathsList):
commonPrefix = os.path.commonprefix(pathsList)
### To prevent /Canopies/TwigA and /Canopies/TwigB
### from registering /Canopies/Twig as prefix
return commonPrefix.rsplit('/', 1)[0]
def _primSelectionChanged(self, added, removed):
"""Called when the prim selection is updated in the data model. Updates
any UI that depends on the state of the selection.
"""
with self._primViewSelectionBlocker:
self._updatePrimViewSelection(added, removed)
self._updatePrimPathText()
if self._stageView:
self._updateHUDPrimStats()
self._updateHUDGeomCounts()
self._stageView.updateView()
self._updatePropertyInspector(
obj=self._dataModel.selection.getFocusPrim())
self._updatePropertyView()
self._refreshAttributeValue()
def _getPrimsFromPaths(self, paths):
"""Get all prims from a list of paths."""
prims = []
for path in paths:
# Ensure we have an Sdf.Path, not a string.
sdfPath = Sdf.Path(str(path))
prim = self._dataModel.stage.GetPrimAtPath(
sdfPath.GetAbsoluteRootOrPrimPath())
if not prim:
raise PrimNotFoundException(sdfPath)
prims.append(prim)
return prims
def _updatePrimPathText(self):
self._ui.currentPathWidget.setText(
', '.join([str(prim.GetPath())
for prim in self._dataModel.selection.getPrims()]))
def _currentPathChanged(self):
"""Called when the currentPathWidget text is changed"""
newPaths = self._ui.currentPathWidget.text()
pathList = re.split(", ?", newPaths)
pathList = [path for path in pathList if len(path) != 0]
try:
prims = self._getPrimsFromPaths(pathList)
except PrimNotFoundException as ex:
# _getPrimsFromPaths couldn't find one of the prims
sys.stderr.write("ERROR: %s\n" % str(ex))
self._updatePrimPathText()
return
explicitProps = any(Sdf.Path(str(path)).IsPropertyPath()
for path in pathList)
if len(prims) == 1 and not explicitProps:
self._dataModel.selection.switchToPrimPath(prims[0].GetPath())
else:
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in prims:
self._dataModel.selection.addPrim(prim)
with self._dataModel.selection.batchPropChanges:
self._dataModel.selection.clearProps()
for path, prim in zip(pathList, prims):
sdfPath = Sdf.Path(str(path))
if sdfPath.IsPropertyPath():
self._dataModel.selection.addPropPath(path)
self._dataModel.selection.clearComputedProps()
# A function for maintaining the primview. For each prim in prims,
# first check that it exists. Then if its item has not
# yet been populated, use _getItemAtPath to populate its "chain"
# of parents, so that the prim's item can be accessed. If it
# does already exist in the _primToItemMap, either expand or
# unexpand the item.
def _expandPrims(self, prims, expand=True):
if prims:
for prim in prims:
if prim:
item = self._primToItemMap.get(prim)
if not item:
primPath = prim.GetPrimPath()
item = self._getItemAtPath(primPath)
# Depending on our "Show Prim" settings, a valid,
# yet inactive, undefined, or abstract prim may
# not yield an item at all.
if item:
item.setExpanded(expand)
def _refreshPrimViewSelection(self, expandedPrims):
"""Refresh the selected prim view items to match the selection data
model.
"""
self._ui.primView.clearSelection()
selectedItems = [
self._getItemAtPath(prim.GetPath())
for prim in self._dataModel.selection.getPrims()]
if len(selectedItems) > 0:
self._ui.primView.setCurrentItem(selectedItems[0])
# unexpand items that were expanded through setting the current item
currExpandedPrims = self._getExpandedPrimViewPrims()
self._expandPrims(currExpandedPrims, expand=False)
# expand previously expanded items in primview
self._expandPrims(expandedPrims)
self._ui.primView.updateSelection(selectedItems, [])
def _updatePrimViewSelection(self, added, removed):
"""Do an incremental update to primView's selection using the added and
removed prim paths from the selectionDataModel.
"""
addedItems = [
self._getItemAtPath(path)
for path in added ]
removedItems = [ self._getItemAtPath(path) for path in removed ]
self._ui.primView.updateSelection(addedItems, removedItems)
def _primsFromSelectionRanges(self, ranges):
"""Iterate over all prims in a QItemSelection from primView."""
for itemRange in ranges:
for index in itemRange.indexes():
if index.column() == 0:
item = self._ui.primView.itemFromIndex(index)
yield item.prim
def _selectionChanged(self, added, removed):
"""Called when primView's selection is changed. If the selection was
changed by a user, update the selection data model with the changes.
"""
if self._primViewSelectionBlocker.blocked():
return
items = self._ui.primView.selectedItems()
if len(items) == 1:
self._dataModel.selection.switchToPrimPath(items[0].prim.GetPath())
else:
with self._dataModel.selection.batchPrimChanges:
for prim in self._primsFromSelectionRanges(added):
self._dataModel.selection.addPrim(prim)
for prim in self._primsFromSelectionRanges(removed):
self._dataModel.selection.removePrim(prim)
def _itemClicked(self, item, col):
# If user clicked in a selected row, we will toggle all selected items;
# otherwise, just the clicked one.
if col == PrimViewColumnIndex.VIS:
itemsToToggle = [ item ]
if item.isSelected():
itemsToToggle = [
self._getItemAtPath(prim.GetPath(), ensureExpanded=True)
for prim in self._dataModel.selection.getPrims()]
changedAny = False
with Timer() as t:
for toToggle in itemsToToggle:
# toggleVis() returns True if the click caused a visibility
# change.
changedOne = toToggle.toggleVis()
if changedOne:
PrimViewItem.propagateVis(toToggle)
changedAny = True
if changedAny:
self.editComplete('Updated prim visibility')
if self._printTiming:
t.PrintTime("update vis column")
def _itemPressed(self, item, col):
if col == PrimViewColumnIndex.DRAWMODE:
self._ui.primView.ShowDrawModeWidgetForItem(item)
def _getPathsFromItems(self, items, prune = False):
# this function returns a list of paths given a list of items if
# prune=True, it excludes certain paths if a parent path is already
# there this avoids double-rendering if both a prim and its parent
# are selected.
#
# Don't include the pseudoroot, though, if it's still selected, because
# leaving it in the pruned list will cause everything else to get
# pruned away!
allPaths = [itm.prim.GetPath() for itm in items]
if not prune:
return allPaths
if len(allPaths) > 1:
allPaths = [p for p in allPaths if p != Sdf.Path.absoluteRootPath]
return Sdf.Path.RemoveDescendentPaths(allPaths)
def _primViewContextMenu(self, point):
item = self._ui.primView.itemAt(point)
self._showPrimContextMenu(item)
def _showPrimContextMenu(self, item):
self.contextMenu = PrimContextMenu(self._mainWindow, item, self)
self.contextMenu.exec_(QtGui.QCursor.pos())
def setFrame(self, frame):
"""Set the `frame`.
Args:
frame (float): The new frame value.
"""
frameIndex = self._findClosestFrameIndex(frame)
self._setFrameIndex(frameIndex)
def _setFrameIndex(self, frameIndex):
"""Set the `frameIndex`.
Args:
frameIndex (int): The new frame index value.
"""
# Ensure the frameIndex exists, if not, return.
try:
frame = self._timeSamples[frameIndex]
except IndexError:
return
currentFrame = Usd.TimeCode(frame)
if self._dataModel.currentFrame != currentFrame:
self._dataModel.currentFrame = currentFrame
self._ui.frameSlider.setValue(frameIndex)
self._updateOnFrameChange()
self.setFrameField(self._dataModel.currentFrame.GetValue())
def _updateGUIForFrameChange(self):
"""Called when the frame changes have finished.
e.g When the playback/scrubbing has stopped.
"""
# slow stuff that we do only when not playing
# topology might have changed, recalculate
self._updateHUDGeomCounts()
self._updatePropertyView()
self._refreshAttributeValue()
# value sources of an attribute can change upon frame change
# due to value clips, so we must update the layer stack.
self._updateLayerStackView()
# refresh the visibility column
self._resetPrimViewVis(selItemsOnly=False, authoredVisHasChanged=False)
def _updateOnFrameChange(self):
"""Called when the frame changes, updates the renderer and such"""
# do not update HUD/BBOX if scrubbing or playing
if not (self._dataModel.playing or self._ui.frameSlider.isSliderDown()):
self._updateGUIForFrameChange()
if self._stageView:
# this is the part that renders
if self._dataModel.playing:
highlightMode = self._dataModel.viewSettings.selHighlightMode
if highlightMode == SelectionHighlightModes.ALWAYS:
# We don't want to resend the selection to the renderer
# every frame during playback unless we are actually going
# to see the selection (which is only when highlight mode is
# ALWAYS).
self._stageView.updateSelection()
self._stageView.updateForPlayback()
else:
self._stageView.updateSelection()
self._stageView.updateView()
def saveFrame(self, fileName):
if self._stageView:
pm = QtGui.QPixmap.grabWindow(self._stageView.winId())
pm.save(fileName, 'TIFF')
def _getPropertiesDict(self):
propertiesDict = OrderedDict()
# leave attribute viewer empty if multiple prims selected
if len(self._dataModel.selection.getPrims()) != 1:
return propertiesDict
prim = self._dataModel.selection.getFocusPrim()
composed = _GetCustomAttributes(prim, self._dataModel)
inheritedPrimvars = UsdGeom.PrimvarsAPI(prim).FindInheritablePrimvars()
# There may be overlap between inheritedProps and prim attributes,
# but that's OK because propsDict will uniquify them below
inheritedProps = [primvar.GetAttr() for primvar in inheritedPrimvars]
props = prim.GetAttributes() + prim.GetRelationships() + inheritedProps
def _cmp(v1, v2):
if v1 < v2:
return -1
if v2 < v1:
return 1
return 0
def cmpFunc(propA, propB):
aName = propA.GetName()
bName = propB.GetName()
return _cmp(aName.lower(), bName.lower())
props.sort(key=cmp_to_key(cmpFunc))
# Add the special composed attributes usdview generates
# at the top of our property list.
for prop in composed:
propertiesDict[prop.GetName()] = prop
for prop in props:
propertiesDict[prop.GetName()] = prop
return propertiesDict
def _propertyViewDeselectItem(self, item):
item.setSelected(False)
for i in range(item.childCount()):
item.child(i).setSelected(False)
def _updatePropertyViewSelection(self):
"""Updates property view's selected items to match the data model."""
focusPrim = self._dataModel.selection.getFocusPrim()
propTargets = self._dataModel.selection.getPropTargets()
computedProps = self._dataModel.selection.getComputedPropPaths()
selectedPrimPropNames = dict()
selectedPrimPropNames.update({prop.GetName(): targets
for prop, targets in propTargets.items()})
selectedPrimPropNames.update({propName: set()
for primPath, propName in computedProps})
rootItem = self._ui.propertyView.invisibleRootItem()
with self._propertyViewSelectionBlocker:
for i in range(rootItem.childCount()):
item = rootItem.child(i)
propName = str(item.text(PropertyViewIndex.NAME))
if propName in selectedPrimPropNames:
item.setSelected(True)
# Select relationships and connections.
targets = {prop.GetPath()
for prop in selectedPrimPropNames[propName]}
for j in range(item.childCount()):
childItem = item.child(j)
targetPath = Sdf.Path(
str(childItem.text(PropertyViewIndex.NAME)))
if targetPath in targets:
childItem.setSelected(True)
else:
self._propertyViewDeselectItem(item)
def _updatePropertyViewInternal(self):
frame = self._dataModel.currentFrame
treeWidget = self._ui.propertyView
treeWidget.setTextElideMode(QtCore.Qt.ElideMiddle)
scrollPosition = treeWidget.verticalScrollBar().value()
# get a dictionary of prim attribs/members and store it in self._propertiesDict
self._propertiesDict = self._getPropertiesDict()
with self._propertyViewSelectionBlocker:
treeWidget.clear()
self._populatePropertyInspector()
curPrimSelection = self._dataModel.selection.getFocusPrim()
currRow = 0
for key, primProperty in self._propertiesDict.items():
targets = None
isInheritedProperty = isinstance(primProperty, Usd.Property) and \
(primProperty.GetPrim() != curPrimSelection)
if type(primProperty) == Usd.Attribute:
if primProperty.HasAuthoredConnections():
typeContent = PropertyViewIcons.ATTRIBUTE_WITH_CONNECTIONS()
typeRole = PropertyViewDataRoles.ATTRIBUTE_WITH_CONNNECTIONS
targets = primProperty.GetConnections()
else:
typeContent = PropertyViewIcons.ATTRIBUTE()
typeRole = PropertyViewDataRoles.ATTRIBUTE
elif isinstance(primProperty, ResolvedBoundMaterial):
typeContent = PropertyViewIcons.COMPOSED()
typeRole = PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS
elif isinstance(primProperty, CustomAttribute):
typeContent = PropertyViewIcons.COMPOSED()
typeRole = PropertyViewDataRoles.COMPOSED
elif isinstance(primProperty, Usd.Relationship):
# Otherwise we have a relationship
targets = primProperty.GetTargets()
if targets:
typeContent = PropertyViewIcons.RELATIONSHIP_WITH_TARGETS()
typeRole = PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS
else:
typeContent = PropertyViewIcons.RELATIONSHIP()
typeRole = PropertyViewDataRoles.RELATIONSHIP
else:
PrintWarning("Property '%s' has unknown property type <%s>." %
(key, type(primProperty)))
continue
valFunc, attrText = GetValueAndDisplayString(primProperty, frame)
item = QtWidgets.QTreeWidgetItem(["", str(key), attrText])
item.rawValue = valFunc()
treeWidget.addTopLevelItem(item)
treeWidget.topLevelItem(currRow).setIcon(PropertyViewIndex.TYPE,
typeContent)
treeWidget.topLevelItem(currRow).setData(PropertyViewIndex.TYPE,
QtCore.Qt.ItemDataRole.WhatsThisRole,
typeRole)
currItem = treeWidget.topLevelItem(currRow)
valTextFont = GetPropertyTextFont(primProperty, frame)
if valTextFont:
currItem.setFont(PropertyViewIndex.VALUE, valTextFont)
currItem.setFont(PropertyViewIndex.NAME, valTextFont)
else:
currItem.setFont(PropertyViewIndex.NAME, UIFonts.BOLD)
fgColor = GetPropertyColor(primProperty, frame)
# Inherited properties are colored 15% darker, along with the
# addition of "(i)" in the type column.
if isInheritedProperty:
# Add "(i)" to the type column to indicate an inherited
# property.
treeWidget.topLevelItem(currRow).setText(PropertyViewIndex.TYPE,
"(i)")
fgColor = fgColor.darker(115)
currItem.setFont(PropertyViewIndex.TYPE, UIFonts.INHERITED)
currItem.setForeground(PropertyViewIndex.NAME, fgColor)
currItem.setForeground(PropertyViewIndex.VALUE, fgColor)
if targets:
childRow = 0
for t in targets:
valTextFont = GetPropertyTextFont(primProperty, frame) or \
UIFonts.BOLD
# USD does not provide or infer values for relationship or
# connection targets, so we don't display them here.
currItem.addChild(
QtWidgets.QTreeWidgetItem(["", str(t), ""]))
currItem.setFont(PropertyViewIndex.VALUE, valTextFont)
child = currItem.child(childRow)
if typeRole == PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS:
child.setIcon(PropertyViewIndex.TYPE,
PropertyViewIcons.TARGET())
child.setData(PropertyViewIndex.TYPE,
QtCore.Qt.ItemDataRole.WhatsThisRole,
PropertyViewDataRoles.TARGET)
else:
child.setIcon(PropertyViewIndex.TYPE,
PropertyViewIcons.CONNECTION())
child.setData(PropertyViewIndex.TYPE,
QtCore.Qt.ItemDataRole.WhatsThisRole,
PropertyViewDataRoles.CONNECTION)
childRow += 1
currRow += 1
self._updatePropertyViewSelection()
# For some reason, resetting the scrollbar position here only works on a
# frame change, not when the prim changes. When the prim changes, the
# scrollbar always stays at the top of the list and setValue() has no
# effect.
treeWidget.verticalScrollBar().setValue(scrollPosition)
def _updatePropertyView(self):
""" Sets the contents of the attribute value viewer """
cursorOverride = not self._timer.isActive()
if cursorOverride:
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
try:
self._updatePropertyViewInternal()
except Exception as err:
print("Problem encountered updating attribute view: %s" % err)
raise
finally:
if cursorOverride:
QtWidgets.QApplication.restoreOverrideCursor()
def _getSelectedObject(self):
focusPrim = self._dataModel.selection.getFocusPrim()
attrs = self._ui.propertyView.selectedItems()
if len(attrs) == 0:
return focusPrim
selectedAttribute = attrs[0]
attrName = str(selectedAttribute.text(PropertyViewIndex.NAME))
if PropTreeWidgetTypeIsRel(selectedAttribute):
return focusPrim.GetRelationship(attrName)
obj = focusPrim.GetAttribute(attrName)
if not obj:
# Check if it is an inherited primvar.
inheritedPrimvar = UsdGeom.PrimvarsAPI(
focusPrim).FindPrimvarWithInheritance(attrName)
if inheritedPrimvar:
obj = inheritedPrimvar.GetAttr()
return obj
def _findIndentPos(self, s):
for index, char in enumerate(s):
if char != ' ':
return index
return len(s) - 1
def _maxToolTipWidth(self):
return 90
def _maxToolTipHeight(self):
return 32
def _trimWidth(self, s, isList=False):
# We special-case the display offset because list
# items will have </li> tags embedded in them.
offset = 10 if isList else 5
if len(s) >= self._maxToolTipWidth():
# For strings, well do special ellipsis behavior
# which displays the last 5 chars with an ellipsis
# in between. For other values, we simply display a
# trailing ellipsis to indicate more data.
if s[0] == '\'' and s[-1] == '\'':
return (s[:self._maxToolTipWidth() - offset]
+ '...'
+ s[len(s) - offset:])
else:
return s[:self._maxToolTipWidth()] + '...'
return s
def _limitToolTipSize(self, s, isList=False):
ttStr = ''
lines = s.split('<br>')
for index, line in enumerate(lines):
if index+1 > self._maxToolTipHeight():
break
ttStr += self._trimWidth(line, isList)
if not isList and index != len(lines)-1:
ttStr += '<br>'
if (len(lines) > self._maxToolTipHeight()):
ellipsis = ' '*self._findIndentPos(line) + '...'
if isList:
ellipsis = '<li>' + ellipsis + '</li>'
else:
ellipsis += '<br>'
ttStr += ellipsis
ttStr += self._trimWidth(lines[len(lines)-2], isList)
return ttStr
def _addRichTextIndicators(self, s):
# - We'll need to use html-style spaces to ensure they are respected
# in the toolTip which uses richtext formatting.
# - We wrap the tooltip as a paragraph to ensure 's are
# respected by Qt's rendering engine.
return '<p>' + s.replace(' ', ' ') + '</p>'
def _limitValueDisplaySize(self, s):
maxValueChars = 300
return s[:maxValueChars]
def _cleanStr(self, s, repl):
# Remove redundant char seqs and strip newlines.
replaced = str(s).replace('\n', repl)
filtered = [u for (u, _) in groupby(replaced.split())]
return ' '.join(filtered)
def _formatMetadataValueView(self, val):
from pprint import pformat, pprint
valStr = self._cleanStr(val, ' ')
ttStr = ''
isList = False
# For iterable things, like VtArrays and lists, we want to print
# a nice numbered list.
if isinstance(val, list) or getattr(val, "_isVtArray", False):
isList = True
# We manually supply the index for our list elements
# because Qt's richtext processor starts the <ol> numbering at 1.
for index, value in enumerate(val):
last = len(val) - 1
trimmed = self._cleanStr(value, ' ')
ttStr += ("<li>" + str(index) + ": " + trimmed + "</li><br>")
elif isinstance(val, dict):
# We stringify all dict elements so they display more nicely.
# For example, by default, the pprint operation would print a
# Vt Array as Vt.Array(N, (E1, ....). By running it through
# str(..). we'd get [(E1, E2), ....] which is more useful to
# the end user trying to examine their data.
for k, v in val.items():
val[k] = str(v)
# We'll need to strip the quotes generated by the str' operation above
stripQuotes = lambda s: s.replace('\'', '').replace('\"', "")
valStr = stripQuotes(self._cleanStr(val, ' '))
formattedDict = pformat(val)
formattedDictLines = formattedDict.split('\n')
for index, line in enumerate(formattedDictLines):
ttStr += (stripQuotes(line)
+ ('' if index == len(formattedDictLines) - 1 else '<br>'))
else:
ttStr = self._cleanStr(val, '<br>')
valStr = self._limitValueDisplaySize(valStr)
ttStr = self._addRichTextIndicators(
self._limitToolTipSize(ttStr, isList))
return valStr, ttStr
def _updateMetadataView(self, obj=None):
""" Sets the contents of the metadata viewer"""
# XXX: this method gets called multiple times on selection, it
# would be nice to clean that up and ensure we only update as needed.
tableWidget = self._ui.metadataView
self._propertiesDict = self._getPropertiesDict()
# Setup table widget
tableWidget.clearContents()
tableWidget.setRowCount(0)
if obj is None:
obj = self._getSelectedObject()
if not obj:
return
m = obj.GetAllMetadata()
# We have to explicitly add in metadata related to composition arcs
# and value clips here, since GetAllMetadata prunes them out.
#
# XXX: Would be nice to have some official facility to query
# this.
compKeys = [# composition related metadata
"references", "inheritPaths", "specializes",
"payload", "subLayers"]
for k in compKeys:
v = obj.GetMetadata(k)
if not v is None:
m[k] = v
clipMetadata = obj.GetMetadata("clips")
if clipMetadata is None:
clipMetadata = {}
numClipRows = 0
for (clip, data) in clipMetadata.items():
numClipRows += len(data)
m["clips"] = clipMetadata
numMetadataRows = (len(m) - 1) + numClipRows
# Variant selections that don't have a defined variant set will be
# displayed as well to aid debugging. Collect them separately from
# the variant sets.
variantSets = {}
setlessVariantSelections = {}
if (isinstance(obj, Usd.Prim)):
# Get all variant selections as setless and remove the ones we find
# sets for.
setlessVariantSelections = obj.GetVariantSets().GetAllVariantSelections()
variantSetNames = obj.GetVariantSets().GetNames()
for variantSetName in variantSetNames:
variantSet = obj.GetVariantSet(variantSetName)
variantNames = variantSet.GetVariantNames()
variantSelection = variantSet.GetVariantSelection()
combo = VariantComboBox(None, obj, variantSetName, self._mainWindow)
# First index is always empty to indicate no (or invalid)
# variant selection.
combo.addItem('')
for variantName in variantNames:
combo.addItem(variantName)
indexToSelect = combo.findText(variantSelection)
combo.setCurrentIndex(indexToSelect)
variantSets[variantSetName] = combo
# Remove found variant set from setless.
setlessVariantSelections.pop(variantSetName, None)
tableWidget.setRowCount(numMetadataRows + len(variantSets) +
len(setlessVariantSelections) + 2)
rowIndex = 0
# Although most metadata should be presented alphabetically,the most
# user-facing items should be placed at the beginning of the metadata
# list, these consist of [object type], [path], variant sets, active,
# assetInfo, and kind.
def populateMetadataTable(key, val, rowIndex):
attrName = QtWidgets.QTableWidgetItem(str(key))
tableWidget.setItem(rowIndex, 0, attrName)
valStr, ttStr = self._formatMetadataValueView(val)
attrVal = QtWidgets.QTableWidgetItem(valStr)
attrVal.setToolTip(ttStr)
tableWidget.setItem(rowIndex, 1, attrVal)
sortedKeys = sorted(m.keys())
reorderedKeys = ["kind", "assetInfo", "active"]
for key in reorderedKeys:
if key in sortedKeys:
sortedKeys.remove(key)
sortedKeys.insert(0, key)
object_type = "Attribute" if type(obj) is Usd.Attribute \
else "Prim" if type(obj) is Usd.Prim \
else "Relationship" if type(obj) is Usd.Relationship \
else "Unknown"
populateMetadataTable("[object type]", object_type, rowIndex)
rowIndex += 1
populateMetadataTable("[path]", str(obj.GetPath()), rowIndex)
rowIndex += 1
for variantSetName, combo in variantSets.items():
attrName = QtWidgets.QTableWidgetItem(str(variantSetName+ ' variant'))
tableWidget.setItem(rowIndex, 0, attrName)
tableWidget.setCellWidget(rowIndex, 1, combo)
combo.currentIndexChanged.connect(
lambda i, combo=combo: combo.updateVariantSelection(
i, self._printTiming))
rowIndex += 1
# Add all the setless variant selections directly after the variant
# combo boxes
for variantSetName, variantSelection in setlessVariantSelections.items():
attrName = QtWidgets.QTableWidgetItem(str(variantSetName+ ' variant'))
tableWidget.setItem(rowIndex, 0, attrName)
valStr, ttStr = self._formatMetadataValueView(variantSelection)
# Italicized label to stand out when debugging a scene.
label = QtWidgets.QLabel('<i>' + valStr + '</i>')
label.setIndent(3)
label.setToolTip(ttStr)
tableWidget.setCellWidget(rowIndex, 1, label)
rowIndex += 1
for key in sortedKeys:
if key == "clips":
for (clip, metadataGroup) in m[key].items():
attrName = QtWidgets.QTableWidgetItem(str('clips:' + clip))
tableWidget.setItem(rowIndex, 0, attrName)
for metadata in metadataGroup.keys():
dataPair = (metadata, metadataGroup[metadata])
valStr, ttStr = self._formatMetadataValueView(dataPair)
attrVal = QtWidgets.QTableWidgetItem(valStr)
attrVal.setToolTip(ttStr)
tableWidget.setItem(rowIndex, 1, attrVal)
rowIndex += 1
elif key == "customData":
populateMetadataTable(key, obj.GetCustomData(), rowIndex)
rowIndex += 1
else:
populateMetadataTable(key, m[key], rowIndex)
rowIndex += 1
tableWidget.resizeColumnToContents(0)
def _updateCompositionView(self, obj=None):
""" Sets the contents of the composition tree view"""
treeWidget = self._ui.compositionTreeWidget
treeWidget.clear()
# Update current spec & current layer, and push those updates
# to the python console
self._onCompositionSelectionChanged()
# If no prim or attribute selected, nothing to show.
if obj is None:
obj = self._getSelectedObject()
if not obj:
return
# For brevity, we display only the basename of layer paths.
def LabelForLayer(l):
return ('~session~' if l == self._dataModel.stage.GetSessionLayer()
else l.GetDisplayName())
# Create treeview items for all sublayers in the layer tree.
def WalkSublayers(parent, node, layerTree, sublayer=False):
layer = layerTree.layer
spec = layer.GetObjectAtPath(node.path)
item = QtWidgets.QTreeWidgetItem(
parent,
[
LabelForLayer(layer),
'sublayer' if sublayer else node.arcType.displayName,
str(node.GetPathAtIntroduction()),
'yes' if bool(spec) else 'no'
] )
# attributes for selection:
item.layer = layer
item.spec = spec
item.identifier = layer.identifier
# attributes for LayerStackContextMenu:
if layer.realPath:
item.layerPath = layer.realPath
if spec:
item.path = node.path
item.setExpanded(True)
item.setToolTip(0, layer.identifier)
if not spec:
for i in range(item.columnCount()):
item.setForeground(i, UIPropertyValueSourceColors.NONE)
for subtree in layerTree.childTrees:
WalkSublayers(item, node, subtree, True)
return item
# Create treeview items for all nodes in the composition index.
def WalkNodes(parent, node):
nodeItem = WalkSublayers(parent, node, node.layerStack.layerTree)
for child in node.children:
WalkNodes(nodeItem, child)
path = obj.GetPath().GetAbsoluteRootOrPrimPath()
prim = self._dataModel.stage.GetPrimAtPath(path)
if not prim:
return
# Populate the treeview with items from the prim index.
index = prim.GetPrimIndex()
if index.IsValid():
WalkNodes(treeWidget, index.rootNode)
def _updateLayerStackView(self, obj=None):
""" Sets the contents of the layer stack viewer"""
tableWidget = self._ui.layerStackView
# Setup table widget
tableWidget.clearContents()
tableWidget.setRowCount(0)
if obj is None:
obj = self._getSelectedObject()
if not obj:
return
path = obj.GetPath()
# The pseudoroot is different enough from prims and properties that
# it makes more sense to process it separately
if path == Sdf.Path.absoluteRootPath:
layers = GetRootLayerStackInfo(
self._dataModel.stage.GetRootLayer())
tableWidget.setColumnCount(2)
tableWidget.horizontalHeaderItem(1).setText('Layer Offset')
tableWidget.setRowCount(len(layers))
for i, layer in enumerate(layers):
layerItem = QtWidgets.QTableWidgetItem(layer.GetHierarchicalDisplayString())
layerItem.layerPath = layer.layer.realPath
layerItem.identifier = layer.layer.identifier
toolTip = "<b>identifier:</b> @%s@ <br> <b>resolved path:</b> %s" % \
(layer.layer.identifier, layerItem.layerPath)
toolTip = self._limitToolTipSize(toolTip)
layerItem.setToolTip(toolTip)
tableWidget.setItem(i, 0, layerItem)
offsetItem = QtWidgets.QTableWidgetItem(layer.GetOffsetString())
offsetItem.layerPath = layer.layer.realPath
offsetItem.identifier = layer.layer.identifier
toolTip = self._limitToolTipSize(str(layer.offset))
offsetItem.setToolTip(toolTip)
tableWidget.setItem(i, 1, offsetItem)
tableWidget.resizeColumnToContents(0)
else:
specs = []
tableWidget.setColumnCount(3)
header = tableWidget.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
tableWidget.horizontalHeaderItem(1).setText('Path')
if path.IsPropertyPath():
prop = obj.GetPrim().GetProperty(path.name)
specs = prop.GetPropertyStack(self._dataModel.currentFrame)
c3 = "Value" if (len(specs) == 0 or
isinstance(specs[0], Sdf.AttributeSpec)) else "Target Paths"
tableWidget.setHorizontalHeaderItem(2,
QtWidgets.QTableWidgetItem(c3))
else:
specs = obj.GetPrim().GetPrimStack()
tableWidget.setHorizontalHeaderItem(2,
QtWidgets.QTableWidgetItem('Metadata'))
tableWidget.setRowCount(len(specs))
for i, spec in enumerate(specs):
layerItem = QtWidgets.QTableWidgetItem(spec.layer.GetDisplayName())
layerItem.setToolTip(self._limitToolTipSize(spec.layer.realPath))
tableWidget.setItem(i, 0, layerItem)
pathItem = QtWidgets.QTableWidgetItem(spec.path.pathString)
pathItem.setToolTip(self._limitToolTipSize(spec.path.pathString))
tableWidget.setItem(i, 1, pathItem)
if path.IsPropertyPath():
_, valStr = GetValueAndDisplayString(spec,
self._dataModel.currentFrame)
ttStr = valStr
valueItem = QtWidgets.QTableWidgetItem(valStr)
sampleBased = spec.layer.GetNumTimeSamplesForPath(path) > 0
valueItemColor = (UIPropertyValueSourceColors.TIME_SAMPLE if
sampleBased else UIPropertyValueSourceColors.DEFAULT)
valueItem.setForeground(valueItemColor)
valueItem.setToolTip(ttStr)
else:
metadataKeys = spec.GetMetaDataInfoKeys()
metadataDict = {}
for mykey in metadataKeys:
if spec.HasInfo(mykey):
metadataDict[mykey] = spec.GetInfo(mykey)
valStr, ttStr = self._formatMetadataValueView(metadataDict)
valueItem = QtWidgets.QTableWidgetItem(valStr)
valueItem.setToolTip(ttStr)
tableWidget.setItem(i, 2, valueItem)
# Add the data the context menu needs
for j in range(3):
item = tableWidget.item(i, j)
item.layerPath = spec.layer.realPath
item.path = spec.path.pathString
item.identifier = spec.layer.identifier
def _isHUDVisible(self):
"""Checks if the upper HUD is visible by looking at the global HUD
visibility menu as well as the 'Subtree Info' menu"""
return self._dataModel.viewSettings.showHUD and self._dataModel.viewSettings.showHUD_Info
def _updateCameraMaskMenu(self):
if self._ui.actionCameraMask_Full.isChecked():
self._dataModel.viewSettings.cameraMaskMode = CameraMaskModes.FULL
elif self._ui.actionCameraMask_Partial.isChecked():
self._dataModel.viewSettings.cameraMaskMode = CameraMaskModes.PARTIAL
else:
self._dataModel.viewSettings.cameraMaskMode = CameraMaskModes.NONE
def _updateCameraMaskOutlineMenu(self):
self._dataModel.viewSettings.showMask_Outline = (
self._ui.actionCameraMask_Outline.isChecked())
def _pickCameraMaskColor(self):
QtWidgets.QColorDialog.setCustomColor(0, 0xFF000000)
QtWidgets.QColorDialog.setCustomColor(1, 0xFF808080)
color = QtWidgets.QColorDialog.getColor()
color = (
color.redF(),
color.greenF(),
color.blueF(),
color.alphaF()
)
self._dataModel.viewSettings.cameraMaskColor = color
def _updateCameraReticlesInsideMenu(self):
self._dataModel.viewSettings.showReticles_Inside = (
self._ui.actionCameraReticles_Inside.isChecked())
def _updateCameraReticlesOutsideMenu(self):
self._dataModel.viewSettings.showReticles_Outside = (
self._ui.actionCameraReticles_Outside.isChecked())
def _pickCameraReticlesColor(self):
QtWidgets.QColorDialog.setCustomColor(0, 0xFF000000)
QtWidgets.QColorDialog.setCustomColor(1, 0xFF0080FF)
color = QtWidgets.QColorDialog.getColor()
color = (
color.redF(),
color.greenF(),
color.blueF(),
color.alphaF()
)
self._dataModel.viewSettings.cameraReticlesColor = color
def _showHUDChanged(self):
self._dataModel.viewSettings.showHUD = self._ui.actionHUD.isChecked()
def _showHUD_InfoChanged(self):
self._dataModel.viewSettings.showHUD_Info = (
self._ui.actionHUD_Info.isChecked())
def _showHUD_ComplexityChanged(self):
self._dataModel.viewSettings.showHUD_Complexity = (
self._ui.actionHUD_Complexity.isChecked())
def _showHUD_PerformanceChanged(self):
self._dataModel.viewSettings.showHUD_Performance = (
self._ui.actionHUD_Performance.isChecked())
def _showHUD_GPUstatsChanged(self):
self._dataModel.viewSettings.showHUD_GPUstats = (
self._ui.actionHUD_GPUstats.isChecked())
def _getHUDStatKeys(self):
''' returns the keys of the HUD with PRIM and NOTYPE and the top and
CV, VERT, and FACE at the bottom.'''
keys = [k for k in self._upperHUDInfo.keys() if k not in (
HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE, HUDEntries.PRIM, HUDEntries.NOTYPE)]
keys = [HUDEntries.PRIM, HUDEntries.NOTYPE] + keys + [HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE]
return keys
def _updateHUDPrimStats(self):
"""update the upper HUD with the proper prim information"""
self._upperHUDInfo = dict()
if self._isHUDVisible():
currentPaths = [n.GetPath()
for n in self._dataModel.selection.getLCDPrims()
if n.IsActive()]
for pth in currentPaths:
count,types = self._tallyPrimStats(
self._dataModel.stage.GetPrimAtPath(pth))
# no entry for Prim counts? initilize it
if HUDEntries.PRIM not in self._upperHUDInfo:
self._upperHUDInfo[HUDEntries.PRIM] = 0
self._upperHUDInfo[HUDEntries.PRIM] += count
for typeKey in types.keys():
# no entry for this prim type? initilize it
if typeKey not in self._upperHUDInfo:
self._upperHUDInfo[typeKey] = 0
self._upperHUDInfo[typeKey] += types[typeKey]
if self._stageView:
self._stageView.upperHUDInfo = self._upperHUDInfo
self._stageView.HUDStatKeys = self._getHUDStatKeys()
def _updateHUDGeomCounts(self):
"""updates the upper HUD with the right geom counts
calls _getGeomCounts() to get the info, which means it could be cached"""
if not self._isHUDVisible():
return
# we get multiple geom dicts, if we have multiple prims selected
geomDicts = [self._getGeomCounts(n, self._dataModel.currentFrame)
for n in self._dataModel.selection.getLCDPrims()]
for key in (HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE):
self._upperHUDInfo[key] = 0
for gDict in geomDicts:
self._upperHUDInfo[key] += gDict[key]
if self._stageView:
self._stageView.upperHUDInfo = self._upperHUDInfo
self._stageView.HUDStatKeys = self._getHUDStatKeys()
def _clearGeomCountsForPrimPath(self, primPath):
entriesToRemove = []
# Clear all entries whose prim is either an ancestor or a descendant
# of the given prim path.
for (p, frame) in self._geomCounts:
if (primPath.HasPrefix(p.GetPath()) or p.GetPath().HasPrefix(primPath)):
entriesToRemove.append((p, frame))
for entry in entriesToRemove:
del self._geomCounts[entry]
def _getGeomCounts( self, prim, frame ):
"""returns cached geom counts if available, or calls _calculateGeomCounts()"""
if (prim,frame) not in self._geomCounts:
self._calculateGeomCounts( prim, frame )
return self._geomCounts[(prim,frame)]
def _accountForFlattening(self,shape):
"""Helper function for computing geomCounts"""
if len(shape) == 1:
return shape[0] // 3
else:
return shape[0]
def _calculateGeomCounts(self, prim, frame):
"""Computes the number of CVs, Verts, and Faces for each prim and each
frame in the stage (for use by the HUD)"""
# This is expensive enough that we should give the user feedback
# that something is happening...
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
try:
thisDict = {HUDEntries.CV: 0, HUDEntries.VERT: 0, HUDEntries.FACE: 0}
if prim.IsA(UsdGeom.Curves):
curves = UsdGeom.Curves(prim)
vertexCounts = curves.GetCurveVertexCountsAttr().Get(frame)
if vertexCounts is not None:
for count in vertexCounts:
thisDict[HUDEntries.CV] += count
elif prim.IsA(UsdGeom.Mesh):
mesh = UsdGeom.Mesh(prim)
faceVertexCount = mesh.GetFaceVertexCountsAttr().Get(frame)
faceVertexIndices = mesh.GetFaceVertexIndicesAttr().Get(frame)
if faceVertexCount is not None and faceVertexIndices is not None:
uniqueVerts = set(faceVertexIndices)
thisDict[HUDEntries.VERT] += len(uniqueVerts)
thisDict[HUDEntries.FACE] += len(faceVertexCount)
self._geomCounts[(prim,frame)] = thisDict
for child in prim.GetChildren():
childResult = self._getGeomCounts(child, frame)
for key in (HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE):
self._geomCounts[(prim,frame)][key] += childResult[key]
except Exception as err:
print("Error encountered while computing prim subtree HUD info: %s" % err)
finally:
QtWidgets.QApplication.restoreOverrideCursor()
def _updateNavigationMenu(self):
"""Make the Navigation menu items enabled or disabled depending on the
selected prim."""
anyModels = False
anyBoundPreviewMaterials = False
anyBoundFullMaterials = False
for prim in self._dataModel.selection.getPrims():
if prim.IsA(UsdGeom.Imageable):
imageable = UsdGeom.Imageable(prim)
anyModels = anyModels or GetEnclosingModelPrim(prim) is not None
(previewMat,previewBindingRel) =\
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.preview)
anyBoundPreviewMaterials |= bool(previewMat)
(fullMat,fullBindingRel) =\
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.full)
anyBoundFullMaterials |= bool(fullMat)
self._ui.actionSelect_Model_Root.setEnabled(anyModels)
self._ui.actionSelect_Bound_Preview_Material.setEnabled(
anyBoundPreviewMaterials)
self._ui.actionSelect_Preview_Binding_Relationship.setEnabled(
anyBoundPreviewMaterials)
self._ui.actionSelect_Bound_Full_Material.setEnabled(
anyBoundFullMaterials)
self._ui.actionSelect_Full_Binding_Relationship.setEnabled(
anyBoundFullMaterials)
def _updateEditMenu(self):
"""Make the Edit Prim menu items enabled or disabled depending on the
selected prim."""
# Use the descendent-pruned selection set to avoid redundant
# traversal of the stage to answer isLoaded...
anyLoadable, unused = GetPrimsLoadability(
self._dataModel.selection.getLCDPrims())
removeEnabled = False
anyImageable = False
anyActive = False
anyInactive = False
for prim in self._dataModel.selection.getPrims():
if prim.IsA(UsdGeom.Imageable):
imageable = UsdGeom.Imageable(prim)
anyImageable = anyImageable or bool(imageable)
removeEnabled = removeEnabled or HasSessionVis(prim)
if prim.IsActive():
anyActive = True
else:
anyInactive = True
self._ui.actionRemove_Session_Visibility.setEnabled(removeEnabled)
self._ui.actionMake_Visible.setEnabled(anyImageable)
self._ui.actionVis_Only.setEnabled(anyImageable)
self._ui.actionMake_Invisible.setEnabled(anyImageable)
self._ui.actionLoad.setEnabled(anyLoadable)
self._ui.actionUnload.setEnabled(anyLoadable)
self._ui.actionActivate.setEnabled(anyInactive)
self._ui.actionDeactivate.setEnabled(anyActive)
def getSelectedItems(self):
return [self._primToItemMap[n]
for n in self._dataModel.selection.getPrims()
if n in self._primToItemMap]
def _getPrimFromPropString(self, p):
return self._dataModel.stage.GetPrimAtPath(p.split('.')[0])
def visSelectedPrims(self):
with BusyContext():
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.MakeVisible()
self.editComplete('Made selected prims visible')
def visOnlySelectedPrims(self):
with BusyContext():
ResetSessionVisibility(self._dataModel.stage)
InvisRootPrims(self._dataModel.stage)
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.MakeVisible()
self.editComplete('Made ONLY selected prims visible')
def invisSelectedPrims(self):
with BusyContext():
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.MakeInvisible()
self.editComplete('Made selected prims invisible')
def removeVisSelectedPrims(self):
with BusyContext():
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.GetVisibilityAttr().Clear()
self.editComplete("Removed selected prims' visibility opinions")
def resetSessionVisibility(self):
with BusyContext():
ResetSessionVisibility(self._dataModel.stage)
self.editComplete('Removed ALL session visibility opinions.')
def _setSelectedPrimsActivation(self, active):
"""Activate or deactivate all selected prims."""
with BusyContext():
# We can only activate/deactivate prims which are not in a master.
paths = []
for item in self.getSelectedItems():
if item.prim.IsPseudoRoot():
print("WARNING: Cannot change activation of pseudoroot.")
elif item.isInMaster:
print("WARNING: The prim <" + str(item.prim.GetPrimPath()) +
"> is in a master. Cannot change activation.")
else:
paths.append(item.prim.GetPrimPath())
# If we are deactivating prims, clear the selection so it doesn't
# hold onto paths from inactive prims.
if not active:
self._dataModel.selection.clear()
# If we try to deactivate prims one at a time in Usd, some may have
# become invalid by the time we get to them. Instead, we set the
# active state all at once through Sdf.
layer = self._dataModel.stage.GetEditTarget().GetLayer()
with Sdf.ChangeBlock():
for path in paths:
sdfPrim = Sdf.CreatePrimInLayer(layer, path)
sdfPrim.active = active
pathNames = ", ".join(path.name for path in paths)
if active:
self.editComplete("Activated {}.".format(pathNames))
else:
self.editComplete("Deactivated {}.".format(pathNames))
def activateSelectedPrims(self):
self._setSelectedPrimsActivation(True)
def deactivateSelectedPrims(self):
self._setSelectedPrimsActivation(False)
def loadSelectedPrims(self):
with BusyContext():
primNames=[]
for item in self.getSelectedItems():
item.setLoaded(True)
primNames.append(item.name)
self.editComplete("Loaded %s." % primNames)
def unloadSelectedPrims(self):
with BusyContext():
primNames=[]
for item in self.getSelectedItems():
item.setLoaded(False)
primNames.append(item.name)
self.editComplete("Unloaded %s." % primNames)
def onStageViewMouseDrag(self):
return
def onPrimSelected(self, path, instanceIndex, topLevelPath, topLevelInstanceIndex, point, button, modifiers):
# Ignoring middle button until we have something
# meaningfully different for it to do
if button in [QtCore.Qt.LeftButton, QtCore.Qt.RightButton]:
# Expected context-menu behavior is that even with no
# modifiers, if we are activating on something already selected,
# do not change the selection
doContext = (button == QtCore.Qt.RightButton and path
and path != Sdf.Path.emptyPath)
doSelection = True
if doContext:
for selPrim in self._dataModel.selection.getPrims():
selPath = selPrim.GetPath()
if (selPath != Sdf.Path.absoluteRootPath and
path.HasPrefix(selPath)):
doSelection = False
break
if doSelection:
self._dataModel.selection.setPoint(point)
shiftPressed = modifiers & QtCore.Qt.ShiftModifier
ctrlPressed = modifiers & QtCore.Qt.ControlModifier
if path != Sdf.Path.emptyPath:
prim = self._dataModel.stage.GetPrimAtPath(path)
# Model picking ignores instancing, but selects the enclosing
# model of the picked prim.
if self._dataModel.viewSettings.pickMode == PickModes.MODELS:
if prim.IsModel():
model = prim
else:
model = GetEnclosingModelPrim(prim)
if model:
prim = model
instanceIndex = ALL_INSTANCES
# Prim picking selects the top level boundable: either the
# gprim, the top-level point instancer (if it's point
# instanced), or the top level USD instance (if it's marked
# instantiable), whichever is closer to namespace root.
# It discards the instance index.
elif self._dataModel.viewSettings.pickMode == PickModes.PRIMS:
topLevelPrim = self._dataModel.stage.GetPrimAtPath(topLevelPath)
if topLevelPrim:
prim = topLevelPrim
while prim.IsInstanceProxy():
prim = prim.GetParent()
instanceIndex = ALL_INSTANCES
# Instance picking selects the top level boundable, like
# prim picking; but if that prim is a point instancer or
# a USD instance, it selects the particular instance
# containing the picked object.
elif self._dataModel.viewSettings.pickMode == PickModes.INSTANCES:
topLevelPrim = self._dataModel.stage.GetPrimAtPath(topLevelPath)
if topLevelPrim:
prim = topLevelPrim
instanceIndex = topLevelInstanceIndex
if prim.IsInstanceProxy():
while prim.IsInstanceProxy():
prim = prim.GetParent()
instanceIndex = ALL_INSTANCES
# Prototype picking selects a specific instance of the
# actual picked gprim, if the gprim is point-instanced.
# This differs from instance picking by selecting the gprim,
# rather than the prototype subtree; and selecting only one
# drawn instance, rather than all sub-instances of a top-level
# instance (for nested point instancers).
# elif self._dataModel.viewSettings.pickMode == PickModes.PROTOTYPES:
# Just pass the selection info through!
if shiftPressed:
# Clicking prim while holding shift adds it to the
# selection.
self._dataModel.selection.addPrim(prim, instanceIndex)
elif ctrlPressed:
# Clicking prim while holding ctrl toggles it in the
# selection.
self._dataModel.selection.togglePrim(prim, instanceIndex)
else:
# Clicking prim with no modifiers sets it as the
# selection.
self._dataModel.selection.switchToPrimPath(
prim.GetPath(), instanceIndex)
elif not shiftPressed and not ctrlPressed:
# Clicking the background with no modifiers clears the
# selection.
self._dataModel.selection.clear()
if doContext:
item = self._getItemAtPath(path)
self._showPrimContextMenu(item)
# context menu steals mouse release event from the StageView.
# We need to give it one so it can track its interaction
# mode properly
mrEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease,
QtGui.QCursor.pos(),
QtCore.Qt.RightButton,
QtCore.Qt.MouseButtons(QtCore.Qt.RightButton),
QtCore.Qt.KeyboardModifiers())
QtWidgets.QApplication.sendEvent(self._stageView, mrEvent)
def onRollover(self, path, instanceIndex, topLevelPath, topLevelInstanceIndex, modifiers):
prim = self._dataModel.stage.GetPrimAtPath(path)
if prim:
headerStr = ""
propertyStr = ""
materialStr = ""
aiStr = ""
vsStr = ""
model = GetEnclosingModelPrim(prim)
def _MakeModelRelativePath(path, model,
boldPrim=True, boldModel=False):
makeRelative = model and path.HasPrefix(model.GetPath())
if makeRelative:
path = path.MakeRelativePath(model.GetPath().GetParentPath())
pathParts = str(path).split('/')
if boldModel and makeRelative:
pathParts[0] = "<b>%s</b>" % pathParts[0]
if boldPrim:
pathParts[-1] = "<b>%s</b>" % pathParts[-1]
return '/'.join(pathParts)
def _HTMLEscape(s):
return s.replace('&', '&'). \
replace('<', '<'). \
replace('>', '>')
# First add in all model-related data, if present
if model:
groupPath = model.GetPath().GetParentPath()
# Make the model name and prim name bold.
primModelPath = _MakeModelRelativePath(prim.GetPath(),
model, True, True)
headerStr = "%s<br><nobr><small>in group:</small> %s</nobr>" % \
(str(primModelPath),str(groupPath))
# asset info, including computed creation date
mAPI = Usd.ModelAPI(model)
assetInfo = mAPI.GetAssetInfo()
aiStr = "<hr><b>assetInfo</b> for %s:" % model.GetName()
if assetInfo and len(assetInfo) > 0:
specs = model.GetPrimStack()
name, time, owner = GetAssetCreationTime(specs,
mAPI.GetAssetIdentifier())
for key, value in assetInfo.items():
aiStr += "<br> -- <em>%s</em> : %s" % (key, _HTMLEscape(str(value)))
aiStr += "<br><em><small>%s created on %s by %s</small></em>" % \
(_HTMLEscape(name), _HTMLEscape(time),
_HTMLEscape(owner))
else:
aiStr += "<br><small><em>No assetInfo!</em></small>"
# variantSets are by no means required/expected, so if there
# are none, don't bother to declare so.
mVarSets = model.GetVariantSets()
setNames = mVarSets.GetNames()
if len(setNames) > 0:
vsStr = "<hr><b>variantSets</b> on %s:" % model.GetName()
for name in setNames:
sel = mVarSets.GetVariantSelection(name)
vsStr += "<br> -- <em>%s</em> = %s" % (name, sel)
else:
headerStr = _MakeModelRelativePath(path, None)
# Property info: advise about rare visibility and purpose conditions
img = UsdGeom.Imageable(prim)
propertyStr = "<hr><b>Property Summary for %s '%s':</b>" % \
(prim.GetTypeName(), prim.GetName())
# Now cherry pick "important" attrs... could do more, here
if img:
if img.GetVisibilityAttr().ValueMightBeTimeVarying():
propertyStr += "<br> -- <em>visibility</em> varies over time"
purpose = img.GetPurposeAttr().Get()
inheritedPurpose = img.ComputePurpose()
if inheritedPurpose != UsdGeom.Tokens.default_:
propertyStr += "<br> -- <em>purpose</em> is <b>%s</b>%s " %\
(inheritedPurpose, "" if purpose == inheritedPurpose \
else ", <small>(inherited)</small>")
gprim = UsdGeom.Gprim(prim)
if gprim:
ds = gprim.GetDoubleSidedAttr().Get()
orient = gprim.GetOrientationAttr().Get()
propertyStr += "<br> -- <em>doubleSided</em> = %s" % \
( "true" if ds else "false")
propertyStr += "<br> -- <em>orientation</em> = %s" % orient
ptBased = UsdGeom.PointBased(prim)
if ptBased:
# XXX WBN to not have to read points in to get array size
# XXX2 Should try to determine varying topology
points = ptBased.GetPointsAttr().Get(
self._dataModel.currentFrame)
propertyStr += "<br> -- %d points" % len(points)
mesh = UsdGeom.Mesh(prim)
if mesh:
propertyStr += "<br> -- <em>subdivisionScheme</em> = %s" %\
mesh.GetSubdivisionSchemeAttr().Get()
topLevelPrim = self._dataModel.stage.GetPrimAtPath(topLevelPath)
pi = UsdGeom.PointInstancer(topLevelPrim)
if pi:
indices = pi.GetProtoIndicesAttr().Get(
self._dataModel.currentFrame)
propertyStr += "<br> -- <em>%d instances</em>" % len(indices)
protos = pi.GetPrototypesRel().GetForwardedTargets()
propertyStr += "<br> -- <em>%d unique prototypes</em>" % len(protos)
if topLevelInstanceIndex >= 0 and topLevelInstanceIndex < len(indices):
protoIndex = indices[topLevelInstanceIndex]
if protoIndex < len(protos):
currProtoPath = protos[protoIndex]
# If, as is common, proto is beneath the PI,
# strip the PI's prefix for display
if currProtoPath.HasPrefix(path):
currProtoPath = currProtoPath.MakeRelativePath(path)
propertyStr += "<br> -- <em>instance of prototype <%s></em>" % str(currProtoPath)
# Material info - this IS expected
materialStr = "<hr><b>Material assignment:</b>"
materialAssigns = {}
materialAssigns['generic'] = (genericMat, genericBindingRel) = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.allPurpose)
materialAssigns[UsdShade.Tokens.preview] = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.preview)
materialAssigns[UsdShade.Tokens.full] = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.full)
gotValidMaterial = False
for purpose, materialAssign in materialAssigns.items():
(material, bindingRel) = materialAssign
if not material:
continue
gotValidMaterial = True
# skip specific purpose binding display if it is the same
# as the generic binding.
if purpose != 'generic' and bindingRel == genericBindingRel:
continue
# if the material is in the same model, make path
# model-relative
materialStr += "<br><em>%s</em>: %s" % (purpose,
_MakeModelRelativePath(material.GetPath(), model))
bindingRelPath = _MakeModelRelativePath(
bindingRel.GetPath(), model)
materialStr += "<br><small><em>Material binding "\
"relationship: %s</em></small>" % str(bindingRelPath)
if not gotValidMaterial:
materialStr += "<small><em>No assigned Material!</em></small>"
# Instance / master info, if this prim is a native instance, else
# instance index/id if it's from a PointInstancer
instanceStr = ""
if prim.IsInstance():
instanceStr = "<hr><b>Instancing:</b><br>"
instanceStr += "<nobr><small><em>Instance of master:</em></small> %s</nobr>" % \
str(prim.GetMaster().GetPath())
elif topLevelInstanceIndex != -1:
instanceStr = "<hr><b>Instance Id:</b> %d" % topLevelInstanceIndex
# Then put it all together
tip = headerStr + propertyStr + materialStr + instanceStr + aiStr + vsStr
else:
tip = ""
QtWidgets.QToolTip.showText(QtGui.QCursor.pos(), tip, self._stageView)
def processNavKeyEvent(self, kpEvent):
# This method is a standin for a hotkey processor... for now greatly
# limited in scope, as we mostly use Qt's builtin hotkey dispatch.
# Since we want navigation keys to be hover-context-sensitive, we
# cannot use the native mechanism.
key = kpEvent.key()
if key == QtCore.Qt.Key_Right:
self._advanceFrame()
return True
elif key == QtCore.Qt.Key_Left:
self._retreatFrame()
return True
elif key == KeyboardShortcuts.FramingKey:
self._frameSelection()
return False
def _viewSettingChanged(self):
self._refreshViewMenubar()
self._displayPurposeChanged()
self._HUDInfoChanged()
def _refreshViewMenubar(self):
"""Refresh the menubar actions associated with a view setting. This
includes updating checked/unchecked and enabled/disabled states for
actions and submenus to match the values in the ViewSettingsDataModel.
"""
self._refreshRenderModeMenu()
self._refreshColorCorrectionModeMenu()
self._refreshPickModeMenu()
self._refreshComplexityMenu()
self._refreshBBoxMenu()
self._refreshLightsMenu()
self._refreshClearColorsMenu()
self._refreshCameraMenu()
self._refreshCameraGuidesMenu()
self._refreshCameraMaskMenu()
self._refreshCameraReticlesMenu()
self._refreshDisplayPurposesMenu()
self._refreshViewMenu()
self._refreshHUDMenu()
self._refreshShowPrimMenu()
self._refreshRedrawOnScrub()
self._refreshRolloverPrimInfoMenu()
self._refreshSelectionHighlightingMenu()
self._refreshSelectionHighlightColorMenu()
def _refreshRenderModeMenu(self):
for action in self._renderModeActions:
action.setChecked(
str(action.text()) == self._dataModel.viewSettings.renderMode)
def _refreshColorCorrectionModeMenu(self):
for action in self._colorCorrectionActions:
action.setChecked(
str(action.text()) == self._dataModel.viewSettings.colorCorrectionMode)
def _refreshPickModeMenu(self):
for action in self._pickModeActions:
action.setChecked(
str(action.text()) == self._dataModel.viewSettings.pickMode)
def _refreshComplexityMenu(self):
complexityName = self._dataModel.viewSettings.complexity.name
for action in self._complexityActions:
action.setChecked(str(action.text()) == complexityName)
def _refreshBBoxMenu(self):
self._ui.showBBoxes.setChecked(self._dataModel.viewSettings.showBBoxes)
self._ui.showAABBox.setChecked(self._dataModel.viewSettings.showAABBox)
self._ui.showOBBox.setChecked(self._dataModel.viewSettings.showOBBox)
self._ui.showBBoxPlayback.setChecked(
self._dataModel.viewSettings.showBBoxPlayback)
def _refreshLightsMenu(self):
# lighting is not activated until a shaded mode is selected
self._ui.menuLights.setEnabled(
self._dataModel.viewSettings.renderMode in ShadedRenderModes)
self._ui.actionAmbient_Only.setChecked(
self._dataModel.viewSettings.ambientLightOnly)
self._ui.actionDomeLight.setChecked(
self._dataModel.viewSettings.domeLightEnabled)
def _refreshClearColorsMenu(self):
clearColorText = self._dataModel.viewSettings.clearColorText
for action in self._clearColorActions:
action.setChecked(str(action.text()) == clearColorText)
def getActiveCamera(self):
return self._dataModel.viewSettings.cameraPrim
def _refreshCameraMenu(self):
cameraPath = self._dataModel.viewSettings.cameraPath
for action in self._ui.menuCamera.actions():
action.setChecked(action.data() == cameraPath)
def _refreshCameraGuidesMenu(self):
self._ui.actionDisplay_Camera_Oracles.setChecked(
self._dataModel.viewSettings.displayCameraOracles)
self._ui.actionCameraMask_Outline.setChecked(
self._dataModel.viewSettings.showMask_Outline)
def _refreshCameraMaskMenu(self):
viewSettings = self._dataModel.viewSettings
self._ui.actionCameraMask_Full.setChecked(
viewSettings.cameraMaskMode == CameraMaskModes.FULL)
self._ui.actionCameraMask_Partial.setChecked(
viewSettings.cameraMaskMode == CameraMaskModes.PARTIAL)
self._ui.actionCameraMask_None.setChecked(
viewSettings.cameraMaskMode == CameraMaskModes.NONE)
def _refreshCameraReticlesMenu(self):
self._ui.actionCameraReticles_Inside.setChecked(
self._dataModel.viewSettings.showReticles_Inside)
self._ui.actionCameraReticles_Outside.setChecked(
self._dataModel.viewSettings.showReticles_Outside)
def _refreshDisplayPurposesMenu(self):
self._ui.actionDisplay_Guide.setChecked(
self._dataModel.viewSettings.displayGuide)
self._ui.actionDisplay_Proxy.setChecked(
self._dataModel.viewSettings.displayProxy)
self._ui.actionDisplay_Render.setChecked(
self._dataModel.viewSettings.displayRender)
def _refreshViewMenu(self):
self._ui.actionEnable_Scene_Materials.setChecked(
self._dataModel.viewSettings.enableSceneMaterials)
self._ui.actionDisplay_PrimId.setChecked(
self._dataModel.viewSettings.displayPrimId)
self._ui.actionCull_Backfaces.setChecked(
self._dataModel.viewSettings.cullBackfaces)
self._ui.actionAuto_Compute_Clipping_Planes.setChecked(
self._dataModel.viewSettings.autoComputeClippingPlanes)
def _refreshHUDMenu(self):
self._ui.actionHUD.setChecked(self._dataModel.viewSettings.showHUD)
self._ui.actionHUD_Info.setChecked(
self._dataModel.viewSettings.showHUD_Info)
self._ui.actionHUD_Complexity.setChecked(
self._dataModel.viewSettings.showHUD_Complexity)
self._ui.actionHUD_Performance.setChecked(
self._dataModel.viewSettings.showHUD_Performance)
self._ui.actionHUD_GPUstats.setChecked(
self._dataModel.viewSettings.showHUD_GPUstats)
def _refreshShowPrimMenu(self):
self._ui.actionShow_Inactive_Prims.setChecked(
self._dataModel.viewSettings.showInactivePrims)
self._ui.actionShow_All_Master_Prims.setChecked(
self._dataModel.viewSettings.showAllMasterPrims)
self._ui.actionShow_Undefined_Prims.setChecked(
self._dataModel.viewSettings.showUndefinedPrims)
self._ui.actionShow_Abstract_Prims.setChecked(
self._dataModel.viewSettings.showAbstractPrims)
def _refreshRedrawOnScrub(self):
self._ui.redrawOnScrub.setChecked(
self._dataModel.viewSettings.redrawOnScrub)
def _refreshRolloverPrimInfoMenu(self):
self._ui.actionRollover_Prim_Info.setChecked(
self._dataModel.viewSettings.rolloverPrimInfo)
def _refreshSelectionHighlightingMenu(self):
for action in self._selHighlightActions:
action.setChecked(
str(action.text())
== self._dataModel.viewSettings.selHighlightMode)
def _refreshSelectionHighlightColorMenu(self):
for action in self._selHighlightColorActions:
action.setChecked(
str(action.text())
== self._dataModel.viewSettings.highlightColorName)
def _displayPurposeChanged(self):
self._updatePropertyView()
if self._stageView:
self._stageView.updateBboxPurposes()
self._stageView.updateView()
def _HUDInfoChanged(self):
"""Called when a HUD setting that requires info refresh has changed."""
if self._isHUDVisible():
self._updateHUDPrimStats()
self._updateHUDGeomCounts()
def _onPrimsChanged(self, primsChange, propertiesChange):
"""Called when prims in the USD stage have changed."""
from .rootDataModel import ChangeNotice
self._updateForStageChanges(
hasPrimResync=(primsChange==ChangeNotice.RESYNC))
| 216,121 | Python | 42.138124 | 129 | 0.607174 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/settings2.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import os, sys, json
class _StateProp(object):
"""Defines a state property on a StateSource object."""
def __init__(self, name, default, propType, validator):
self.name = name
self.default = default
self.propType = propType
self.validator = validator
class StateSource(object):
"""An object which has some savable application state."""
def __init__(self, parent, name):
self._parentStateSource = parent
self._childStateSources = dict()
self._stateSourceName = name
self._stateSourceProperties = dict()
# Register child source with the parent.
if self._parentStateSource is not None:
self._parentStateSource._registerChildStateSource(self)
def _registerChildStateSource(self, child):
"""Registers a child StateSource with this source object."""
self._childStateSources[child._stateSourceName] = child
def _getState(self):
"""Get this source's state dict from its parent source."""
if self._parentStateSource is None:
return dict()
else:
return self._parentStateSource._getChildState(self._stateSourceName)
def _getChildState(self, childName):
"""Get a child source's state dict. This method guarantees that a dict
will be return but does not guarantee anything about the contents of
the dict.
"""
state = self._getState()
if childName in state:
childState = state[childName]
# Child state could be loaded from file as any JSON-serializable
# type (int, str, etc.). Only return it if it is a dict. Otherwise,
# fallback to empty dict.
if isinstance(childState, dict):
return childState
# Create a new state dict for the child and save it in this source's
# state dict.
childState = dict()
state[childName] = childState
return childState
def _typeCheck(self, value, prop):
"""Validate a value against a StateProp."""
# Make sure the value has the correct type.
valueType = type(value)
if valueType is not prop.propType:
if sys.version_info.major >= 3:
str_types = [str]
else:
str_types = [str, unicode]
if valueType is int and prop.propType is float:
pass # ints are valid for float types.
elif prop.propType in str_types and valueType in str_types:
pass # str and unicode can be used interchangeably.
else:
print("Value {} has type {} but state property {} has type {}.".format(
repr(value), valueType, repr(prop.name), prop.propType),
file=sys.stderr)
print(" Using default value {}.".format(repr(prop.default)),
file=sys.stderr)
return False
# Make sure value passes custom validation. Otherwise, use default value.
if prop.validator(value):
return True
else:
print("Value {} did not pass custom validation for state property {}.".format(
repr(value), repr(prop.name)), file=sys.stderr)
print(" Using default value {}.".format(repr(prop.default)),
file=sys.stderr)
return False
def _saveState(self):
"""Saves the source's state to the settings object's state buffer."""
newState = dict()
# Save state properties.
self.onSaveState(newState)
# Validate state properties.
for name, value in tuple(newState.items()):
if name not in self._stateSourceProperties:
print("State property {} not defined. It will be removed.".format(
repr(name)), file=sys.stderr)
del newState[name]
prop = self._stateSourceProperties[name]
if self._typeCheck(value, prop):
newState[name] = value
else:
newState[name] = prop.default
# Make sure no state properties were forgotten.
for prop in self._stateSourceProperties.values():
if prop.name not in newState:
print("State property {} not saved.".format(repr(prop.name)),
file=sys.stderr)
# Update the real state dict with the new state. This preserves unused
# data loaded from the state file.
self._getState().update(newState)
# Save all child states.
for child in self._childStateSources.values():
child._saveState()
def stateProperty(self, name, default, propType=None, validator=lambda value: True):
"""Validates and creates a new StateProp for this source. The property's
value is returned so this method can be used during StateSource
initialization."""
# Make sure there are no conflicting state properties.
if name in self._stateSourceProperties:
raise RuntimeError("State property name {} already in use.".format(
repr(name)))
# Grab state property type from default value if it was not defined.
if propType is None:
propType = type(default)
# Make sure default value is valid.
if not isinstance(default, propType):
raise RuntimeError("Default value {} does not match type {}.".format(
repr(default), repr(propType)))
if not validator(default):
raise RuntimeError("Default value {} does not pass custom validation "
"for state property {}.".format(repr(default), repr(name)))
prop = _StateProp(name, default, propType, validator)
self._stateSourceProperties[name] = prop
# Load the value from the state dict and validate it.
state = self._getState()
value = state.get(name, default)
if self._typeCheck(value, prop):
return value
else:
return prop.default
def onSaveState(self, state):
"""Save the source's state properties to a dict."""
raise NotImplementedError
class Settings(StateSource):
"""An object which encapsulates saving and loading of application state to
a state file. When created, it loads state from a state file and stores it
in a buffer. Its children sources can fetch their piece of state from the
buffer. On save, this object tells its children to save their current
states, then saves the buffer back to the state file.
"""
def __init__(self, version, stateFilePath=None):
# Settings should be the only StateSource with no parent or name.
StateSource.__init__(self, None, None)
self._version = version
self._stateFilePath = stateFilePath
self._versionsStateBuffer = None
self._stateBuffer = None
self._isEphemeral = (self._stateFilePath is None)
self._loadState()
def _loadState(self):
"""Loads and returns application state from a state file. If the file is
not found, contains invalid JSON, does not contain a dictionary, an
empty state is returned instead.
"""
# Load the dict containing all versions of app state.
if not self._isEphemeral:
try:
with open(self._stateFilePath, "r") as fp:
self._versionsStateBuffer = json.load(fp)
except IOError as e:
if os.path.isfile(self._stateFilePath):
print("Error opening state file: " + str(e), file=sys.stderr)
else:
print("State file not found, a new one will be created.",
file=sys.stderr)
except ValueError:
print("State file contained invalid JSON. Please fix or delete " +
"it. Default settings will be used for this instance of " +
"USDView, but will not be saved.", file=sys.stderr)
self._isEphemeral = True
# Make sure JSON returned a dict.
if not isinstance(self._versionsStateBuffer, dict):
self._versionsStateBuffer = dict()
# Load the correct version of the state dict.
self._stateBuffer = self._versionsStateBuffer.get(self._version, None)
if not isinstance(self._stateBuffer, dict):
self._stateBuffer = dict()
self._versionsStateBuffer[self._version] = self._stateBuffer
# overrides StateSource._getState
def _getState(self):
"""Gets the buffered state rather than asking its parent for its state.
"""
return self._stateBuffer
def save(self):
"""Inform all children to save their states, then write the state buffer
back to the state file.
"""
if not self._isEphemeral:
self._saveState()
try:
with open(self._stateFilePath, "w") as fp:
json.dump(self._versionsStateBuffer, fp,
indent=2, separators=(",", ": "))
except IOError as e:
print("Could not save state file: " + str(e), file=sys.stderr)
def onSaveState(self, state):
"""Settings object has no state properties."""
pass
| 10,551 | Python | 39.274809 | 90 | 0.610748 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/variantComboBox.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from .common import Timer
class VariantComboBox(QtWidgets.QComboBox):
def __init__(self, parent, prim, variantSetName, mainWindow):
QtWidgets.QComboBox.__init__(self, parent)
self.prim = prim
self.variantSetName = variantSetName
def updateVariantSelection(self, index, printTiming):
variantSet = self.prim.GetVariantSet(self.variantSetName)
currentVariantSelection = variantSet.GetVariantSelection()
newVariantSelection = str(self.currentText())
if currentVariantSelection != newVariantSelection:
with Timer() as t:
variantSet.SetVariantSelection(newVariantSelection)
if printTiming:
t.PrintTime("change variantSet %s to %s" %
(variantSet.GetName(), newVariantSelection))
| 1,925 | Python | 40.869564 | 74 | 0.721039 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/freeCamera.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from math import atan, radians as rad
from pxr import Gf, Tf
from .qt import QtCore
from .common import DEBUG_CLIPPING
# FreeCamera inherits from QObject only so that it can send signals...
# which is really a pretty nice, easy to use notification system.
class FreeCamera(QtCore.QObject):
# Allows FreeCamera owner to act when the camera's relationship to
# its viewed content changes. For instance, to compute the value
# to supply for setClosestVisibleDistFromPoint()
signalFrustumChanged = QtCore.Signal()
defaultNear = 1
defaultFar = 2000000
# Experimentally on Nvidia M6000, if Far/Near is greater than this,
# then geometry in the back half of the volume will disappear
maxSafeZResolution = 1e6
# Experimentally on Nvidia M6000, if Far/Near is greater than this,
# then we will often see Z-fighting artifacts even for geometry that
# is close to camera, when rendering for picking
maxGoodZResolution = 5e4
def __init__(self, isZUp, fov=60.0):
"""FreeCamera can be either a Z up or Y up camera, based on 'zUp'"""
super(FreeCamera, self).__init__()
self._camera = Gf.Camera()
self._camera.SetPerspectiveFromAspectRatioAndFieldOfView(
1.0, fov, Gf.Camera.FOVVertical)
self._overrideNear = None
self._overrideFar = None
self.resetClippingPlanes()
self._isZUp = isZUp
self._cameraTransformDirty = True
self._rotTheta = 0
self._rotPhi = 0
self._rotPsi = 0
self._center = Gf.Vec3d(0,0,0)
self._dist = 100
self._camera.focusDistance = self._dist
self._closestVisibleDist = None
self._lastFramedDist = None
self._lastFramedClosestDist = None
self._selSize = 10
if isZUp:
# This is also Gf.Camera.Y_UP_TO_Z_UP_MATRIX
self._YZUpMatrix = Gf.Matrix4d().SetRotate(
Gf.Rotation(Gf.Vec3d.XAxis(), -90))
self._YZUpInvMatrix = self._YZUpMatrix.GetInverse()
else:
self._YZUpMatrix = Gf.Matrix4d(1.0)
self._YZUpInvMatrix = Gf.Matrix4d(1.0)
# Why a clone() method vs copy.deepcopy()ing the FreeCamera ?
# 1) Several of the Gf classes are not python-picklable (requirement of
# deepcopy), nor is GfCamera. Adding that infrastructure for this
# single client seems weighty.
# 2) We could make FreeCamera itself be picklable... that solution would
# require twice as much code as clone(). If we wind up extracting
# FreeCamera to be a more general building block, it may be worth it,
# and clone() would transition to __getstate__().
def clone(self):
clone = FreeCamera(self._isZUp)
clone._camera = Gf.Camera(self._camera)
# skipping stereo attrs for now
clone._rotTheta = self._rotTheta
clone._rotPhi = self._rotPhi
clone._rotPsi = self._rotPsi
clone._center = Gf.Vec3d(self._center)
clone._dist = self._dist
clone._closestVisibleDist = self._closestVisibleDist
clone._lastFramedClosestDist = self._lastFramedClosestDist
clone._lastFramedDist = self._lastFramedDist
clone._selSize = self._selSize
clone._overrideNear = self._overrideNear
clone._overrideFar = self._overrideFar
clone._YZUpMatrix = Gf.Matrix4d(self._YZUpMatrix)
clone._YZUpInvMatrix = Gf.Matrix4d(self._YZUpInvMatrix)
return clone
def _pushToCameraTransform(self):
"""
Updates the camera's transform matrix, that is, the matrix that brings
the camera to the origin, with the camera view pointing down:
+Y if this is a Zup camera, or
-Z if this is a Yup camera .
"""
if not self._cameraTransformDirty:
return
def RotMatrix(vec, angle):
return Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(vec, angle))
# self._YZUpInvMatrix influences the behavior about how the
# FreeCamera will tumble. It is the identity or a rotation about the
# x-Axis.
self._camera.transform = (
Gf.Matrix4d().SetTranslate(Gf.Vec3d.ZAxis() * self.dist) *
RotMatrix(Gf.Vec3d.ZAxis(), -self._rotPsi) *
RotMatrix(Gf.Vec3d.XAxis(), -self._rotPhi) *
RotMatrix(Gf.Vec3d.YAxis(), -self._rotTheta) *
self._YZUpInvMatrix *
Gf.Matrix4d().SetTranslate(self.center))
self._camera.focusDistance = self.dist
self._cameraTransformDirty = False
def _pullFromCameraTransform(self):
"""
Updates parameters (center, rotTheta, etc.) from the camera transform.
"""
# reads the transform set on the camera and updates all the other
# parameters. This is the inverse of _pushToCameraTransform
cam_transform = self._camera.transform
dist = self._camera.focusDistance
frustum = self._camera.frustum
cam_pos = frustum.position
cam_axis = frustum.ComputeViewDirection()
# Compute translational parts
self._dist = dist
self._selSize = dist / 10.0
self._center = cam_pos + dist * cam_axis
# self._YZUpMatrix influences the behavior about how the
# FreeCamera will tumble. It is the identity or a rotation about the
# x-Axis.
# Compute rotational part
transform = cam_transform * self._YZUpMatrix
transform.Orthonormalize()
rotation = transform.ExtractRotation()
# Decompose and set angles
self._rotTheta, self._rotPhi, self._rotPsi = -rotation.Decompose(
Gf.Vec3d.YAxis(), Gf.Vec3d.XAxis(), Gf.Vec3d.ZAxis())
self._cameraTransformDirty = True
def _rangeOfBoxAlongRay(self, camRay, bbox, debugClipping=False):
maxDist = -float('inf')
minDist = float('inf')
boxRange = bbox.GetRange()
boxXform = bbox.GetMatrix()
for i in range (8):
# for each corner of the bounding box, transform to world
# space and project
point = boxXform.Transform(boxRange.GetCorner(i))
pointDist = camRay.FindClosestPoint(point)[1]
# find the projection of that point of the camera ray
# and find the farthest and closest point.
if pointDist > maxDist:
maxDist = pointDist
if pointDist < minDist:
minDist = pointDist
if debugClipping:
print("Projected bounds near/far: %f, %f" % (minDist, maxDist))
# if part of the bbox is behind the ray origin (i.e. camera),
# we clamp minDist to be positive. Otherwise, reduce minDist by a bit
# so that geometry at exactly the edge of the bounds won't be clipped -
# do the same for maxDist, also!
if minDist < FreeCamera.defaultNear:
minDist = FreeCamera.defaultNear
else:
minDist *= 0.99
maxDist *= 1.01
if debugClipping:
print("Contracted bounds near/far: %f, %f" % (minDist, maxDist))
return minDist, maxDist
def setClippingPlanes(self, stageBBox):
'''Computes and sets automatic clipping plane distances using the
camera's position and orientation, the bouding box
surrounding the stage, and the distance to the closest rendered
object in the central view of the camera (closestVisibleDist).
If either of the "override" clipping attributes are not None,
we use those instead'''
debugClipping = Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING)
# If the scene bounding box is empty, or we are fully on manual
# override, then just initialize to defaults.
if stageBBox.GetRange().IsEmpty() or \
(self._overrideNear and self._overrideFar) :
computedNear, computedFar = FreeCamera.defaultNear, FreeCamera.defaultFar
else:
# The problem: We want to include in the camera frustum all the
# geometry the viewer should be able to see, i.e. everything within
# the inifinite frustum starting at distance epsilon from the
# camera itself. However, the further the imageable geometry is
# from the near-clipping plane, the less depth precision we will
# have to resolve nearly colinear/incident polygons (which we get
# especially with any doubleSided geometry). We can run into such
# situations astonishingly easily with large sets when we are
# focussing in on just a part of a set that spans 10^5 units or
# more.
#
# Our solution: Begin by projecting the endpoints of the imageable
# world's bounds onto the ray piercing the center of the camera
# frustum, and take the near/far clipping distances from its
# extent, clamping at a positive value for near. To address the
# z-buffer precision issue, we rely on someone having told us how
# close the closest imageable geometry actually is to the camera,
# by having called setClosestVisibleDistFromPoint(). This gives us
# the most liberal near distance we can use and not clip the
# geometry we are looking at. We actually choose some fraction of
# that distance instead, because we do not expect the someone to
# recompute the closest point with every camera manipulation, as
# it can be expensive (we do emit signalFrustumChanged to notify
# them, however). We only use this if the current range of the
# bbox-based frustum will have precision issues.
frustum = self._camera.frustum
camPos = frustum.position
camRay = Gf.Ray(camPos, frustum.ComputeViewDirection())
computedNear, computedFar = self._rangeOfBoxAlongRay(camRay,
stageBBox,
debugClipping)
precisionNear = computedFar / FreeCamera.maxGoodZResolution
if debugClipping:
print("Proposed near for precision: {}, closestDist: {}"\
.format(precisionNear, self._closestVisibleDist))
if self._closestVisibleDist:
# Because of our concern about orbit/truck causing
# clipping, make sure we don't go closer than half the
# distance to the closest visible point
halfClose = self._closestVisibleDist / 2.0
if self._closestVisibleDist < self._lastFramedClosestDist:
# This can happen if we have zoomed in closer since
# the last time setClosestVisibleDistFromPoint() was called.
# Clamp to precisionNear, which gives a balance between
# clipping as we zoom in, vs bad z-fighting as we zoom in.
# See AdjustDistance() for comment about better solution.
halfClose = max(precisionNear, halfClose, computedNear)
if debugClipping:
print("ADJUSTING: Accounting for zoom-in")
if halfClose < computedNear:
# If there's stuff very very close to the camera, it
# may have been clipped by computedNear. Get it back!
computedNear = halfClose
if debugClipping:
print("ADJUSTING: closestDist was closer than bboxNear")
elif precisionNear > computedNear:
computedNear = min((precisionNear + halfClose) / 2.0,
halfClose)
if debugClipping:
print("ADJUSTING: gaining precision by pushing out")
near = self._overrideNear or computedNear
far = self._overrideFar or computedFar
# Make sure far is greater than near
far = max(near+1, far)
if debugClipping:
print("***Final Near/Far: {}, {}".format(near, far))
self._camera.clippingRange = Gf.Range1f(near, far)
def computeGfCamera(self, stageBBox, autoClip=False):
"""Makes sure the FreeCamera's computed parameters are up-to-date, and
returns the GfCamera object. If 'autoClip' is True, then compute
"optimal" positions for the near/far clipping planes based on the
current closestVisibleDist, in order to maximize Z-buffer resolution"""
self._pushToCameraTransform()
if autoClip:
self.setClippingPlanes(stageBBox)
else:
self.resetClippingPlanes()
return self._camera
def resetClippingPlanes(self):
"""Set near and far back to their uncomputed defaults."""
near = self._overrideNear or FreeCamera.defaultNear
far = self._overrideFar or FreeCamera.defaultFar
self._camera.clippingRange = Gf.Range1f(near, far)
def frameSelection(self, selBBox, frameFit):
# needs to be recomputed
self._closestVisibleDist = None
self.center = selBBox.ComputeCentroid()
selRange = selBBox.ComputeAlignedRange()
self._selSize = max(*selRange.GetSize())
if self.orthographic:
self.fov = self._selSize * frameFit
self.dist = self._selSize + FreeCamera.defaultNear
else:
halfFov = self.fov*0.5 or 0.5 # don't divide by zero
lengthToFit = self._selSize * frameFit * 0.5
self.dist = lengthToFit / atan(rad(halfFov))
# Very small objects that fill out their bounding boxes (like cubes)
# may well pierce our 1 unit default near-clipping plane. Make sure
# that doesn't happen.
if self.dist < FreeCamera.defaultNear + self._selSize * 0.5:
self.dist = FreeCamera.defaultNear + lengthToFit
def setClosestVisibleDistFromPoint(self, point):
frustum = self._camera.frustum
camPos = frustum.position
camRay = Gf.Ray(camPos, frustum.ComputeViewDirection())
self._closestVisibleDist = camRay.FindClosestPoint(point)[1]
self._lastFramedDist = self.dist
self._lastFramedClosestDist = self._closestVisibleDist
if Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING):
print("Resetting closest distance to {}; CameraPos: {}, closestPoint: {}".format(self._closestVisibleDist, camPos, point))
def ComputePixelsToWorldFactor(self, viewportHeight):
'''Computes the ratio that converts pixel distance into world units.
It treats the pixel distances as if they were projected to a plane going
through the camera center.'''
self._pushToCameraTransform()
if self.orthographic:
return self.fov / viewportHeight
else:
frustumHeight = self._camera.frustum.window.GetSize()[1]
return frustumHeight * self._dist / viewportHeight
def Tumble(self, dTheta, dPhi):
''' Tumbles the camera around the center point by (dTheta, dPhi) degrees. '''
self._rotTheta += dTheta
self._rotPhi += dPhi
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def AdjustDistance(self, scaleFactor):
'''Scales the distance of the freeCamera from it's center typically by
scaleFactor unless it puts the camera into a "stuck" state.'''
# When dist gets very small, you can get stuck and not be able to
# zoom back out, if you just keep multiplying. Switch to addition
# in that case, choosing an incr that works for the scale of the
# framed geometry.
if scaleFactor > 1 and self.dist < 2:
selBasedIncr = self._selSize / 25.0
scaleFactor -= 1.0
self.dist += min(selBasedIncr, scaleFactor)
else:
self.dist *= scaleFactor
# Make use of our knowledge that we are changing distance to camera
# to also adjust _closestVisibleDist to keep it useful. Make sure
# not to recede farther than the last *computed* closeDist, since that
# will generally cause unwanted clipping of close objects.
# XXX: This heuristic does a good job of preventing undesirable
# clipping as we zoom in and out, but sacrifices the z-buffer
# precision we worked hard to get. If Hd/UsdImaging could cheaply
# provide us with the closest-point from the last-rendered image,
# we could use it safely here to update _closestVisibleDist much
# more accurately than this calculation.
if self._closestVisibleDist:
if self.dist > self._lastFramedDist:
self._closestVisibleDist = self._lastFramedClosestDist
else:
self._closestVisibleDist = \
self._lastFramedClosestDist - \
self._lastFramedDist + \
self.dist
def Truck(self, deltaRight, deltaUp):
''' Moves the camera by (deltaRight, deltaUp) in worldspace coordinates.
This is similar to a camera Truck/Pedestal.
'''
# need to update the camera transform before we access the frustum
self._pushToCameraTransform()
frustum = self._camera.frustum
cam_up = frustum.ComputeUpVector()
cam_right = Gf.Cross(frustum.ComputeViewDirection(), cam_up)
self._center += (deltaRight * cam_right + deltaUp * cam_up)
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def PanTilt(self, dPan, dTilt):
''' Rotates the camera around the current camera base (approx. the film
plane). Both parameters are in degrees.
This moves the center point that we normally tumble around.
This is similar to a camera Pan/Tilt.
'''
self._camera.transform = (
Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(Gf.Vec3d.XAxis(), dTilt)) *
Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(Gf.Vec3d.YAxis(), dPan)) *
self._camera.transform)
self._pullFromCameraTransform()
# When we Pan/Tilt, we don't want to roll the camera so we just zero it
# out here.
self._rotPsi = 0.0
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def Walk(self, dForward, dRight):
''' Specialized camera movement that moves it on the "horizontal" plane
'''
# need to update the camera transform before we access the frustum
self._pushToCameraTransform()
frustum = self._camera.frustum
cam_up = frustum.ComputeUpVector().GetNormalized()
cam_forward = frustum.ComputeViewDirection().GetNormalized()
cam_right = Gf.Cross(cam_forward, cam_up)
delta = dForward * cam_forward + dRight * cam_right
self._center += delta
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@staticmethod
def FromGfCamera(gfCamera, isZUp):
self = FreeCamera(isZUp)
self._camera = gfCamera
self._pullFromCameraTransform()
return self
@property
def rotTheta(self):
return self._rotTheta
@rotTheta.setter
def rotTheta(self, value):
self._rotTheta = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def rotPhi(self):
return self._rotPhi
@rotPhi.setter
def rotPhi(self, value):
self._rotPhi = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def center(self):
return self._center
@center.setter
def center(self, value):
self._center = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def dist(self):
return self._dist
@dist.setter
def dist(self, value):
self._dist = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def orthographic(self):
return self._camera.projection == Gf.Camera.Orthographic
@orthographic.setter
def orthographic(self, orthographic):
if orthographic:
self._camera.projection = Gf.Camera.Orthographic
else:
self._camera.projection = Gf.Camera.Perspective
self.signalFrustumChanged.emit()
@property
def fov(self):
"""The vertical field of view, in degrees, for perspective cameras.
For orthographic cameras fov is the height of the view frustum, in
world units.
"""
if self._camera.projection == Gf.Camera.Perspective:
return self._camera.GetFieldOfView(Gf.Camera.FOVVertical)
else:
return (self._camera.verticalAperture * Gf.Camera.APERTURE_UNIT)
@fov.setter
def fov(self, value):
if self._camera.projection == Gf.Camera.Perspective:
self._camera.SetPerspectiveFromAspectRatioAndFieldOfView(
self._camera.aspectRatio, value, Gf.Camera.FOVVertical)
else:
self._camera.SetOrthographicFromAspectRatioAndSize(
self._camera.aspectRatio, value, Gf.Camera.FOVVertical)
self.signalFrustumChanged.emit()
@property
def near(self):
return self._camera.clippingRange.min
@property
def far(self):
return self._camera.clippingRange.max
# no setters for near and far - one must set overrideNear/Far instead
@property
def overrideNear(self):
return self._overrideNear
@overrideNear.setter
def overrideNear(self, value):
"""To remove the override, set to None"""
self._overrideNear = value
@property
def overrideFar(self):
return self._overrideFar
@overrideFar.setter
def overrideFar(self, value):
"""To remove the override, set to None"""
self._overrideFar = value
| 23,336 | Python | 40.37766 | 134 | 0.631385 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/propertyLegend.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
""" This module provides the help dialog(also known as the property legend)
in Usdview's MainWindow. This provides a key describing the items displayed
in the property browser.
"""
from .qt import QtWidgets
from .propertyLegendUI import Ui_PropertyLegend
from .common import UIBaseColors, UIPropertyValueSourceColors, ItalicizeLabelText, PropertyViewIcons
class PropertyLegend(QtWidgets.QWidget):
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
self._ui = Ui_PropertyLegend()
self._ui.setupUi(self)
# The property legend always starts off collapsed.
self.setMaximumHeight(0)
self._isMinimized = True
self._iconDisplaySize = (16, 16)
graphicsScene = QtWidgets.QGraphicsScene()
self._ui.propertyLegendColorFallback.setScene(graphicsScene)
self._ui.propertyLegendColorDefault.setScene(graphicsScene)
self._ui.propertyLegendColorTimeSample.setScene(graphicsScene)
self._ui.propertyLegendColorNoValue.setScene(graphicsScene)
self._ui.propertyLegendColorValueClips.setScene(graphicsScene)
self._ui.propertyLegendColorCustom.setScene(graphicsScene)
# set color of attribute viewer legend boxes
self._ui.propertyLegendColorFallback.setForegroundBrush(
UIPropertyValueSourceColors.FALLBACK)
self._ui.propertyLegendColorDefault.setForegroundBrush(
UIPropertyValueSourceColors.DEFAULT)
self._ui.propertyLegendColorTimeSample.setForegroundBrush(
UIPropertyValueSourceColors.TIME_SAMPLE)
self._ui.propertyLegendColorNoValue.setForegroundBrush(
UIPropertyValueSourceColors.NONE)
self._ui.propertyLegendColorValueClips.setForegroundBrush(
UIPropertyValueSourceColors.VALUE_CLIPS)
self._ui.propertyLegendColorCustom.setForegroundBrush(
UIBaseColors.RED)
# set color of attribute viewer text items
legendTextUpdate = lambda t, c: (
('<font color=\"%s\">' % c.color().name()) + t.text() + '</font>')
timeSampleLegend = self._ui.propertyLegendLabelTimeSample
timeSampleLegend.setText(
legendTextUpdate(timeSampleLegend, UIPropertyValueSourceColors.TIME_SAMPLE))
fallbackLegend = self._ui.propertyLegendLabelFallback
fallbackLegend.setText(
legendTextUpdate(fallbackLegend, UIPropertyValueSourceColors.FALLBACK))
valueClipLegend = self._ui.propertyLegendLabelValueClips
valueClipLegend.setText(
legendTextUpdate(valueClipLegend, UIPropertyValueSourceColors.VALUE_CLIPS))
noValueLegend = self._ui.propertyLegendLabelNoValue
noValueLegend.setText(
legendTextUpdate(noValueLegend, UIPropertyValueSourceColors.NONE))
defaultLegend = self._ui.propertyLegendLabelDefault
defaultLegend.setText(
legendTextUpdate(defaultLegend, UIPropertyValueSourceColors.DEFAULT))
customLegend = self._ui.propertyLegendLabelCustom
customLegend.setText(
legendTextUpdate(customLegend, UIBaseColors.RED))
interpolatedStr = 'Interpolated'
tsLabel = self._ui.propertyLegendLabelTimeSample
tsLabel.setText(ItalicizeLabelText(tsLabel.text(), interpolatedStr))
vcLabel = self._ui.propertyLegendLabelValueClips
vcLabel.setText(ItalicizeLabelText(vcLabel.text(), interpolatedStr))
# Load up and set the icons for the property legend
self._ui.propertyLegendTargetIcon.setPixmap(
PropertyViewIcons.TARGET().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendConnIcon.setPixmap(
PropertyViewIcons.CONNECTION().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendAttrPlainIcon.setPixmap(
PropertyViewIcons.ATTRIBUTE().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendRelPlainIcon.setPixmap(
PropertyViewIcons.RELATIONSHIP().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendAttrWithConnIcon.setPixmap(
PropertyViewIcons.ATTRIBUTE_WITH_CONNECTIONS().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendRelWithTargetIcon.setPixmap(
PropertyViewIcons.RELATIONSHIP_WITH_TARGETS().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendCompIcon.setPixmap(
PropertyViewIcons.COMPOSED().pixmap(*self._iconDisplaySize))
def IsMinimized(self):
return self._isMinimized
def ToggleMinimized(self):
self._isMinimized = not self._isMinimized
def GetHeight(self):
return self.height()
def GetResetHeight(self):
return self.sizeHint().height()
| 5,787 | Python | 43.523077 | 100 | 0.724555 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/appEventFilter.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Qt Components
from .qt import QtCore, QtGui, QtWidgets
from .common import KeyboardShortcuts
class AppEventFilter(QtCore.QObject):
'''This class's primary responsibility is delivering key events to
"the right place". Given usdview's simplistic approach to shortcuts
(i.e. just uses the native Qt mechanism that does not allow for
context-sensitive keypress dispatching), we take a simplistic approach
to routing: use Qt's preferred mechanism of processing keyPresses
only in widgets that have focus; therefore, the primary behavior of this
filter is to track mouse-position in order to set widget focus, so that
widgets with keyboard navigation behaviors operate when the mouse is over
them.
We add one special behaviors on top of that, which is to turn unaccepted
left/right events into up/down events for TreeView widgets, because we
do not have a specialized class on which to provide this nice navigation
behavior.'''
# in future it would be a hotkey dispatcher instead of appController
# that we'd dispatch to, but we don't have one yet
def __init__(self, appController):
QtCore.QObject.__init__(self)
self._appController = appController
def IsNavKey(self, key, modifiers):
# Note that the arrow keys are considered part of the keypad on macOS.
return (key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right,
QtCore.Qt.Key_Up, QtCore.Qt.Key_Down,
QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown,
QtCore.Qt.Key_Home, QtCore.Qt.Key_End,
KeyboardShortcuts.FramingKey)
and modifiers in (QtCore.Qt.NoModifier,
QtCore.Qt.KeypadModifier))
def _IsWindow(self, obj):
if isinstance(obj, QtWidgets.QWidget):
return obj.isWindow()
else:
return isinstance(obj, QtGui.QWindow)
def TopLevelWindow(self, obj):
parent = obj.parent()
return obj if (self._IsWindow(obj) or not parent) else self.TopLevelWindow(parent)
def WantsNavKeys(self, w):
if not w or self._IsWindow(w):
return False
# The broader test would be QtWidgets.QAbstractItemView,
# but pragmatically, the TableViews in usdview don't really
# benefit much from keyboard navigation, and we'd rather
# allow the arrow keys drive the playhead when such widgets would
# otherwise get focus
elif isinstance(w, QtWidgets.QTreeView):
return True
else:
return self.WantsNavKeys(w.parent())
def NavigableOrTopLevelObject(self, w):
if (not w or
self._IsWindow(w) or
isinstance(w, QtWidgets.QTreeView) or
isinstance(w, QtWidgets.QDialog)):
return w
else:
parent = w.parent()
return w if not parent else self.NavigableOrTopLevelObject(parent)
def JealousFocus(self, w):
return (isinstance(w, QtWidgets.QLineEdit) or
isinstance(w, QtWidgets.QComboBox) or
isinstance(w, QtWidgets.QTextEdit) or
isinstance(w, QtWidgets.QAbstractSlider) or
isinstance(w, QtWidgets.QAbstractSpinBox) or
isinstance(w, QtWidgets.QWidget) and w.windowModality() in [QtCore.Qt.WindowModal,
QtCore.Qt.ApplicationModal])
def SetFocusFromMousePos(self, backupWidget):
# It's possible the mouse isn't over any of our windows at the time,
# in which case use the top-level window of backupWidget.
overObject = QtWidgets.QApplication.widgetAt(QtGui.QCursor.pos())
topLevelObject = self.NavigableOrTopLevelObject(overObject)
focusObject = topLevelObject if topLevelObject else self.TopLevelWindow(backupWidget)
if focusObject and isinstance(focusObject, QtWidgets.QWidget):
focusObject.setFocus()
def eventFilter(self, widget, event):
# There is currently no filtering we want to do for modal or popups
if (QtWidgets.QApplication.activeModalWidget() or
QtWidgets.QApplication.activePopupWidget()):
return False
currFocusWidget = QtWidgets.QApplication.focusWidget()
if event.type() == QtCore.QEvent.KeyPress:
key = event.key()
isNavKey = self.IsNavKey(key, event.modifiers())
if key == QtCore.Qt.Key_Escape:
# ESC resets focus based on mouse position, regardless of
# who currently holds focus
self.SetFocusFromMousePos(widget)
return True
elif currFocusWidget and self.JealousFocus(currFocusWidget):
# Don't touch if there's a greedy focus widget
return False
elif (isNavKey and self.WantsNavKeys(currFocusWidget)):
# Special handling for navigation keys:
# 1. When a "navigable" widget is focussed (a TreeView),
# route arrow keys to the widget and consume them
# 2. To make for snappier navigation, when the TreeView
# won't accept a left/right because an item is already
# opened or closed, turn it into an up/down event. It
# WBN if this behavior could be part of the widgets
# themselves, but currently, usdview does not specialize
# a class for its TreeView widgets.
event.setAccepted(False)
currFocusWidget.event(event)
accepted = event.isAccepted()
if (not accepted and
key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right)):
advance = (key == QtCore.Qt.Key_Right)
altNavKey = QtCore.Qt.Key_Down if advance else QtCore.Qt.Key_Up
subEvent = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
altNavKey,
event.modifiers())
QtWidgets.QApplication.postEvent(currFocusWidget, subEvent)
event.setAccepted(True)
return True
elif isNavKey:
if self._appController.processNavKeyEvent(event):
return True
elif (event.type() == QtCore.QEvent.MouseMove and
not self.JealousFocus(currFocusWidget)):
self.SetFocusFromMousePos(widget)
# Note we do not consume the event!
# During startup, Qt seems to queue up events on objects that may
# have disappeared by the time the eventFilter is called upon. This
# is true regardless of how late we install the eventFilter, and
# whether we process pending events before installing. So we
# silently ignore Runtime errors that occur as a result.
try:
return QtCore.QObject.eventFilter(self, widget, event)
except RuntimeError:
return True
| 8,300 | Python | 46.982659 | 104 | 0.628795 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/pythonInterpreter.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from pxr import Tf
from .qt import QtCore, QtGui, QtWidgets
from .usdviewApi import UsdviewApi
from code import InteractiveInterpreter
import os, sys, keyword
# just a handy debugging method
def _PrintToErr(line):
old = sys.stdout
sys.stdout = sys.__stderr__
print(line)
sys.stdout = old
def _Redirected(method):
def new(self, *args, **kw):
old = sys.stdin, sys.stdout, sys.stderr
sys.stdin, sys.stdout, sys.stderr = self, self, self
try:
ret = method(self, *args, **kw)
finally:
sys.stdin, sys.stdout, sys.stderr = old
return ret
return new
class _Completer(object):
"""Taken from rlcompleter, with readline references stripped, and a local
dictionary to use."""
def __init__(self, locals):
self.locals = locals
def Complete(self, text, state):
"""Return the next possible completion for 'text'.
This is called successively with state == 0, 1, 2, ... until it
returns None. The completion should begin with 'text'.
"""
if state == 0:
if "." in text:
self.matches = self._AttrMatches(text)
else:
self.matches = self._GlobalMatches(text)
try:
return self.matches[state]
except IndexError:
return None
def _GlobalMatches(self, text):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names
currently defines in __main__ that match.
"""
builtin_mod = None
if sys.version_info.major >= 3:
import builtins
builtin_mod = builtins
else:
import __builtin__
builtin_mod = __builtin__
import __main__
matches = set()
n = len(text)
for l in [keyword.kwlist,builtin_mod.__dict__.keys(),
__main__.__dict__.keys(), self.locals.keys()]:
for word in l:
if word[:n] == text and word != "__builtins__":
matches.add(word)
return list(matches)
def _AttrMatches(self, text):
"""Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in the globals of __main__, it will be evaluated
and its attributes (as revealed by dir()) are used as possible
completions. (For class instances, class members are are also
considered.)
WARNING: this can still invoke arbitrary C code, if an object
with a __getattr__ hook is evaluated.
"""
import re, __main__
assert len(text)
# This is all a bit hacky, but that's tab-completion for you.
# Now find the last index in the text of a set of characters, and split
# the string into a prefix and suffix token there. The suffix token
# will be used for completion.
splitChars = ' )(;,+=*/-%!<>'
index = -1
for char in splitChars:
index = max(text.rfind(char), index)
if index >= len(text)-1:
return []
prefix = ''
suffix = text
if index >= 0:
prefix = text[:index+1]
suffix = text[index+1:]
m = re.match(r"([^.]+(\.[^.]+)*)\.(.*)", suffix)
if not m:
return []
expr, attr = m.group(1, 3)
try:
myobject = eval(expr, __main__.__dict__, self.locals)
except (AttributeError, NameError, SyntaxError):
return []
words = set(dir(myobject))
if hasattr(myobject,'__class__'):
words.add('__class__')
words = words.union(set(_GetClassMembers(myobject.__class__)))
words = list(words)
matches = set()
n = len(attr)
for word in words:
if word[:n] == attr and word != "__builtins__":
matches.add("%s%s.%s" % (prefix, expr, word))
return list(matches)
def _GetClassMembers(cls):
ret = dir(cls)
if hasattr(cls, '__bases__'):
for base in cls.__bases__:
ret = ret + _GetClassMembers(base)
return ret
class Interpreter(InteractiveInterpreter):
def __init__(self, locals = None):
InteractiveInterpreter.__init__(self,locals)
self._outputBrush = None
# overridden
def showsyntaxerror(self, filename = None):
self._outputBrush = QtGui.QBrush(QtGui.QColor('#ffcc63'))
try:
InteractiveInterpreter.showsyntaxerror(self, filename)
finally:
self._outputBrush = None
# overridden
def showtraceback(self):
self._outputBrush = QtGui.QBrush(QtGui.QColor('#ff0000'))
try:
InteractiveInterpreter.showtraceback(self)
finally:
self._outputBrush = None
def GetOutputBrush(self):
return self._outputBrush
# Modified from site.py in the Python distribution.
#
# This allows each interpreter editor to have it's own Helper object.
# The built-in pydoc.help grabs sys.stdin and sys.stdout the first time it
# is run and then never lets them go.
class _Helper(object):
"""Define a replacement for the built-in 'help'.
This is a wrapper around pydoc.Helper (with a twist).
"""
def __init__(self, input, output):
import pydoc
self._helper = pydoc.Helper(input, output)
def __repr__(self):
return "Type help() for interactive help, " \
"or help(object) for help about object."
def __call__(self, *args, **kwds):
return self._helper(*args, **kwds)
class Controller(QtCore.QObject):
"""
Controller is a Python shell written using Qt.
This class is a controller between Python and something which acts
like a QTextEdit.
"""
_isAnyReadlineEventLoopActive = False
def __init__(self, textEdit, initialPrompt, locals = None):
"""Constructor.
The optional 'locals' argument specifies the dictionary in
which code will be executed; it defaults to a newly created
dictionary with key "__name__" set to "__console__" and key
"__doc__" set to None.
"""
super(Controller, self).__init__()
self.interpreter = Interpreter(locals)
self.interpreter.locals['help'] = _Helper(self, self)
self.completer = _Completer(self.interpreter.locals)
# last line + last incomplete lines
self.lines = []
# flag: the interpreter needs more input to run the last lines.
self.more = 0
# history
self.history = []
self.historyPointer = None
self.historyInput = ''
# flag: readline() is being used for e.g. raw_input and input().
# We use a nested QEventloop here because we want to emulate
# modeless UI even though the readline protocol requires blocking calls.
self.readlineEventLoop = QtCore.QEventLoop(textEdit)
# interpreter prompt.
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
self.textEdit = textEdit
self.textEdit.destroyed.connect(self._TextEditDestroyedSlot)
self.textEdit.returnPressed.connect(self._ReturnPressedSlot)
self.textEdit.requestComplete.connect(self._CompleteSlot)
self.textEdit.requestNext.connect(self._NextSlot)
self.textEdit.requestPrev.connect(self._PrevSlot)
appInstance = QtWidgets.QApplication.instance()
appInstance.aboutToQuit.connect(self._QuitSlot)
self.textEdit.setTabChangesFocus(False)
self.textEdit.setWordWrapMode(QtGui.QTextOption.WrapAnywhere)
self.textEdit.setWindowTitle('Interpreter')
self.textEdit.promptLength = len(sys.ps1)
# Do initial auto-import.
self._DoAutoImports()
# interpreter banner
self.write('Python %s on %s.\n' % (sys.version, sys.platform))
# Run $PYTHONSTARTUP startup script.
startupFile = os.getenv('PYTHONSTARTUP')
if startupFile:
path = os.path.realpath(os.path.expanduser(startupFile))
if os.path.isfile(path):
self.ExecStartupFile(path)
self.write(initialPrompt)
self.write(sys.ps1)
self.SetInputStart()
def _DoAutoImports(self):
modules = Tf.ScriptModuleLoader().GetModulesDict()
for name, mod in modules.items():
self.interpreter.runsource('import ' + mod.__name__ +
' as ' + name + '\n')
@_Redirected
def ExecStartupFile(self, path):
# fix for bug 9104
# this sets __file__ in the globals dict while we are execing these
# various startup scripts, so that they can access the location from
# which they are being run.
# also, update the globals dict after we exec the file (bug 9529)
self.interpreter.runsource( 'g = dict(globals()); g["__file__"] = ' +
'"%s"; execfile("%s", g);' % (path, path) +
'del g["__file__"]; globals().update(g);' )
self.SetInputStart()
self.lines = []
def SetInputStart(self):
cursor = self.textEdit.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self.textEdit.SetStartOfInput(cursor.position())
def _QuitSlot(self):
if self.readlineEventLoop:
if self.readlineEventLoop.isRunning():
self.readlineEventLoop.Exit()
def _TextEditDestroyedSlot(self):
self.readlineEventLoop = None
def _ReturnPressedSlot(self):
if self.readlineEventLoop.isRunning():
self.readlineEventLoop.Exit()
else:
self._Run()
def flush(self):
"""
Simulate stdin, stdout, and stderr.
"""
pass
def isatty(self):
"""
Simulate stdin, stdout, and stderr.
"""
return 1
def readline(self):
"""
Simulate stdin, stdout, and stderr.
"""
# XXX: Prevent more than one interpreter from blocking on a readline()
# call. Starting more than one subevent loop does not work,
# because they must exit in the order that they were created.
if Controller._isAnyReadlineEventLoopActive:
raise RuntimeError("Simultaneous readline() calls in multiple "
"interpreters are not supported.")
cursor = self.textEdit.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self.SetInputStart()
self.textEdit.setTextCursor(cursor)
try:
Controller._isAnyReadlineEventLoopActive = True
# XXX TODO - Make this suck less if possible. We're invoking a
# subeventloop here, which means until we return from this
# readline we'll never get up to the main event loop. To avoid
# using a subeventloop, we would need to return control to the
# main event loop in the main thread, suspending the execution of
# the code that called into here, which also lives in the main
# thread. This essentially requires a
# co-routine/continuation-based solution capable of dealing with
# an arbitrary stack of interleaved Python/C calls (e.g. greenlet).
self.readlineEventLoop.Exec()
finally:
Controller._isAnyReadlineEventLoopActive = False
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.MoveAnchor)
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.KeepAnchor)
txt = str(cursor.selectedText())
if len(txt) == 0:
return '\n'
else:
self.write('\n')
return txt
@_Redirected
def write(self, text):
'Simulate stdin, stdout, and stderr.'
# Move the cursor to the end of the document
self.textEdit.moveCursor(QtGui.QTextCursor.End)
# Clear any existing text format. We will explicitly set the format
# later to something else if need be.
self.textEdit.ResetCharFormat()
# Copy the textEdit's current cursor.
cursor = self.textEdit.textCursor()
try:
# If there's a designated output brush, merge that character format
# into the cursor's character format.
if self.interpreter.GetOutputBrush():
cf = QtGui.QTextCharFormat()
cf.setForeground(self.interpreter.GetOutputBrush())
cursor.mergeCharFormat(cf)
# Write the text to the textEdit.
cursor.insertText(text)
finally:
# Set the textEdit's cursor to the end of input
self.textEdit.moveCursor(QtGui.QTextCursor.End)
# get the length of a string in pixels bases on our current font
@staticmethod
def _GetStringLengthInPixels(cf, string):
font = cf.font()
fm = QtGui.QFontMetrics(font)
strlen = fm.width(string)
return strlen
def _CompleteSlot(self):
cf = self.textEdit.currentCharFormat()
line = self._GetInputLine()
cursor = self.textEdit.textCursor()
origPos = cursor.position()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.KeepAnchor)
text = str(cursor.selectedText())
tokens = text.split()
token = ''
if len(tokens) != 0:
token = tokens[-1]
completions = []
p = self.completer.Complete(token,len(completions))
while p != None:
completions.append(p)
p = self.completer.Complete(token, len(completions))
if len(completions) == 0:
return
elif len(completions) != 1:
self.write("\n")
contentsRect = self.textEdit.contentsRect()
# get the width inside the margins to eventually determine the
# number of columns in our text table based on the max string width
# of our completed words XXX TODO - paging based on widget height
width = contentsRect.right() - contentsRect.left()
maxLength = 0
for i in completions:
maxLength = max(maxLength, self._GetStringLengthInPixels(cf, i))
# pad it a bit
maxLength = maxLength + self._GetStringLengthInPixels(cf, ' ')
# how many columns can we fit on screen?
numCols = max(1,width // maxLength)
# how many rows do we need to fit our data
numRows = (len(completions) // numCols) + 1
columnWidth = QtGui.QTextLength(QtGui.QTextLength.FixedLength,
maxLength)
tableFormat = QtGui.QTextTableFormat()
tableFormat.setAlignment(QtCore.Qt.AlignLeft)
tableFormat.setCellPadding(0)
tableFormat.setCellSpacing(0)
tableFormat.setColumnWidthConstraints([columnWidth] * numCols)
tableFormat.setBorder(0)
cursor = self.textEdit.textCursor()
# Make the completion table insertion a single edit block
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.End)
textTable = cursor.insertTable(numRows, numCols, tableFormat)
completions.sort()
index = 0
completionsLength = len(completions)
for col in range(0,numCols):
for row in range(0,numRows):
cellNum = (row * numCols) + col
if (cellNum >= completionsLength):
continue
tableCell = textTable.cellAt(row,col)
cellCursor = tableCell.firstCursorPosition()
cellCursor.insertText(completions[index], cf)
index +=1
cursor.endEditBlock()
self.textEdit.setTextCursor(cursor)
self.write("\n")
if self.more:
self.write(sys.ps2)
else:
self.write(sys.ps1)
self.SetInputStart()
# complete up to the common prefix
cp = os.path.commonprefix(completions)
# make sure that we keep everything after the cursor the same as it
# was previously
i = line.rfind(token)
textToRight = line[i+len(token):]
line = line[0:i] + cp + textToRight
self.write(line)
# replace the line and reset the cursor
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput() + len(line) -
len(textToRight))
self.textEdit.setTextCursor(cursor)
else:
i = line.rfind(token)
line = line[0:i] + completions[0] + line[i+len(token):]
# replace the line and reset the cursor
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.MoveAnchor)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor.insertText(line)
cursor.setPosition(origPos + len(completions[0]) - len(token))
self.textEdit.setTextCursor(cursor)
def _NextSlot(self):
if len(self.history):
# if we have no history pointer, we can't go forward..
if (self.historyPointer == None):
return
# if we are at the end of our history stack, we can't go forward
elif (self.historyPointer == len(self.history) - 1):
self._ClearLine()
self.write(self.historyInput)
self.historyPointer = None
return
self.historyPointer += 1
self._Recall()
def _PrevSlot(self):
if len(self.history):
# if we have no history pointer, set it to the most recent
# item in the history stack, and stash away our current input
if (self.historyPointer == None):
self.historyPointer = len(self.history)
self.historyInput = self._GetInputLine()
# if we are at the end of our history, beep
elif (self.historyPointer <= 0):
return
self.historyPointer -= 1
self._Recall()
def _IsBlank(self, txt):
return len(txt.strip()) == 0
def _GetInputLine(self):
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.MoveAnchor)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
txt = str(cursor.selectedText())
return txt
def _ClearLine(self):
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.MoveAnchor)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
@_Redirected
def _Run(self):
"""
Append the last line to the history list, let the interpreter execute
the last line(s), and clean up accounting for the interpreter results:
(1) the interpreter succeeds
(2) the interpreter fails, finds no errors and wants more line(s)
(3) the interpreter fails, finds errors and writes them to sys.stderr
"""
self.historyPointer = None
inputLine = self._GetInputLine()
if (inputLine != ""):
self.history.append(inputLine)
self.lines.append(inputLine)
source = '\n'.join(self.lines)
self.write('\n')
self.more = self.interpreter.runsource(source)
if self.more:
self.write(sys.ps2)
self.SetInputStart()
else:
self.write(sys.ps1)
self.SetInputStart()
self.lines = []
def _Recall(self):
"""
Display the current item from the command history.
"""
self._ClearLine()
self.write(self.history[self.historyPointer])
class View(QtWidgets.QTextEdit):
"""View is a QTextEdit which provides some extra
facilities to help implement an interpreter console. In particular,
QTextEdit does not provide for complete control over the buffer being
edited. Some signals are emitted *after* action has already been
taken, disallowing controller classes from really controlling the widget.
This widget fixes that.
"""
returnPressed = QtCore.Signal()
requestPrev = QtCore.Signal()
requestNext = QtCore.Signal()
requestComplete = QtCore.Signal()
def __init__(self, parent=None):
super(View, self).__init__(parent)
self.promptLength = 0
self.__startOfInput = 0
self.setUndoRedoEnabled(False)
self.setAcceptRichText(False)
self.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
self.tripleClickTimer = QtCore.QBasicTimer()
self.tripleClickPoint = QtCore.QPoint()
self._ignoreKeyPresses = True
self.ResetCharFormat()
def SetStartOfInput(self, position):
self.__startOfInput = position
def StartOfInput(self):
return self.__startOfInput
def ResetCharFormat(self):
charFormat = QtGui.QTextCharFormat()
charFormat.setFontFamily('monospace')
self.setCurrentCharFormat(charFormat)
def _PositionInInputArea(self, position):
return position - self.__startOfInput
def _PositionIsInInputArea(self, position):
return self._PositionInInputArea(position) >= 0
def _CursorIsInInputArea(self):
return self._PositionIsInInputArea(self.textCursor().position())
def _SelectionIsInInputArea(self):
if (not self.textCursor().hasSelection()):
return False
selStart = self.textCursor().selectionStart()
selEnd = self.textCursor().selectionEnd()
return self._PositionIsInInputArea(selStart) and \
self._PositionIsInInputArea(selEnd)
def _MoveCursorToStartOfInput(self, select=False):
cursor = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
cursor.movePosition(QtGui.QTextCursor.End, anchor)
cursor.setPosition(self.__startOfInput, anchor)
self.setTextCursor(cursor)
def _MoveCursorToEndOfInput(self, select=False):
c = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
c.movePosition(QtGui.QTextCursor.End, anchor)
self.setTextCursor(c)
def _WritableCharsToLeftOfCursor(self):
return (self._PositionInInputArea(self.textCursor().position()) > 0)
def mousePressEvent(self, e):
app = QtWidgets.QApplication.instance()
# is this a triple click?
if ((e.button() & QtCore.Qt.LeftButton) and
self.tripleClickTimer.isActive() and
(e.globalPos() - self.tripleClickPoint).manhattanLength() <
app.startDragDistance() ):
# instead of duplicating the triple click code completely, we just
# pass it along. but we modify the selection that comes out of it
# to exclude the prompt, if appropriate
super(View, self).mousePressEvent(e)
if (self._CursorIsInInputArea()):
selStart = self.textCursor().selectionStart()
selEnd = self.textCursor().selectionEnd()
if (self._PositionInInputArea(selStart) < 0):
# remove selection up until start of input
self._MoveCursorToStartOfInput(False)
cursor = self.textCursor()
cursor.setPosition(selEnd, QtGui.QTextCursor.KeepAnchor)
self.setTextCursor(cursor)
else:
super(View, self).mousePressEvent(e)
def mouseDoubleClickEvent(self, e):
super(View, self).mouseDoubleClickEvent(e)
app = QtWidgets.QApplication.instance()
self.tripleClickTimer.start(app.doubleClickInterval(), self)
# make a copy here, otherwise tripleClickPoint will always = globalPos
self.tripleClickPoint = QtCore.QPoint(e.globalPos())
def timerEvent(self, e):
if (e.timerId() == self.tripleClickTimer.timerId()):
self.tripleClickTimer.stop()
else:
super(View, self).timerEvent(e)
def enterEvent(self, e):
self._ignoreKeyPresses = False
def leaveEvent(self, e):
self._ignoreKeyPresses = True
def dragEnterEvent(self, e):
self._ignoreKeyPresses = False
super(View, self).dragEnterEvent(e)
def dragLeaveEvent(self, e):
self._ignoreKeyPresses = True
super(View, self).dragLeaveEvent(e)
def insertFromMimeData(self, source):
if not self._CursorIsInInputArea():
self._MoveCursorToEndOfInput()
if source.hasText():
text = source.text().replace('\r', '')
textLines = text.split('\n')
if (textLines[-1] == ''):
textLines = textLines[:-1]
for i in range(len(textLines)):
line = textLines[i]
cursor = self.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
cursor.insertText(line)
cursor.movePosition(QtGui.QTextCursor.End)
self.setTextCursor(cursor)
if i < len(textLines) - 1:
self.returnPressed.emit()
def keyPressEvent(self, e):
"""
Handle user input a key at a time.
"""
if (self._ignoreKeyPresses):
e.ignore()
return
key = e.key()
ctrl = e.modifiers() & QtCore.Qt.ControlModifier
alt = e.modifiers() & QtCore.Qt.AltModifier
shift = e.modifiers() & QtCore.Qt.ShiftModifier
cursorInInput = self._CursorIsInInputArea()
selectionInInput = self._SelectionIsInInputArea()
hasSelection = self.textCursor().hasSelection()
canBackspace = self._WritableCharsToLeftOfCursor()
canEraseSelection = selectionInInput and cursorInInput
if key == QtCore.Qt.Key_Backspace:
if (canBackspace and not hasSelection) or canEraseSelection:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Delete:
if (cursorInInput and not hasSelection) or canEraseSelection:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Left:
pos = self._PositionInInputArea(self.textCursor().position())
if pos == 0:
e.ignore()
else:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Right:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Return or key == QtCore.Qt.Key_Enter:
# move cursor to end of line.
# emit signal to tell controller enter was pressed.
if not cursorInInput:
self._MoveCursorToStartOfInput(False)
cursor = self.textCursor()
cursor.movePosition(QtGui.QTextCursor.EndOfBlock)
self.setTextCursor(cursor)
# emit returnPressed
self.returnPressed.emit()
elif (key == QtCore.Qt.Key_Up
or key == QtCore.Qt.Key_Down
# support Ctrl+P and Ctrl+N for history
# navigation along with arrows
or (ctrl and (key == QtCore.Qt.Key_P
or key == QtCore.Qt.Key_N))
# support Ctrl+E/End and Ctrl+A/Home for terminal
# style nav. to the ends of the line
or (ctrl and (key == QtCore.Qt.Key_A
or key == QtCore.Qt.Key_E))
or (key == QtCore.Qt.Key_Home
or key == QtCore.Qt.Key_End)):
if cursorInInput:
if (key == QtCore.Qt.Key_Up or key == QtCore.Qt.Key_P):
self.requestPrev.emit()
if (key == QtCore.Qt.Key_Down or key == QtCore.Qt.Key_N):
self.requestNext.emit()
if (key == QtCore.Qt.Key_A or key == QtCore.Qt.Key_Home):
self._MoveCursorToStartOfInput(select=shift)
if (key == QtCore.Qt.Key_E or key == QtCore.Qt.Key_End):
self._MoveCursorToEndOfInput(select=shift)
e.ignore()
else:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Tab:
self.AutoComplete()
e.accept()
elif ((ctrl and key == QtCore.Qt.Key_C) or
(shift and key == QtCore.Qt.Key_Insert)):
# Copy should never move cursor.
super(View, self).keyPressEvent(e)
elif ((ctrl and key == QtCore.Qt.Key_X) or
(shift and key == QtCore.Qt.Key_Delete)):
# Disallow cut from outside the input area so users don't
# affect the scrollback buffer.
if not selectionInInput:
e.ignore()
else:
super(View, self).keyPressEvent(e)
elif (key == QtCore.Qt.Key_Control or
key == QtCore.Qt.Key_Alt or
key == QtCore.Qt.Key_Shift):
# Ignore modifier keypresses by themselves so the cursor
# doesn't jump to the end of input when users begin a
# key combination.
e.ignore()
else:
# All other keypresses should append to the end of input.
if not cursorInInput:
self._MoveCursorToEndOfInput()
super(View, self).keyPressEvent(e)
def AutoComplete(self):
if self._CursorIsInInputArea():
self.requestComplete.emit()
def _MoveCursorToBeginning(self, select=False):
if self._CursorIsInInputArea():
self._MoveCursorToStartOfInput(select)
else:
cursor = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
cursor.setPosition(0, anchor)
self.setTextCursor(cursor)
def _MoveCursorToEnd(self, select=False):
if self._CursorIsInInputArea():
self._MoveCursorToEndOfInput(select)
else:
cursor = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
cursor.setPosition(self.__startOfInput, anchor)
cursor.movePosition(QtGui.QTextCursor.Up, anchor)
cursor.movePosition(QtGui.QTextCursor.EndOfLine, anchor)
self.setTextCursor(cursor)
def MoveCursorToBeginning(self):
self._MoveCursorToBeginning(False)
def MoveCursorToEnd(self):
self._MoveCursorToEnd(False)
def SelectToTop(self):
self._MoveCursorToBeginning(True)
def SelectToBottom(self):
self._MoveCursorToEnd(True)
FREQUENTLY_USED = [
"dataModel", "stage", "frame", "prim", "property", "spec", "layer"]
INITIAL_PROMPT = """
Use the `usdviewApi` variable to interact with UsdView.
Type `help(usdviewApi)` to view available API methods and properties.
Frequently used properties:
{}\n""".format(
"".join(" usdviewApi.{} - {}\n".format(
name, getattr(UsdviewApi, name).__doc__)
for name in FREQUENTLY_USED))
class Myconsole(View):
def __init__(self, parent, usdviewApi):
super(Myconsole, self).__init__(parent)
self.setObjectName("Myconsole")
# Inject the UsdviewApi into the interpreter variables.
interpreterLocals = vars()
interpreterLocals["usdviewApi"] = usdviewApi
# Make a Controller.
self._controller = Controller(self, INITIAL_PROMPT, interpreterLocals)
def locals(self):
return self._controller.interpreter.locals
| 33,935 | Python | 34.35 | 80 | 0.590423 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primContextMenuItems.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtGui, QtWidgets
from .usdviewContextMenuItem import UsdviewContextMenuItem
import os
import sys
#
# Edit the following to alter the per-prim context menu.
#
# Every entry should be an object derived from PrimContextMenuItem,
# defined below.
#
def _GetContextMenuItems(appController, item):
return [JumpToEnclosingModelItem(appController, item),
SelectBoundPreviewMaterialMenuItem(appController, item),
SelectBoundFullMaterialMenuItem(appController, item),
SeparatorMenuItem(appController, item),
ToggleVisibilityMenuItem(appController, item),
VisOnlyMenuItem(appController, item),
RemoveVisMenuItem(appController, item),
SeparatorMenuItem(appController, item),
LoadOrUnloadMenuItem(appController, item),
ActiveMenuItem(appController, item),
SeparatorMenuItem(appController, item),
CopyPrimPathMenuItem(appController, item),
CopyModelPathMenuItem(appController, item),
SeparatorMenuItem(appController, item),
IsolateAssetMenuItem(appController, item),
SetAsActiveCamera(appController, item)]
#
# The base class for per-prim context menu items.
#
class PrimContextMenuItem(UsdviewContextMenuItem):
def __init__(self, appController, item):
self._selectionDataModel = appController._dataModel.selection
self._currentFrame = appController._dataModel.currentFrame
self._appController = appController
self._item = item
def IsEnabled(self):
return True
def IsSeparator(self):
return False
def GetText(self):
return ""
def RunCommand(self):
return True
#
# Puts a separator in the context menu
#
class SeparatorMenuItem(PrimContextMenuItem):
def IsSeparator(self):
return True
#
# Replace each selected prim with its enclosing model prim, if it has one,
# in the selection set
#
class JumpToEnclosingModelItem(PrimContextMenuItem):
def IsEnabled(self):
from .common import GetEnclosingModelPrim
for p in self._selectionDataModel.getPrims():
if GetEnclosingModelPrim(p) is not None:
return True
return False
def GetText(self):
return "Jump to Enclosing Model"
def RunCommand(self):
self._appController.selectEnclosingModel()
#
# Replace each selected prim with the "preview" Material it is bound to.
#
class SelectBoundPreviewMaterialMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from pxr import UsdShade
self._boundPreviewMaterial = None
self._bindingRel = None
for p in self._selectionDataModel.getPrims():
(self._boundPreviewMaterial, self._bindingRel) = \
UsdShade.MaterialBindingAPI(p).ComputeBoundMaterial(
UsdShade.Tokens.preview)
if self._boundPreviewMaterial:
break
def IsEnabled(self):
return bool(self._boundPreviewMaterial)
def GetText(self):
if self._boundPreviewMaterial:
isPreviewBindingRel = 'preview' in self._bindingRel.SplitName()
return "Select Bound Preview Material (%s%s)" % (
self._boundPreviewMaterial.GetPrim().GetName(),
"" if isPreviewBindingRel else " from generic binding")
else:
return "Select Bound Preview Material (None)"
def RunCommand(self):
self._appController.selectBoundPreviewMaterial()
#
# Replace each selected prim with the "preview" Material it is bound to.
#
class SelectBoundFullMaterialMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from pxr import UsdShade
self._boundFullMaterial = None
self._bindingRel = None
for p in self._selectionDataModel.getPrims():
(self._boundFullMaterial, self._bindingRel) = \
UsdShade.MaterialBindingAPI(p).ComputeBoundMaterial(
UsdShade.Tokens.full)
if self._boundFullMaterial:
break
def IsEnabled(self):
return bool(self._boundFullMaterial)
def GetText(self):
if self._boundFullMaterial:
isFullBindingRel = 'full' in self._bindingRel.SplitName()
return "Select Bound Full Material (%s%s)" % (
self._boundFullMaterial.GetPrim().GetName(),
"" if isFullBindingRel else " from generic binding")
else:
return "Select Bound Full Material (None)"
def RunCommand(self):
self._appController.selectBoundFullMaterial()
#
# Allows you to activate/deactivate a prim in the graph
#
class ActiveMenuItem(PrimContextMenuItem):
def GetText(self):
if self._selectionDataModel.getFocusPrim().IsActive():
return "Deactivate"
else:
return "Activate"
def RunCommand(self):
active = self._selectionDataModel.getFocusPrim().IsActive()
if active:
self._appController.deactivateSelectedPrims()
else:
self._appController.activateSelectedPrims()
#
# Allows you to vis or invis a prim in the graph, based on its current
# resolved visibility
#
class ToggleVisibilityMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from pxr import UsdGeom
self._imageable = False
self._isVisible = False
for prim in self._selectionDataModel.getPrims():
imgbl = UsdGeom.Imageable(prim)
if imgbl:
self._imageable = True
self._isVisible = (imgbl.ComputeVisibility(self._currentFrame)
== UsdGeom.Tokens.inherited)
break
def IsEnabled(self):
return self._imageable
def GetText(self):
return "Make Invisible" if self._isVisible else "Make Visible"
def RunCommand(self):
if self._isVisible:
self._appController.invisSelectedPrims()
else:
self._appController.visSelectedPrims()
#
# Allows you to vis-only a prim in the graph
#
class VisOnlyMenuItem(PrimContextMenuItem):
def IsEnabled(self):
from pxr import UsdGeom
for prim in self._selectionDataModel.getPrims():
if prim.IsA(UsdGeom.Imageable):
return True
return False
def GetText(self):
return "Vis Only"
def RunCommand(self):
self._appController.visOnlySelectedPrims()
#
# Remove any vis/invis authored on selected prims
#
class RemoveVisMenuItem(PrimContextMenuItem):
def IsEnabled(self):
from .common import HasSessionVis
for prim in self._selectionDataModel.getPrims():
if HasSessionVis(prim):
return True
return False
def GetText(self):
return "Remove Session Visibility"
def RunCommand(self):
self._appController.removeVisSelectedPrims()
#
# Toggle load-state on the selected prims, if loadable
#
class LoadOrUnloadMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from .common import GetPrimsLoadability
# Use the descendent-pruned selection set to avoid redundant
# traversal of the stage to answer isLoaded...
self._loadable, self._loaded = GetPrimsLoadability(
self._selectionDataModel.getLCDPrims())
def IsEnabled(self):
return self._loadable
def GetText(self):
return "Unload" if self._loaded else "Load"
def RunCommand(self):
if self._loaded:
self._appController.unloadSelectedPrims()
else:
self._appController.loadSelectedPrims()
#
# Copies the paths of the currently selected prims to the clipboard
#
class CopyPrimPathMenuItem(PrimContextMenuItem):
def GetText(self):
if len(self._selectionDataModel.getPrims()) > 1:
return "Copy Prim Paths"
return "Copy Prim Path"
def RunCommand(self):
pathlist = [str(p.GetPath())
for p in self._selectionDataModel.getPrims()]
pathStrings = '\n'.join(pathlist)
cb = QtWidgets.QApplication.clipboard()
cb.setText(pathStrings, QtGui.QClipboard.Selection )
cb.setText(pathStrings, QtGui.QClipboard.Clipboard )
#
# Copies the path of the first-selected prim's enclosing model
# to the clipboard, if the prim is inside a model
#
class CopyModelPathMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from .common import GetEnclosingModelPrim
if len(self._selectionDataModel.getPrims()) == 1:
self._modelPrim = GetEnclosingModelPrim(
self._selectionDataModel.getFocusPrim())
else:
self._modelPrim = None
def IsEnabled(self):
return self._modelPrim
def GetText(self):
name = ( "(%s)" % self._modelPrim.GetName() ) if self._modelPrim else ""
return "Copy Enclosing Model %s Path" % name
def RunCommand(self):
modelPath = str(self._modelPrim.GetPath())
cb = QtWidgets.QApplication.clipboard()
cb.setText(modelPath, QtGui.QClipboard.Selection )
cb.setText(modelPath, QtGui.QClipboard.Clipboard )
#
# Copies the current prim and subtree to a file of the user's choosing
# XXX This is not used, and does not work. Leaving code in for now for
# future reference/inspiration
#
class IsolateCopyPrimMenuItem(PrimContextMenuItem):
def GetText(self):
return "Isolate Copy of Prim..."
def RunCommand(self):
focusPrim = self._selectionDataModel.getFocusPrim()
inFile = focusPrim.GetScene().GetUsdFile()
guessOutFile = os.getcwd() + "/" + focusPrim.GetName() + "_copy.usd"
(outFile, _) = QtWidgets.QFileDialog.getSaveFileName(None,
"Specify the Usd file to create", guessOutFile, 'Usd files (*.usd)')
if (outFile.rsplit('.')[-1] != 'usd'):
outFile += '.usd'
if inFile == outFile:
sys.stderr.write( "Cannot isolate a copy to the source usd!\n" )
return
sys.stdout.write( "Writing copy to new file '%s' ... " % outFile )
sys.stdout.flush()
os.system( 'usdcopy -inUsd ' + inFile +
' -outUsd ' + outFile + ' ' +
' -sourcePath ' + focusPrim.GetPath() + '; ' +
'usdview ' + outFile + ' &')
sys.stdout.write( "Done!\n" )
def IsEnabled(self):
numSelectedPrims = len(self._selectionDataModel.getPrims())
focusPrimActive = self._selectionDataModel.getFocusPrim().GetActive()
return numSelectedPrims == 1 and focusPrimActive
#
# Launches usdview on the asset instantiated at the selected prim, as
# defined by USD assetInfo present on the prim
#
class IsolateAssetMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
self._assetName = None
if len(self._selectionDataModel.getPrims()) == 1:
from pxr import Usd
model = Usd.ModelAPI(self._selectionDataModel.getFocusPrim())
name = model.GetAssetName()
identifier = model.GetAssetIdentifier()
if name and identifier:
# Ar API is still settling out...
# from pxr import Ar
# identifier = Ar.GetResolver().Resolve("", identifier.path)
from pxr import Sdf
layer = Sdf.Layer.Find(identifier.path)
if layer:
self._assetName = name
self._filePath = layer.realPath
def IsEnabled(self):
return self._assetName
def GetText(self):
name = ( " '%s'" % self._assetName ) if self._assetName else ""
return "usdview asset%s" % name
def RunCommand(self):
print("Spawning usdview %s" % self._filePath)
os.system("usdview %s &" % self._filePath)
#
# If the selected prim is a camera and not the currently active camera, display
# an enabled menu item to set it as the active camera.
#
class SetAsActiveCamera(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
self._nonActiveCameraPrim = None
if len(self._selectionDataModel.getPrims()) is 1:
prim = self._selectionDataModel.getPrims()[0]
from pxr import UsdGeom
cam = UsdGeom.Camera(prim)
if cam:
if prim != appController.getActiveCamera():
self._nonActiveCameraPrim = prim
def IsEnabled(self):
return self._nonActiveCameraPrim
def GetText(self):
return "Set As Active Camera"
def RunCommand(self):
self._appController._cameraSelectionChanged(self._nonActiveCameraPrim)
| 14,333 | Python | 31.577273 | 80 | 0.650945 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/plugin.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import sys
import importlib
from pxr import Tf
from pxr import Plug
from .qt import QtGui
class DuplicateCommandPlugin(Exception):
"""Exception raised when two command plugins are registered with the same
name.
"""
def __init__(self, name):
super(DuplicateCommandPlugin, self).__init__(
("A command plugin with the name '{}' has already been "
"registered.").format(name))
self.name = name
class DeferredImport(object):
"""Defers importing a module until one of the target callable objects is
called for the first time. Note that there is no way to know if a callable
object exists in the target module or even if the target module exists until
import time. All objects that are referenced are assumed to exist until
proven otherwise when they are called (at which point an ImportError is
raised).
Example:
math = DeferredImport("math")
# You can pull as many callable objects from `math` as desired, even if they
# don't actually exist in `math`.
sqrt = math.sqrt
cos = math.cos
foo = math.foo # does not exist in the real `math` module
# The `math` module will only be imported when this next line runs because
# this is the first invocation of a callable object from `math`.
cos(0)
# This will raise an ImportError because `math.foo` doesn't really exist.
foo(0)
"""
def __init__(self, moduleName, packageName=None):
self._moduleName = moduleName
self._packageName = packageName
self._module = None
def __getattr__(self, attr):
"""Returns a function which calls the target function of the module and
passes along any parameters. The module is lazy-imported when a function
returned by this method is called for the first time.
"""
def f(*args, **kwargs):
if self._module is None:
# Try to import the target module.
try:
self._module = importlib.import_module(
self._moduleName, package=self._packageName)
except ImportError:
raise ImportError(
"Failed deferred import: module '{}' not found.".format(
self._moduleName))
# Try to get the target function from the imported module.
try:
moduleFunction = getattr(self._module, attr)
except AttributeError:
raise ImportError(("Failed deferred import: callable object "
" '{}' from module '{}' not found").format(
attr, self._moduleName))
# Module and function loaded successfully. Now we can call the
# function and pass it the parameters.
return moduleFunction(*args, **kwargs)
# Return the deferring function. It will be called at some point after
# this method returns.
return f
class PluginContainer(object):
"""A base class for a container which holds some Usdview plugins. Specific
containers should inherit from this class and define the 'registerPlugins'
and 'configureView' methods.
"""
def deferredImport(self, moduleName):
"""Return a DeferredImport object which can be used to lazy load
functions when they are invoked for the first time.
"""
return DeferredImport(moduleName, self.__module__)
def registerPlugins(self, plugRegistry, plugCtx):
"""This method is called after the container is discovered by Usdview,
and should call 'registerCommandPlugin' one or more times on the
plugRegistry to add commands to Usdview.
"""
raise NotImplementedError
def configureView(self, plugRegistry, plugUIBuilder):
"""This method is called directly after 'registerPlugins' and can be
used to add menus which invoke a plugin command using the plugUIBuilder.
"""
raise NotImplementedError
# We load the PluginContainer using libplug so it needs to be a defined Tf.Type.
PluginContainerTfType = Tf.Type.Define(PluginContainer)
class CommandPlugin(object):
"""A Usdview command plugin object. The plugin's `callback` parameter must
be a callable object which takes a UsdviewApi object as its only parameter.
"""
def __init__(self, name, displayName, callback, description, usdviewApi):
self._name = name
self._displayName = displayName
self._callback = callback
self._usdviewApi = usdviewApi
self._description = description
@property
def name(self):
"""Return the command's name."""
return self._name
@property
def displayName(self):
"""Return the command's display name."""
return self._displayName
@property
def description(self):
"""Return the command description."""
return self._description
def run(self):
"""Run the command's callback function."""
self._callback(self._usdviewApi)
class PluginMenu(object):
"""Object which adds Usdview command plugins to a QMenu."""
def __init__(self, qMenu):
self._qMenu = qMenu
self._submenus = dict()
def addItem(self, commandPlugin, shortcut=None):
"""Add a new command plugin to the menu. Optionally, provide a hotkey/
shortcut.
"""
action = self._qMenu.addAction(commandPlugin.displayName,
lambda: commandPlugin.run())
action.setToolTip(commandPlugin.description)
if shortcut is not None:
action.setShortcut(QtGui.QKeySequence(shortcut))
def findOrCreateSubmenu(self, menuName):
"""Get a PluginMenu object for the submenu with the given name. If no
submenu with the given name exists, it is created.
"""
if menuName in self._submenus:
return self._submenus[menuName]
else:
subQMenu = self._qMenu.addMenu(menuName)
subQMenu.setToolTipsVisible(True)
submenu = PluginMenu(subQMenu)
self._submenus[menuName] = submenu
return submenu
def addSeparator(self):
"""Add a separator to the menu."""
self._qMenu.addSeparator()
class PluginRegistry(object):
"""Manages all plugins loaded by Usdview."""
def __init__(self, usdviewApi):
self._usdviewApi = usdviewApi
self._commandPlugins = dict()
def registerCommandPlugin(self, name, displayName, callback,
description=""):
"""Creates, registers, and returns a new command plugin.
The plugin's `name` parameter is used to find the plugin from the
registry later. It is good practice to prepend the plugin container's
name to the plugin's `name` parameter to avoid duplicate names
(i.e. "MyPluginContainer.myPluginName"). If a duplicate name is found, a
DuplicateCommandPlugin exception will be raised.
The `displayName` parameter is the name displayed to users.
The plugin's `callback` parameter must be a callable object which takes
a UsdviewApi object as its only parameter.
The optional `description` parameter is a short description of what the
command does which can be displayed to users.
"""
plugin = CommandPlugin(name, displayName, callback, description,
self._usdviewApi)
if name in self._commandPlugins:
raise DuplicateCommandPlugin(name)
self._commandPlugins[name] = plugin
return plugin
def getCommandPlugin(self, name):
"""Finds and returns a registered command plugin. If no plugin with the
given name is registered, return None instead.
"""
return self._commandPlugins.get(name, None)
class PluginUIBuilder(object):
"""Used by plugins to construct UI elements in Usdview."""
def __init__(self, mainWindow):
self._mainWindow = mainWindow
self._menus = dict()
def findOrCreateMenu(self, menuName):
"""Get a PluginMenu object for the menu with the given name. If no menu
with the given name exists, it is created.
"""
if menuName in self._menus:
return self._menus[menuName]
else:
qMenu = self._mainWindow.menuBar().addMenu(menuName)
qMenu.setToolTipsVisible(True)
menu = PluginMenu(qMenu)
self._menus[menuName] = menu
return menu
def loadPlugins(usdviewApi, mainWindow):
"""Find and load all Usdview plugins."""
# Find all the defined container types using libplug.
containerTypes = Plug.Registry.GetAllDerivedTypes(
PluginContainerTfType)
# Find all plugins and plugin container types through libplug.
plugins = dict()
for containerType in containerTypes:
plugin = Plug.Registry().GetPluginForType(containerType)
pluginContainerTypes = plugins.setdefault(plugin, [])
pluginContainerTypes.append(containerType)
# Load each plugin in alphabetical order by name. For each plugin, load all
# of its containers in alphabetical order by type name.
allContainers = []
for plugin in sorted(plugins.keys(), key=lambda plugin: plugin.name):
plugin.Load()
pluginContainerTypes = sorted(
plugins[plugin], key=lambda containerType: containerType.typeName)
for containerType in pluginContainerTypes:
if containerType.pythonClass is None:
print(("WARNING: Missing plugin container '{}' from plugin "
"'{}'. Make sure the container is a defined Tf.Type and "
"the container's import path matches the path in "
"plugInfo.json.").format(
containerType.typeName, plugin.name), file=sys.stderr)
continue
container = containerType.pythonClass()
allContainers.append(container)
# No plugins to load, so don't create a registry.
if len(allContainers) == 0:
return None
# Register all plugins from each container. If there is a naming conflict,
# abort plugin initialization.
registry = PluginRegistry(usdviewApi)
for container in allContainers:
try:
container.registerPlugins(registry, usdviewApi)
except DuplicateCommandPlugin as e:
print("WARNING: {}".format(e), file=sys.stderr)
print("Plugins will not be loaded.", file=sys.stderr)
return None
# Allow each plugin to construct UI elements.
uiBuilder = PluginUIBuilder(mainWindow)
for container in allContainers:
container.configureView(registry, uiBuilder)
return registry
| 11,947 | Python | 33.333333 | 80 | 0.652549 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.