浏览代码

draft

/main
Kevin Gu 4 年前
当前提交
4c25184a
共有 27 个文件被更改,包括 5897 次插入0 次删除
  1. 313
      engine/Build.bee.cs
  2. 97
      engine/README.md
  3. 1001
      engine/bee.exe
  4. 1001
      engine/bee.pdb
  5. 103
      engine/src/engine.cc
  6. 75
      engine/src/platform_base.h
  7. 51
      engine/src/render_api.cc
  8. 24
      engine/src/render_api.h
  9. 451
      engine/src/render_api_d3d11.cc
  10. 222
      engine/src/render_api_opengles.cc
  11. 310
      engine/src/render_api_vulkan.cc
  12. 438
      engine/third_party/Unity/IUnityEventQueue.h
  13. 57
      engine/third_party/Unity/IUnityGraphics.h
  14. 23
      engine/third_party/Unity/IUnityGraphicsD3D11.h
  15. 183
      engine/third_party/Unity/IUnityGraphicsD3D12.h
  16. 74
      engine/third_party/Unity/IUnityGraphicsMetal.h
  17. 237
      engine/third_party/Unity/IUnityGraphicsVulkan.h
  18. 206
      engine/third_party/Unity/IUnityInterface.h
  19. 265
      engine/third_party/Unity/IUnityProfiler.h
  20. 174
      engine/third_party/Unity/IUnityProfilerCallbacks.h
  21. 377
      engine/third_party/Unity/IUnityRenderingExtensions.h
  22. 210
      engine/third_party/Unity/IUnityShaderCompilerAccess.h
  23. 5
      engine/third_party/Unity/LICENSE.md

313
engine/Build.bee.cs


using System;
using System.Linq;
using Bee.Core;
using Bee.DotNet;
using Bee.ProjectGeneration.VisualStudio;
using Bee.VisualStudioSolution;
using static Bee.NativeProgramSupport.NativeProgramConfiguration;
using Bee.NativeProgramSupport;
class Build
{
static void Main()
{
var libUIWidgets = SetupLibUIWidgets();
var builder = new VisualStudioNativeProjectFileBuilder(libUIWidgets);
builder = libUIWidgets.SetupConfigurations.Aggregate(
builder,
(current, c) => current.AddProjectConfiguration(c));
var sln = new VisualStudioSolution();
sln.Path = "libUIWidgets.gen.sln";
sln.Projects.Add(builder.DeployTo("libUIWidgets.gen.vcxproj"));
Backend.Current.AddAliasDependency("ProjectFiles", sln.Setup());
}
static NativeProgram SetupLibUIWidgets()
{
var np = new NativeProgram("libUIWidgets")
{
Sources =
{
"src/engine.cc",
"src/platform_base.h",
"src/render_api.cc",
"src/render_api.h",
"src/render_api_d3d11.cc",
//"src/render_api_vulkan.cc",
//"src/render_api_opengles.cc",
},
OutputName = {c => $"libUIWidgets{(c.CodeGen == CodeGen.Debug ? "_d" : "")}"},
};
np.CompilerSettings().Add(c => c.WithCppLanguageVersion(CppLanguageVersion.Cpp17));
np.IncludeDirectories.Add("third_party");
np.Defines.Add(c => c.CodeGen == CodeGen.Debug,
new[] {"_ITERATOR_DEBUG_LEVEL=2", "_HAS_ITERATOR_DEBUGGING=1", "_SECURE_SCL=1"});
np.LinkerSettings().Add(l => l.WithCustomFlags_workaround(new[] {"/DEBUG:FULL"}));
SetupFml(np);
SetupSkia(np);
var toolchain = ToolChain.Store.Windows().VS2019().Sdk_17134().x64();
var codegens = new[] {CodeGen.Debug};
foreach (var codegen in codegens)
{
var config = new NativeProgramConfiguration(codegen, toolchain, lump: true);
var builtNP = np.SetupSpecificConfiguration(config, toolchain.DynamicLibraryFormat)
.DeployTo("build");
builtNP.DeployTo("../Samples/UIWidgetsSamples_2019_4/Assets/Plugins/x86_64");
}
//
// var npAndroid = new NativeProgram("libUIWidgets")
// {
// Sources =
// {
// "src/engine.cc",
// "src/platform_base.h",
// "src/render_api.cc",
// "src/render_api.h",
// "src/render_api_vulkan.cc",
// "src/render_api_opengles.cc",
// },
// OutputName = {c => $"libUIWidgets{(c.CodeGen == CodeGen.Debug ? "_d" : "")}"},
// };
//
// npAndroid.Defines.Add("SUPPORT_VULKAN");
// npAndroid.CompilerSettings().Add(c => c.WithCppLanguageVersion(CppLanguageVersion.Cpp17));
// npAndroid.IncludeDirectories.Add("third_party");
//
// SetupSkiaAndroid(npAndroid);
//
// var androidToolchain = ToolChain.Store.Android().r19().Arm64();
//
// foreach (var codegen in codegens)
// {
// var config = new NativeProgramConfiguration(codegen, androidToolchain, lump: true);
//
// // var builtNP = npAndroid.SetupSpecificConfiguration(config, androidToolchain.DynamicLibraryFormat)
// // .DeployTo("build_android_arm64");
// //
// // builtNP.DeployTo("../Samples/UIWidgetsSamples_2019_4/Assets/Plugins/Android/arm64");
// // builtNP.DeployTo("../Samples/UIWidgetsSamples_2019_4/BuildAndroid/unityLibrary/src/main/jniLibs/arm64-v8a/");
// }
return np;
}
static void SetupFml(NativeProgram np)
{
var flutterRoot = Environment.GetEnvironmentVariable("FLUTTER_ROOT");
if (string.IsNullOrEmpty(flutterRoot))
{
flutterRoot = Environment.GetEnvironmentVariable("USERPROFILE") + "/engine/src";
}
np.Defines.Add(new[]
{
// gn desc out\host_debug_unopt\ //flutter/fml:fml_lib defines
"USE_OPENSSL=1",
"__STD_C",
"_CRT_RAND_S",
"_CRT_SECURE_NO_DEPRECATE",
"_HAS_EXCEPTIONS=0",
"_SCL_SECURE_NO_DEPRECATE",
"WIN32_LEAN_AND_MEAN",
"NOMINMAX",
"_ATL_NO_OPENGL",
"_WINDOWS",
"CERT_CHAIN_PARA_HAS_EXTRA_FIELDS",
"NTDDI_VERSION=0x06030000",
"PSAPI_VERSION=1",
"WIN32",
"_SECURE_ATL",
"_USING_V110_SDK71_",
"_UNICODE",
"UNICODE",
"_WIN32_WINNT=0x0603",
"WINVER=0x0603",
"_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS",
"_DEBUG",
"FLUTTER_RUNTIME_MODE_DEBUG=1",
"FLUTTER_RUNTIME_MODE_PROFILE=2",
"FLUTTER_RUNTIME_MODE_RELEASE=3",
"FLUTTER_RUNTIME_MODE_JIT_RELEASE=4",
"FLUTTER_RUNTIME_MODE=1",
"FLUTTER_JIT_RUNTIME=1",
});
np.IncludeDirectories.Add(flutterRoot);
np.Libraries.Add(c =>
{
var basePath = flutterRoot + "/out/host_debug_unopt";
return new PrecompiledLibrary[]
{
new StaticLibrary(basePath + "/obj/flutter/fml/fml_lib.lib"),
};
});
}
static void SetupSkia(NativeProgram np)
{
var skiaRoot = Environment.GetEnvironmentVariable("SKIA_ROOT");
if (string.IsNullOrEmpty(skiaRoot))
{
skiaRoot = Environment.GetEnvironmentVariable("USERPROFILE") + "/skia_repo/skia";
}
np.Defines.Add(new[]
{
// bin\gn desc out\Debug\ //:skia defines
"SK_ENABLE_SPIRV_VALIDATION",
"_CRT_SECURE_NO_WARNINGS",
"_HAS_EXCEPTIONS=0",
"WIN32_LEAN_AND_MEAN",
"NOMINMAX",
"SK_GAMMA_APPLY_TO_A8",
"SK_ALLOW_STATIC_GLOBAL_INITIALIZERS=1",
"GR_TEST_UTILS=1",
"SKIA_IMPLEMENTATION=1",
"SK_GL",
"SK_ENABLE_DUMP_GPU",
"SK_SUPPORT_PDF",
"SK_CODEC_DECODES_JPEG",
"SK_ENCODE_JPEG",
"SK_SUPPORT_XPS",
"SK_ENABLE_ANDROID_UTILS",
"SK_USE_LIBGIFCODEC",
"SK_HAS_HEIF_LIBRARY",
"SK_CODEC_DECODES_PNG",
"SK_ENCODE_PNG",
"SK_ENABLE_SKSL_INTERPRETER",
"SK_CODEC_DECODES_WEBP",
"SK_ENCODE_WEBP",
"SK_XML",
// bin\gn desc out\Debug\ //third_party/angle2:libEGL defines
"LIBEGL_IMPLEMENTATION",
"_CRT_SECURE_NO_WARNINGS",
"_HAS_EXCEPTIONS=0",
"WIN32_LEAN_AND_MEAN",
"NOMINMAX",
"ANGLE_ENABLE_ESSL",
"ANGLE_ENABLE_GLSL",
"ANGLE_ENABLE_HLSL",
"ANGLE_ENABLE_OPENGL",
"EGL_EGLEXT_PROTOTYPES",
"GL_GLEXT_PROTOTYPES",
"ANGLE_ENABLE_D3D11",
"ANGLE_ENABLE_D3D9",
"GL_APICALL=",
"GL_API=",
"EGLAPI=",
});
np.IncludeDirectories.Add(skiaRoot);
np.IncludeDirectories.Add(skiaRoot + "/third_party/externals/angle2/include");
// np.IncludeDirectories.Add(skiaRoot + "/include/third_party/vulkan");
np.Libraries.Add(IsWindows, c =>
{
var basePath = skiaRoot + "/out/Debug";
return new PrecompiledLibrary[]
{
new StaticLibrary(basePath + "/skia.lib"),
new StaticLibrary(basePath + "/skottie.lib"),
new StaticLibrary(basePath + "/sksg.lib"),
new StaticLibrary(basePath + "/skshaper.lib"),
new StaticLibrary(basePath + "/libEGL.dll.lib"),
new StaticLibrary(basePath + "/libGLESv2.dll.lib"),
// new SystemLibrary("Opengl32.lib"),
new SystemLibrary("User32.lib"),
//new SystemLibrary("D3D12.lib"),
//new SystemLibrary("DXGI.lib"),
//new SystemLibrary("d3dcompiler.lib"),
// new SystemLibrary(basePath + "/obj/tools/trace/trace.ChromeTracingTracer.obj"),
// new SystemLibrary(basePath + "/obj/tools/trace/trace.EventTracingPriv.obj"),
// new SystemLibrary(basePath + "/obj/tools/trace/trace.SkDebugfTracer.obj"),
// new SystemLibrary(basePath + "/obj/tools/flags/flags.CommandLineFlags.obj"),
};
});
var basePath = skiaRoot + "/out/Debug";
np.SupportFiles.Add(
new DeployableFile(basePath + "/libEGL.dll"),
new DeployableFile(basePath + "/libEGL.dll.pdb"),
new DeployableFile(basePath + "/libGLESv2.dll"),
new DeployableFile(basePath + "/libGLESv2.dll.pdb")
);
}
// static void SetupSkiaAndroid(NativeProgram np)
// {
// var skiaRoot = Environment.GetEnvironmentVariable("SKIA_ROOT");
// if (string.IsNullOrEmpty(skiaRoot))
// {
// skiaRoot = Environment.GetEnvironmentVariable("USERPROFILE") + "/skia_repo/skia";
// }
//
// np.Defines.Add(new[]
// {
// // bin\gn desc out\arm64\ //:skia defines
// "SK_ENABLE_SPIRV_VALIDATION",
// "SK_GAMMA_APPLY_TO_A8",
// "SK_GAMMA_EXPONENT=1.4",
// "SK_GAMMA_CONTRAST=0.0",
// "SK_ALLOW_STATIC_GLOBAL_INITIALIZERS=1",
// "GR_TEST_UTILS=1",
// "SK_USE_VMA",
// "SKIA_IMPLEMENTATION=1",
// "SK_GL",
// "SK_VULKAN",
// "SK_ENABLE_VK_LAYERS",
// "SK_ENABLE_DUMP_GPU",
// "SK_SUPPORT_PDF",
// "SK_CODEC_DECODES_JPEG",
// "SK_ENCODE_JPEG",
// "SK_ENABLE_ANDROID_UTILS",
// "SK_USE_LIBGIFCODEC",
// "SK_HAS_HEIF_LIBRARY",
// "SK_CODEC_DECODES_PNG",
// "SK_ENCODE_PNG",
// "SK_CODEC_DECODES_RAW",
// "SK_ENABLE_SKSL_INTERPRETER",
// "SKVM_JIT",
// "SK_CODEC_DECODES_WEBP",
// "SK_ENCODE_WEBP",
// "SK_XML",
// "XML_STATIC"
// });
//
// np.IncludeDirectories.Add(skiaRoot);
//
// np.Libraries.Add(c =>
// {
// var basePath = skiaRoot + "/out/arm64";
// return new PrecompiledLibrary[]
// {
// new StaticLibrary(basePath + "/libskia.a"),
// new StaticLibrary(basePath + "/libskottie.a"),
// new StaticLibrary(basePath + "/libsksg.a"),
// new StaticLibrary(basePath + "/libskshaper.a"),
// new SystemLibrary("EGL"),
// new SystemLibrary("GLESv2"),
// new SystemLibrary("log"),
// new StaticLibrary(basePath + "/obj/src/utils/libskia.SkJSON.o"),
// new StaticLibrary(basePath + "/obj/src/core/libskia.SkCubicMap.o"),
// new StaticLibrary(basePath + "/obj/src/effects/libskia.SkColorMatrix.o"),
// new StaticLibrary(basePath + "/obj/src/pathops/libskia.SkOpBuilder.o"),
// new StaticLibrary(basePath + "/obj/src/utils/libskia.SkParse.o"),
// };
// });
// }
}

97
engine/README.md


# UIWidgets Engine
## Introduction
This is the engine code of UIWidgets.
## How to Build Depedencies (Windows)
### Build Skia
1. Install depot_tools
```
git clone 'https://chromium.googlesource.com/chromium/tools/depot_tools.git'
```
Add ${PWD}/depot_tools to PATH
2. Clone the skia Repo
git clone https://skia.googlesource.com/skia.git
cd skia
git checkout chrome/m85
python2 tools/git-sync-deps
3. Build skia
```
bin/gn gen out/Debug
```
Update out/Debug/args.gn with the following content:
```
clang_win = "C:\Program Files\LLVM"
cc = "clang"
cxx = "clang++"
is_debug = true
skia_use_angle = true
skia_use_egl = true
extra_cflags = [
"/MTd",
"-I../../third_party/externals/angle2/include",
]
```
```
ninja -C out/Debug -k 0
```
Ignore this error: "lld-link: error: could not open 'EGL': no such file or directory"
### Build flutter fml
1. Setting up the Engine development environment
Follow https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment
2. Compiling for Windows
Follow https://github.com/flutter/flutter/wiki/Compiling-the-engine#compiling-for-windows
3. Checkout flutter-1.17-candidate.5
```
cd engine/src/flutter
git checkout flutter-1.17-candidate.5
gclient sync -D
```
Apply the following diff:
```
diff --git a/fml/BUILD.gn b/fml/BUILD.gn
index 9b5626e78..da1322ce5 100644
--- a/fml/BUILD.gn
+++ b/fml/BUILD.gn
@@ -295,3 +295,10 @@ executable("fml_benchmarks") {
"//flutter/runtime:libdart",
]
}
+
+static_library("fml_lib") {
+ complete_static_lib = true
+ deps = [
+ "//flutter/fml",
+ ]
+}
```
```
set GYP_MSVS_OVERRIDE_PATH=C:\Program Files (x86)\Microsoft Visual Studio\2017\Community
cd engine/src
python ./flutter/tools/gn --unoptimized
ninja -C .\out\host_debug_unopt\ flutter/fml:fml_lib
```
### Build flutter txt
...
## How to Build Engine
```
bee
```

1001
engine/bee.exe
文件差异内容过多而无法显示
查看文件

1001
engine/bee.pdb
文件差异内容过多而无法显示
查看文件

103
engine/src/engine.cc


#include <assert.h>
#include "Unity/IUnityGraphics.h"
#include "include/core/SkSurface.h"
#include "include/gpu/GrBackendSurface.h"
#include "render_api.h"
static IUnityInterfaces* s_UnityInterfaces = NULL;
static IUnityGraphics* s_Graphics = NULL;
static UnityGfxRenderer s_DeviceType = kUnityGfxRendererNull;
static RenderAPI* s_CurrentAPI = NULL;
static void UNITY_INTERFACE_API
OnGraphicsDeviceEvent(UnityGfxDeviceEventType eventType) {
if (eventType == kUnityGfxDeviceEventInitialize) {
assert(s_CurrentAPI == NULL);
s_DeviceType = s_Graphics->GetRenderer();
s_CurrentAPI = CreateRenderAPI(s_DeviceType);
}
if (s_CurrentAPI) {
s_CurrentAPI->ProcessDeviceEvent(eventType, s_UnityInterfaces);
}
if (eventType == kUnityGfxDeviceEventShutdown) {
delete s_CurrentAPI;
s_CurrentAPI = NULL;
s_DeviceType = kUnityGfxRendererNull;
}
}
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
UnityPluginLoad(IUnityInterfaces* unityInterfaces) {
s_UnityInterfaces = unityInterfaces;
s_Graphics = s_UnityInterfaces->Get<IUnityGraphics>();
s_Graphics->RegisterDeviceEventCallback(OnGraphicsDeviceEvent);
OnGraphicsDeviceEvent(kUnityGfxDeviceEventInitialize);
}
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload() {
s_Graphics->UnregisterDeviceEventCallback(OnGraphicsDeviceEvent);
}
// --------------------------------------------------------------------------
// SetTextureFromUnity, an example function we export which is called by one of
// the scripts.
extern "C" UNITY_INTERFACE_EXPORT void* UNITY_INTERFACE_API
CreateTexture(int w, int h) {
if (s_CurrentAPI == NULL) {
return NULL;
}
return s_CurrentAPI->CreateTexture(w, h);
}
extern "C" UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API
CreateTexture1(void *ptr, int w, int h) {
if (s_CurrentAPI == NULL) {
return;
}
s_CurrentAPI->CreateTexture1(ptr, w, h);
}
extern "C" UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API
SetImageTexture(void *ptr) {
if (s_CurrentAPI == NULL) {
return;
}
return s_CurrentAPI->SetImageTexture(ptr);
}
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API Draw123() {
if (s_CurrentAPI == NULL) {
return;
}
s_CurrentAPI->Draw();
}
static void UNITY_INTERFACE_API OnRenderEvent(int eventID) {
// Unknown / unsupported graphics device type? Do nothing
if (s_CurrentAPI == NULL) {
return;
}
if (eventID == 1) {
s_CurrentAPI->Draw();
} else if (eventID == 2) {
s_CurrentAPI->PreDraw();
} else if (eventID == 3) {
s_CurrentAPI->PostDraw();
}
}
extern "C" UnityRenderingEvent UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
GetRenderEventFunc() {
return OnRenderEvent;
}

75
engine/src/platform_base.h


#pragma once
// Standard base includes, defines that indicate our current platform, etc.
#include <stddef.h>
// Which platform we are on?
// UNITY_WIN - Windows (regular win32)
// UNITY_OSX - Mac OS X
// UNITY_LINUX - Linux
// UNITY_IOS - iOS
// UNITY_TVOS - tvOS
// UNITY_ANDROID - Android
// UNITY_METRO - WSA or UWP
// UNITY_WEBGL - WebGL
#if _MSC_VER
#define UNITY_WIN 1
#elif defined(__APPLE__)
#if TARGET_OS_TV
#define UNITY_TVOS 1
#elif TARGET_OS_IOS
#define UNITY_IOS 1
#else
#define UNITY_OSX 1
#endif
#elif defined(__ANDROID__)
#define UNITY_ANDROID 1
#elif defined(UNITY_METRO) || defined(UNITY_LINUX) || defined(UNITY_WEBGL)
// these are defined externally
#elif defined(__EMSCRIPTEN__)
// this is already defined in Unity 5.6
#define UNITY_WEBGL 1
#else
#error "Unknown platform!"
#endif
// Which graphics device APIs we possibly support?
#if UNITY_METRO
#define SUPPORT_D3D11 1
#if WINDOWS_UWP
#define SUPPORT_D3D12 1
#endif
#elif UNITY_WIN
#define SUPPORT_D3D11 1 // comment this out if you don't have D3D11 header/library files
#define SUPPORT_D3D12 1 // comment this out if you don't have D3D12 header/library files
#define SUPPORT_OPENGL_UNIFIED 0
#define SUPPORT_OPENGL_CORE 0
#define SUPPORT_VULKAN 0 // Requires Vulkan SDK to be installed
#elif UNITY_IOS || UNITY_TVOS || UNITY_ANDROID || UNITY_WEBGL
#ifndef SUPPORT_OPENGL_ES
#define SUPPORT_OPENGL_ES 1
#endif
#define SUPPORT_OPENGL_UNIFIED SUPPORT_OPENGL_ES
#ifndef SUPPORT_VULKAN
#define SUPPORT_VULKAN 1
#endif
#elif UNITY_OSX || UNITY_LINUX
#define SUPPORT_OPENGL_UNIFIED 1
#define SUPPORT_OPENGL_CORE 1
#endif
#if UNITY_IOS || UNITY_TVOS || UNITY_OSX
#define SUPPORT_METAL 1
#endif
// COM-like Release macro
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(a) if (a) { a->Release(); a = NULL; }
#endif

51
engine/src/render_api.cc


#include "render_api.h"
#include "platform_base.h"
#include "Unity/IUnityGraphics.h"
RenderAPI* CreateRenderAPI(UnityGfxRenderer apiType)
{
# if SUPPORT_D3D11
if (apiType == kUnityGfxRendererD3D11)
{
extern RenderAPI* CreateRenderAPI_D3D11();
return CreateRenderAPI_D3D11();
}
# endif // if SUPPORT_D3D11
// # if SUPPORT_D3D12
// if (apiType == kUnityGfxRendererD3D12)
// {
// extern RenderAPI* CreateRenderAPI_D3D12();
// return CreateRenderAPI_D3D12();
// }
// # endif // if SUPPORT_D3D12
# if SUPPORT_OPENGL_UNIFIED
if (apiType == kUnityGfxRendererOpenGLCore || apiType == kUnityGfxRendererOpenGLES20 || apiType == kUnityGfxRendererOpenGLES30)
{
extern RenderAPI* CreateRenderAPI_OpenGLCoreES(UnityGfxRenderer apiType);
return CreateRenderAPI_OpenGLCoreES(apiType);
}
# endif // if SUPPORT_OPENGL_UNIFIED
// # if SUPPORT_METAL
// if (apiType == kUnityGfxRendererMetal)
// {
// extern RenderAPI* CreateRenderAPI_Metal();
// return CreateRenderAPI_Metal();
// }
// # endif // if SUPPORT_METAL
//# if SUPPORT_VULKAN
// if (apiType == kUnityGfxRendererVulkan)
// {
// extern RenderAPI* CreateRenderAPI_Vulkan();
// return CreateRenderAPI_Vulkan();
// }
//# endif // if SUPPORT_VULKAN
// Unknown or unsupported graphics API
return NULL;
}

24
engine/src/render_api.h


#pragma once
#include "Unity/IUnityGraphics.h"
class RenderAPI {
public:
virtual ~RenderAPI() {}
virtual void ProcessDeviceEvent(UnityGfxDeviceEventType type,
IUnityInterfaces* interfaces) = 0;
virtual void CreateTexture1(void* ptr, int width, int height) = 0;
virtual void* CreateTexture(int width, int height) = 0;
virtual void SetImageTexture(void* ptr) = 0;
virtual void Draw() = 0;
virtual void PreDraw() = 0;
virtual void PostDraw() = 0;
};
RenderAPI* CreateRenderAPI(UnityGfxRenderer apiType);

451
engine/src/render_api_d3d11.cc


#include <cassert>
#include "platform_base.h"
#include "render_api.h"
// Direct3D 11 implementation of RenderAPI.
#if SUPPORT_D3D11
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <assert.h>
#include <d3d11.h>
#include <string.h>
#include <vector>
#include "Unity/IUnityGraphicsD3D11.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkSurface.h"
#include "include/core/SkTextBlob.h"
#include "include/effects/SkPerlinNoiseShader.h"
#include "include/gpu/GrBackendSurface.h"
#include "include/gpu/GrContext.h"
#include "include/gpu/gl/GrGLTypes.h"
#include "modules/skottie/include/Skottie.h"
#include "src/gpu/gl/GrGLDefines.h"
#include "third_party/dart/runtime/include/dart_tools_api.h"
void Dart_TimelineEvent(const char* label, int64_t timestamp0,
int64_t timestamp1_or_async_id,
Dart_Timeline_Event_Type type, intptr_t argument_count,
const char** argument_names,
const char** argument_values) {}
int64_t Dart_TimelineGetMicros() { return 0; }
class RenderAPI_D3D11 : public RenderAPI {
public:
RenderAPI_D3D11();
virtual ~RenderAPI_D3D11() {}
virtual void ProcessDeviceEvent(UnityGfxDeviceEventType type,
IUnityInterfaces* interfaces);
void* CreateTexture(int width, int height) override;
void CreateTexture1(void* ptr1, int width, int height) override;
void SetImageTexture(void* ptr) override;
void Draw() override;
void PreDraw() override;
void PostDraw() override;
private:
void CreateResources();
void ReleaseResources();
void draw(SkCanvas* canvas);
private:
ID3D11Device* m_Device;
ID3D11Device* m_DeviceSkia;
EGLDeviceEXT m_eglDevice;
EGLDisplay m_eglDisplay;
EGLConfig m_eglConfig;
EGLContext m_eglContext;
ID3D11Texture2D* m_TextureHandle = NULL;
int m_TextureWidth = 0;
int m_TextureHeight = 0;
sk_sp<GrContext> m_GrContext;
GrBackendTexture m_backendTex;
sk_sp<SkSurface> m_SkSurface;
IDXGIKeyedMutex* mutex_unity;
IDXGIKeyedMutex* mutex_skia;
sk_sp<skottie::Animation> animation_;
ID3D11Texture2D* image_texture_ = NULL;
sk_sp<SkImage> image_;
};
RenderAPI* CreateRenderAPI_D3D11() { return new RenderAPI_D3D11(); }
RenderAPI_D3D11::RenderAPI_D3D11() : m_Device(NULL) {}
void RenderAPI_D3D11::ProcessDeviceEvent(UnityGfxDeviceEventType type,
IUnityInterfaces* interfaces) {
fml::MessageLoop* loop1 = nullptr;
fml::AutoResetWaitableEvent latch1;
fml::AutoResetWaitableEvent term1;
std::thread thread1([&loop1, &latch1, &term1]() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
loop1 = &fml::MessageLoop::GetCurrent();
latch1.Signal();
term1.Wait();
});
fml::MessageLoop* loop2 = nullptr;
fml::AutoResetWaitableEvent latch2;
fml::AutoResetWaitableEvent term2;
std::thread thread2([&loop2, &latch2, &term2]() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
loop2 = &fml::MessageLoop::GetCurrent();
latch2.Signal();
term2.Wait();
});
latch1.Wait();
latch2.Wait();
term1.Signal();
term2.Signal();
thread1.join();
thread2.join();
switch (type) {
case kUnityGfxDeviceEventInitialize: {
IUnityGraphicsD3D11* d3d = interfaces->Get<IUnityGraphicsD3D11>();
m_Device = d3d->GetDevice();
CreateResources();
break;
}
case kUnityGfxDeviceEventShutdown:
ReleaseResources();
break;
}
}
void RenderAPI_D3D11::CreateResources() {
IDXGIDevice* dxgi_device;
HRESULT hr = m_Device->QueryInterface(__uuidof(IDXGIDevice),
reinterpret_cast<void**>(&dxgi_device));
assert(SUCCEEDED(hr) && "UgpDXGISwapChain: QueryInterface(...) failed");
IDXGIAdapter* adapter;
hr = dxgi_device->GetAdapter(&adapter);
assert(SUCCEEDED(hr) && "UgpDXGISwapChain: GetAdapter(...) failed");
DXGI_ADAPTER_DESC adapter_desc;
hr = adapter->GetDesc(&adapter_desc);
assert(SUCCEEDED(hr) && "UgpDXGISwapChain: GetDesc(...) failed");
adapter->Release();
dxgi_device->Release();
EGLint displayAttribs[] = {EGL_PLATFORM_ANGLE_TYPE_ANGLE,
EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
EGL_PLATFORM_ANGLE_D3D_LUID_HIGH_ANGLE,
adapter_desc.AdapterLuid.HighPart,
EGL_PLATFORM_ANGLE_D3D_LUID_LOW_ANGLE,
adapter_desc.AdapterLuid.LowPart,
EGL_NONE};
m_eglDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE,
EGL_DEFAULT_DISPLAY, displayAttribs);
// EGLDeviceEXT eglDevice = eglCreateDeviceANGLE(
// EGL_D3D11_DEVICE_ANGLE, reinterpret_cast<void*>(m_Device), nullptr);
// m_eglDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT,
// eglDevice, nullptr);
eglInitialize(m_eglDisplay, nullptr, nullptr);
EGLAttrib angleDevice = 0;
eglQueryDisplayAttribEXT(m_eglDisplay, EGL_DEVICE_EXT, &angleDevice);
EGLAttrib device = 0;
eglQueryDeviceAttribEXT(reinterpret_cast<EGLDeviceEXT>(angleDevice),
EGL_D3D11_DEVICE_ANGLE, &device);
m_DeviceSkia = reinterpret_cast<ID3D11Device*>(device);
EGLConfig config;
int num_config;
eglGetConfigs(m_eglDisplay, &config, 1, &num_config);
const EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
m_eglContext =
eglCreateContext(m_eglDisplay, config, nullptr, contextAttributes);
eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, m_eglContext);
m_GrContext = GrContext::MakeGL();
animation_ =
skottie::Animation::MakeFromFile(R"(C:\Users\kgdev\skottie.txt)");
// if (rdoc_api) rdoc_api->StartFrameCapture(m_DeviceSkia, NULL);
}
void RenderAPI_D3D11::ReleaseResources() {}
void* RenderAPI_D3D11::CreateTexture(int width, int height) {
ID3D11Texture2D* d3d11_texture = nullptr; // todo: keep reference.
CD3D11_TEXTURE2D_DESC desc(
DXGI_FORMAT_R8G8B8A8_UNORM, width, height, 1, 1,
D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET,
D3D11_USAGE_DEFAULT, 0, 1, 0, D3D11_RESOURCE_MISC_SHARED);
assert(
SUCCEEDED(m_DeviceSkia->CreateTexture2D(&desc, nullptr, &d3d11_texture)));
const EGLint attribs[] = {EGL_NONE};
EGLImage image =
eglCreateImageKHR(m_eglDisplay, EGL_NO_CONTEXT, EGL_D3D11_TEXTURE_ANGLE,
static_cast<EGLClientBuffer>(d3d11_texture), attribs);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image);
GrGLTextureInfo textureInfo;
textureInfo.fTarget = GR_GL_TEXTURE_2D;
textureInfo.fID = texture;
textureInfo.fFormat = GR_GL_RGBA8;
m_backendTex = GrBackendTexture(width, height, GrMipMapped::kNo, textureInfo);
m_GrContext = GrContext::MakeGL();
m_SkSurface = SkSurface::MakeFromBackendTexture(
m_GrContext.get(), m_backendTex, kBottomLeft_GrSurfaceOrigin, 1,
kRGBA_8888_SkColorType, nullptr, nullptr);
IDXGIResource* image_resource;
HRESULT hr = d3d11_texture->QueryInterface(
__uuidof(IDXGIResource), reinterpret_cast<void**>(&image_resource));
assert(SUCCEEDED(hr) &&
"UgpDXGISwapChain: QueryInterface(IDXGIResource1) failed");
HANDLE shared_image_handle;
hr = image_resource->GetSharedHandle(&shared_image_handle);
assert(SUCCEEDED(hr) && "UgpDXGISwapChain: GetSharedHandle() failed");
image_resource->Release();
// hr = d3d11_texture->QueryInterface(__uuidof(IDXGIKeyedMutex),
// (void**)&mutex_skia);
// assert(SUCCEEDED(hr));
IDXGIResource* dxgiResource;
m_Device->OpenSharedResource(shared_image_handle, __uuidof(ID3D11Resource),
(void**)(&dxgiResource));
ID3D11Texture2D* texture_unity;
dxgiResource->QueryInterface(__uuidof(ID3D11Texture2D),
(void**)(&texture_unity));
dxgiResource->Release();
// hr = texture_unity->QueryInterface(__uuidof(IDXGIKeyedMutex),
// (LPVOID*)&mutex_unity);
// assert(SUCCEEDED(hr));
return texture_unity;
}
void RenderAPI_D3D11::CreateTexture1(void* ptr1, int width, int height) {
ID3D11Texture2D* d3d11_texture = (ID3D11Texture2D*)ptr1;
IDXGIResource* image_resource;
HRESULT hr = d3d11_texture->QueryInterface(
__uuidof(IDXGIResource), reinterpret_cast<void**>(&image_resource));
assert(SUCCEEDED(hr) &&
"UgpDXGISwapChain: QueryInterface(IDXGIResource1) failed");
HANDLE shared_image_handle;
hr = image_resource->GetSharedHandle(&shared_image_handle);
assert(SUCCEEDED(hr) && "UgpDXGISwapChain: GetSharedHandle() failed");
image_resource->Release();
IDXGIResource* dxgiResource;
m_DeviceSkia->OpenSharedResource(
shared_image_handle, __uuidof(ID3D11Resource), (void**)(&dxgiResource));
ID3D11Texture2D* texture_unity;
dxgiResource->QueryInterface(__uuidof(ID3D11Texture2D),
(void**)(&texture_unity));
dxgiResource->Release();
// image_texture_ = texture_unity;
const EGLint attribs[] = {EGL_NONE};
EGLImage image =
eglCreateImageKHR(m_eglDisplay, EGL_NO_CONTEXT, EGL_D3D11_TEXTURE_ANGLE,
static_cast<EGLClientBuffer>(texture_unity), attribs);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image);
GrGLTextureInfo textureInfo;
textureInfo.fTarget = GR_GL_TEXTURE_2D;
textureInfo.fID = texture;
textureInfo.fFormat = GR_GL_RGBA8;
m_backendTex = GrBackendTexture(width, height, GrMipMapped::kNo, textureInfo);
m_SkSurface = SkSurface::MakeFromBackendTexture(
m_GrContext.get(), m_backendTex, kBottomLeft_GrSurfaceOrigin, 1,
kRGBA_8888_SkColorType, nullptr, nullptr);
}
void RenderAPI_D3D11::SetImageTexture(void* ptr) {
ID3D11Texture2D* d3d11_texture = (ID3D11Texture2D*)ptr;
IDXGIResource* image_resource;
HRESULT hr = d3d11_texture->QueryInterface(
__uuidof(IDXGIResource), reinterpret_cast<void**>(&image_resource));
assert(SUCCEEDED(hr) &&
"UgpDXGISwapChain: QueryInterface(IDXGIResource1) failed");
HANDLE shared_image_handle;
hr = image_resource->GetSharedHandle(&shared_image_handle);
assert(SUCCEEDED(hr) && "UgpDXGISwapChain: GetSharedHandle() failed");
image_resource->Release();
IDXGIResource* dxgiResource;
m_DeviceSkia->OpenSharedResource(
shared_image_handle, __uuidof(ID3D11Resource), (void**)(&dxgiResource));
ID3D11Texture2D* texture_unity;
dxgiResource->QueryInterface(__uuidof(ID3D11Texture2D),
(void**)(&texture_unity));
dxgiResource->Release();
image_texture_ = texture_unity;
const EGLint attribs[] = {EGL_NONE};
EGLImage image =
eglCreateImageKHR(m_eglDisplay, EGL_NO_CONTEXT, EGL_D3D11_TEXTURE_ANGLE,
static_cast<EGLClientBuffer>(image_texture_), attribs);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image);
GrGLTextureInfo textureInfo;
textureInfo.fTarget = GR_GL_TEXTURE_2D;
textureInfo.fID = texture;
textureInfo.fFormat = GR_GL_RGBA8;
GrBackendTexture backendTex =
GrBackendTexture(1000, 1000, GrMipMapped::kNo, textureInfo);
image_ = SkImage::MakeFromTexture(
m_GrContext.get(), backendTex, kBottomLeft_GrSurfaceOrigin,
kRGBA_8888_SkColorType, kOpaque_SkAlphaType, nullptr);
}
void RenderAPI_D3D11::draw(SkCanvas* canvas) {
canvas->drawColor(SK_ColorWHITE);
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(4);
paint.setColor(SK_ColorRED);
SkRect rect = SkRect::MakeXYWH(50, 50, 40, 60);
canvas->drawRect(rect, paint);
SkRRect oval;
oval.setOval(rect);
oval.offset(40, 60);
paint.setColor(SK_ColorBLUE);
canvas->drawRRect(oval, paint);
paint.setColor(SK_ColorCYAN);
canvas->drawCircle(180, 50, 25, paint);
rect.offset(80, 0);
paint.setColor(SK_ColorYELLOW);
canvas->drawRoundRect(rect, 10, 10, paint);
SkPath path;
path.cubicTo(768, 0, -512, 256, 256, 256);
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
canvas->drawImage(image_, 128, 128, &paint);
SkRect rect2 = SkRect::MakeXYWH(0, 0, 40, 60);
canvas->drawImageRect(image_, rect2, &paint);
SkPaint paint2;
auto text = SkTextBlob::MakeFromString("Hello, Skia!", SkFont(nullptr, 18));
canvas->drawTextBlob(text.get(), 50, 25, paint2);
}
void draw1(SkCanvas* canvas) {
canvas->clear(SK_ColorWHITE);
SkPaint paint;
paint.setShader(
SkPerlinNoiseShader::MakeFractalNoise(0.05f, 0.05f, 4, 0.0f, nullptr));
canvas->drawPaint(paint);
}
double t = 0;
void RenderAPI_D3D11::Draw() {
// mutex_skia->AcquireSync(0, 5000);
SkCanvas* canvas = m_SkSurface->getCanvas();
draw(canvas);
/* canvas->clear(SK_ColorWHITE);
t += 1.0 / 60;
if (t >= animation_->duration()) {
t = 0.0;
}
animation_->seekFrameTime(t);
animation_->render(canvas);*/
SkRect rect = SkRect::MakeLTRB(100, 100, 200, 200);
canvas->drawImageRect(image_, rect, nullptr);
// mutex_skia->ReleaseSync(0);
canvas->flush();
canvas->getGrContext()->submit(true);
// if (rdoc_api) rdoc_api->EndFrameCapture(m_DeviceSkia, NULL);
}
void RenderAPI_D3D11::PreDraw() {
// mutex_unity->AcquireSync(0, 5000);
}
void RenderAPI_D3D11::PostDraw() {
// mutex_unity->ReleaseSync(0);
}
#endif // #if SUPPORT_D3D11

222
engine/src/render_api_opengles.cc


#include <include/gpu/GrContext.h>
#include <src/gpu/gl/GrGLDefines.h>
#include "cassert"
#include "include/core/SkCanvas.h"
#include "include/core/SkSurface.h"
#include "include/core/SkTextBlob.h"
#include "include/effects/SkPerlinNoiseShader.h"
#include "include/gpu/GrBackendSurface.h"
#include "include/gpu/GrContext.h"
#include "include/gpu/gl/GrGLTypes.h"
#include "modules/skottie/include/Skottie.h"
#include "platform_base.h"
#include "render_api.h"
#include "src/gpu/gl/GrGLDefines.h"
#include "windows.h"
#include <wingdi.h>
#if SUPPORT_OPENGL_UNIFIED
#include <GLES2/gl2.h>
class RenderAPI_OpenGLCoreES : public RenderAPI {
public:
RenderAPI_OpenGLCoreES(UnityGfxRenderer apiType);
virtual ~RenderAPI_OpenGLCoreES() {}
void ProcessDeviceEvent(UnityGfxDeviceEventType type,
IUnityInterfaces* interfaces) override;
void* CreateTexture(int width, int height) override { return nullptr; }
void CreateTexture1(void* ptr1, int width, int height) override;
void SetImageTexture(void* ptr) override;
void Draw() override;
void PreDraw() override {}
void PostDraw() override {}
private:
void CreateResources();
void draw(SkCanvas* canvas);
private:
UnityGfxRenderer m_APIType;
GLuint m_VertexShader;
GLuint m_FragmentShader;
GLuint m_Program;
GLuint m_VertexArray;
GLuint m_VertexBuffer;
int m_UniformWorldMatrix;
int m_UniformProjMatrix;
sk_sp<GrContext> gr_context_;
GrBackendTexture m_backendTex;
sk_sp<SkSurface> m_SkSurface;
void* surface_texture1_ptr_;
sk_sp<SkImage> image_;
void* texture1_ptr_;
int width_, height_;
void* image1_ptr_;
HGLRC skia_ctx_ = NULL;
sk_sp<skottie::Animation> animation_;
};
RenderAPI* CreateRenderAPI_OpenGLCoreES(UnityGfxRenderer apiType) {
return new RenderAPI_OpenGLCoreES(apiType);
}
void RenderAPI_OpenGLCoreES::CreateResources() {
HGLRC current_ctx = wglGetCurrentContext();
HDC hdc = wglGetCurrentDC();
//skia_ctx_ = wglCreateContext(hdc);
// wglShareLists(current_ctx, skia_ctx_);
gr_context_ = GrContext::MakeGL();
animation_ =
skottie::Animation::MakeFromFile(R"(C:\Users\kgdev\skottie.txt)");
skia_ctx_ = NULL;
m_SkSurface = nullptr;
surface_texture1_ptr_ = nullptr;
image_ = nullptr;
}
RenderAPI_OpenGLCoreES::RenderAPI_OpenGLCoreES(UnityGfxRenderer apiType)
: m_APIType(apiType) {}
void RenderAPI_OpenGLCoreES::ProcessDeviceEvent(UnityGfxDeviceEventType type,
IUnityInterfaces* interfaces) {
if (type == kUnityGfxDeviceEventInitialize) {
CreateResources();
} else if (type == kUnityGfxDeviceEventShutdown) {
//@TODO: release resources
}
}
void RenderAPI_OpenGLCoreES::CreateTexture1(void* ptr1, int width, int height) {
HGLRC current_ctx = wglGetCurrentContext();
HDC hdc = wglGetCurrentDC();
texture1_ptr_ = ptr1;
width_ = width;
height_ = height;
}
void RenderAPI_OpenGLCoreES::SetImageTexture(void* ptr) { image1_ptr_ = ptr; }
void RenderAPI_OpenGLCoreES::draw(SkCanvas* canvas) {
canvas->drawColor(SK_ColorWHITE);
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(4);
paint.setColor(SK_ColorRED);
SkRect rect = SkRect::MakeXYWH(50, 50, 40, 60);
canvas->drawRect(rect, paint);
SkRRect oval;
oval.setOval(rect);
oval.offset(40, 60);
paint.setColor(SK_ColorBLUE);
canvas->drawRRect(oval, paint);
paint.setColor(SK_ColorCYAN);
canvas->drawCircle(180, 50, 25, paint);
rect.offset(80, 0);
paint.setColor(SK_ColorYELLOW);
canvas->drawRoundRect(rect, 10, 10, paint);
SkPath path;
path.cubicTo(768, 0, -512, 256, 256, 256);
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
canvas->drawImage(image_, 128, 128, &paint);
SkRect rect2 = SkRect::MakeXYWH(0, 0, 40, 60);
canvas->drawImageRect(image_, rect2, &paint);
SkPaint paint2;
auto text = SkTextBlob::MakeFromString("Hello, Skia!", SkFont(nullptr, 18));
canvas->drawTextBlob(text.get(), 50, 25, paint2);
}
double t2 = 0;
void RenderAPI_OpenGLCoreES::Draw() {
// mutex_skia->AcquireSync(0, 5000);
HGLRC current_ctx = wglGetCurrentContext();
HDC hdc = wglGetCurrentDC();
if (!skia_ctx_) {
skia_ctx_ = wglCreateContext(hdc);
wglShareLists(current_ctx, skia_ctx_);
}
bool result = wglMakeCurrent(hdc, skia_ctx_);
if (!m_SkSurface || surface_texture1_ptr_ != texture1_ptr_) {
surface_texture1_ptr_ = texture1_ptr_;
GrGLTextureInfo textureInfo;
textureInfo.fTarget = GR_GL_TEXTURE_2D;
textureInfo.fID = GrGLuint((long)texture1_ptr_);
textureInfo.fFormat = GR_GL_RGBA8;
m_backendTex =
GrBackendTexture(width_, height_, GrMipMapped::kNo, textureInfo);
m_SkSurface = SkSurface::MakeFromBackendTexture(
gr_context_.get(), m_backendTex, kBottomLeft_GrSurfaceOrigin, 1,
kRGBA_8888_SkColorType, nullptr, nullptr);
}
if (!image_) {
GrGLTextureInfo textureInfo;
textureInfo.fTarget = GR_GL_TEXTURE_2D;
textureInfo.fID = GrGLuint((long)image1_ptr_);
textureInfo.fFormat = GR_GL_RGBA8;
GrBackendTexture backendTex =
GrBackendTexture(1000, 1000, GrMipMapped::kNo, textureInfo);
image_ = SkImage::MakeFromTexture(
gr_context_.get(), backendTex, kBottomLeft_GrSurfaceOrigin,
kRGBA_8888_SkColorType, kOpaque_SkAlphaType, nullptr);
}
SkCanvas* canvas = m_SkSurface->getCanvas();
draw(canvas);
canvas->clear(SK_ColorWHITE);
t2 += 1.0 / 60;
if (t2 >= animation_->duration()) {
t2 = 0.0;
}
animation_->seekFrameTime(t2);
animation_->render(canvas);
// SkRect rect = SkRect::MakeLTRB(100, 100, 200, 200);
// canvas->drawImageRect(image_, rect, nullptr);
// mutex_skia->ReleaseSync(0);
canvas->flush();
canvas->getGrContext()->submit(true);
// if (rdoc_api) rdoc_api->EndFrameCapture(m_DeviceSkia, NULL);
wglMakeCurrent(wglGetCurrentDC(), current_ctx);
}
#endif // #if SUPPORT_OPENGL_UNIFIED

310
engine/src/render_api_vulkan.cc
文件差异内容过多而无法显示
查看文件

438
engine/third_party/Unity/IUnityEventQueue.h


// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an AS IS BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityInterface.h"
// 5.2 patch 1 + of Unity will support this.
// The lack or presence of this feature can cause the EventQueue
// to crash if used against the wrong version of Unity.
//
// Before we had the IUnityInterfaces system this interface changed
// to support a cleanup handler on events. This broke our plugins
// in older versions of Unity. The registry should help us with
// this sort of thing in the future.
#ifndef EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
#define EVENTQUEUE_SUPPORTS_EVENT_CLEANUP 1
#endif
////////////////////////////////////////////////////////////////////////////////////////
// NOTE: Do not include any additional headers here. This is an external facing header
// so avoid any internal dependencies.
////////////////////////////////////////////////////////////////////////////////////////
// The Unity EventQueue is a standard way of passing information between plugins or parts
// of the engine without any reliance on managed systems, game objects or
// other pieces of Unity.
//
// Events are simply a structure and GUID pair. GUIDs were chosen rather
// than hashes as it allows plugins to define their own event
// payloads and use the EventQueue.
//
// While the EventQueue itself is self contained and can be used for
// many different applications within Unity the global event
// queue that is passed to plugins is always serviced on the main
// simulation thread and thus serves as a convenient means of
// pushing asynchronous operations back to the main game thread
//
// Payloads should strive to be small. The EventQueue is a 0 allocation
// system which ensures that the use of events does not fragment
// or add undue pressure on resource limited systems.
//
// This header defines ALL that is required to listen, define
// and send events from both within Unity and from plugins.
////////////////////////////////////////////////////////////////////////////////////////
// USAGE:
//
// SENDING
// ========
//
// To Define new Event:
// --------------------
// // Structure and GUID
// struct MyEvent {};
// REGISTER_EVENT_ID(0x19D736400584B24BULL,0x98B9EFBE26D3F3C9ULL,MyEvent)
// // hash above is a GUID split into 2 64 bit integers for convenience.
// // DO NOT DUPLICATE GUIDS!
//
// To Send an Event:
// -----------------
// // Create Payload and send
// MyEvent evt;
// GlobalEventQueue::GetInstance ().SendEvent (evt);
//
// LISTENING
// ==========
//
// STATIC FUNCTION: To Listen For An Event:
// ----------------------------------------
//
// void MyListenFunction (const MyEvent & payload)
// { /* do something useful */ }
//
// // No register that function, create delegate, register delegate with EventQueue
// // Lifetime of delegate is important.
// StaticFunctionEventHandler<MyEvent> myEventDelegate (&MyListenFunction);
// GlobalEventQueue::GetInstance ()->AddHandler (&myEventDelegate);
//
//
// CLASS LISTENER: To Listen on an instance of a class:
// ----------------------------------------------------
// class MyClass
// {
// // This method will get called, always called HandleEvent
// void HandleEvent(const MyEvent & payload);
//
// MyClass()
// {
// // Hookup to listen can be anywhere but here it's in the ctor.
// GlobalEventQueue::GetInstance ()->AddHandler (m_myDelegate.SetObject (this));
// }
//
// ~MyClass()
// {
// // Stop listening.
// GlobalEventQueue::GetInstance ()->RemoveHandler (m_myDelegate);
// }
//
// // Delegate is a member of the class.
// ClassBasedEventHandler<MyEvent,MyClass> m_myDelegate;
// };
// GUID definition for a new event.
//
// There is a tool to compute these, run the tool on the name of your
// message and insert the hash/type combination in your header file.
// This defines the EventId for your event payload (struct)
// Use this for events that do not require a destructor.
#define REGISTER_EVENT_ID(HASHH, HASHL , TYPE) \
namespace UnityEventQueue \
{ \
template<> \
inline const EventId GetEventId< TYPE > () \
{ \
return EventId(HASHH,HASHL) ; \
} \
}
#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
// GUID definition for a new event with a destructor.
//
// If your event payload requires a destructor. Define:
//
// void Destroy()
//
// Which should be a method on your payload and then use this macro.
// If your event
// can guarantee that someone is listening before you fire
// your first event this is all you have to do.
//
// However if you do not know if someone is listening when you
// fire your first event you will need to call RegisterCleanup
// somewhere to ensure your events get cleaned up properly.
//
// There is a tool to compute these, run the tool on the name of your
// payload and insert the hash/type combination in your header file.
#define REGISTER_EVENT_ID_WITH_CLEANUP(HASHH, HASHL, TYPE) \
namespace UnityEventQueue \
{ \
typedef StaticFunctionEventHandler< TYPE > DestructorMethod_##HASHH##HASHL; \
\
template<> \
inline void GenericDestructorMethodForType< TYPE > ( const TYPE & eventPayload ) \
{ const_cast<TYPE&>(eventPayload).Destroy(); } \
\
template<> \
inline EventHandler * GetEventDestructor< TYPE >() \
{ \
static DestructorMethod_##HASHH##HASHL g_Destructor(&GenericDestructorMethodForType< TYPE >); \
return &g_Destructor; \
} \
} \
REGISTER_EVENT_ID(HASHH,HASHL,TYPE)
#endif
namespace UnityEventQueue
{
// EventId - GUID
//
// To facilitate custom events the EventId object must be a full fledged GUID
// to ensure cross plugin uniqueness constraints.
//
// Template specialization is used to produce a means of looking up an
// EventId from it's payload type at compile time. The net result should compile
// down to passing around the GUID.
//
// REGISTER_EVENT_ID should be placed in
// the header file of any payload definition OUTSIDE of all namespaces (all EventIds live
// in the UnityEventQueue namespace by default) The payload structure and the registration ID are all that
// is required to expose the event to other systems.
//
// There is a tool to generate registration macros for EventIds.
struct EventId
{
public:
EventId(unsigned long long high, unsigned long long low)
: mGUIDHigh(high)
, mGUIDLow(low)
{}
EventId(const EventId & other)
{
mGUIDHigh = other.mGUIDHigh;
mGUIDLow = other.mGUIDLow;
}
EventId & operator=(const EventId & other)
{
mGUIDHigh = other.mGUIDHigh;
mGUIDLow = other.mGUIDLow;
return *this;
}
bool Equals(const EventId & other) const { return mGUIDHigh == other.mGUIDHigh && mGUIDLow == other.mGUIDLow; }
bool LessThan(const EventId & other) const { return mGUIDHigh < other.mGUIDHigh || (mGUIDHigh == other.mGUIDHigh && mGUIDLow < other.mGUIDLow); }
unsigned long long mGUIDHigh;
unsigned long long mGUIDLow;
};
inline bool operator==(const EventId & left, const EventId & right) { return left.Equals(right); }
inline bool operator!=(const EventId & left, const EventId & right) { return !left.Equals(right); }
inline bool operator<(const EventId & left, const EventId & right) { return left.LessThan(right); }
inline bool operator>(const EventId & left, const EventId & right) { return right.LessThan(left); }
inline bool operator>=(const EventId & left, const EventId & right) { return !operator<(left, right); }
inline bool operator<=(const EventId & left, const EventId & right) { return !operator>(left, right); }
// Generic Version of GetEventId to allow for specialization
//
// If you get errors about return values related to this method
// then you have forgotten to include REGISTER_EVENT_ID() for your
// payload / event. This method should never be compiled, ever.
template<typename T> const EventId GetEventId();
class EventQueue;
class EventHandler;
#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
// Generic version retrieving a classes destructor.
// Any class that does not specialize this will not define a destructor.
template<typename T> EventHandler * GetEventDestructor() { return (EventHandler*)NULL; }
// This is a static method that helps us call a meaningful method on the event
// itself improving the cleanliness of the EQ design.
template<typename T> void GenericDestructorMethodForType(const T & /*eventPayload*/) {}
#endif
// ====================================================================
// ADAPTER / DELEGATE - This is the base interface that the EventQueue
// uses to know about listeners for events.
//
// DO NOT USE DIRECTLY!
//
// Use the StaticFunction of ClassBased EventHandlers to build
// adapters to your systems and empower them to receive events.
class EventHandler
{
public:
EventHandler() : m_Next(0) {}
virtual ~EventHandler() {}
// This actually kicks the event to the handler function or object.
virtual void HandleEvent(EventId & id, void * data) = 0;
// This is required when registering this handler
virtual EventId HandlerEventId() = 0;
#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
// This is required when registering this handler
virtual EventHandler * GetMyEventDestructor() = 0;
#endif
// Internal, do not use, required for walking and calling handlers
EventHandler * GetNext() { return m_Next; }
private:
// Intrusive list holding a linked list of handlers for this EventId
// Exists to avoid allocations - Do Not Touch.
friend class EventHandlerList;
EventHandler * m_Next;
};
// ====================================================================
// CLASS DELEGATE - Classes can be the target of events.
//
// Event handlers are the endpoints of the system. To Unity all
// event endpoints look like a single virtual function call.
//
// This adapter will call the HandleEvent( EVENTTYPE & ) method
// on the object specified when an event is triggered.
template<typename EVENTTYPE, typename OBJECTTYPE>
class ClassBasedEventHandler : public EventHandler
{
public:
ClassBasedEventHandler(OBJECTTYPE * handler = NULL) : m_Handler(handler) {}
// The actual adapter method, calls into the registered object.
virtual void HandleEvent(EventId & id, void * data)
{ (void)id; m_Handler->HandleEvent(*static_cast<EVENTTYPE*>(data)); }
// Boilerplate required when registering this handler.
virtual EventId HandlerEventId()
{ return GetEventId<EVENTTYPE>(); }
#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
// Required boilerplate. Used during registration of this object.
virtual EventHandler * GetMyEventDestructor()
{ return GetEventDestructor<EVENTTYPE>(); }
#endif
ClassBasedEventHandler<EVENTTYPE, OBJECTTYPE> *
SetObject(OBJECTTYPE * handler)
{ m_Handler = handler; return this; }
#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
OBJECTTYPE * GetHandler()
{ return m_Handler; }
#endif
protected:
OBJECTTYPE * m_Handler;
};
// ====================================================================
// FUNCTION DELEGATE - Static functions can be event handlers.
//
// Event handlers are the endpoints of the system. To Unity all
// event endpoints look like a single virtual function call.
//
// This object wraps a static function turning it into an event endpoint
// much like a C# delegate does.
// The wrapped function will be called when the event is triggered
template<typename EVENTTYPE>
class StaticFunctionEventHandler : public EventHandler
{
public:
typedef void (*HandlerFunction)(const EVENTTYPE & payload);
StaticFunctionEventHandler(HandlerFunction handlerCallback) : m_Handler(handlerCallback) {}
virtual void HandleEvent(EventId & id, void * data)
{ (void)id; m_Handler(*static_cast<EVENTTYPE*>(data)); }
// Required boilerplate. Used during registration of this object.
virtual EventId HandlerEventId()
{ return GetEventId<EVENTTYPE>(); }
#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
// Required boilerplate. Used during registration of this object.
virtual EventHandler * GetMyEventDestructor()
{ return GetEventDestructor<EVENTTYPE>(); }
#endif
protected:
HandlerFunction m_Handler;
};
// ============================================================
// Some built in event types for adding removing event handlers
// from secondary threads. Use these instead of calling AddHandler
// from a secondary thread.
struct AddEventHandler
{
AddEventHandler(EventHandler * handler) : m_Handler(handler) {}
EventHandler * m_Handler;
};
struct RemoveEventHandler
{
RemoveEventHandler(EventHandler * handler) : m_Handler(handler) {}
EventHandler * m_Handler;
};
// ============================================================
// The Event Queue is a lock free multiple write single read
// deferred event system. It uses GUIDs to map payloads to
// event handler delegates. The system has some
// templates to make registering for events fairly painless
// but takes care to try to keep template cost very low.
//
// NOTE: payloads should be very very small and never allocate
// or free memory since they can and will be passed across
// dll boundaries.
//
// There is a hard limit of kMaxEventQueueEventSize bytes for any
// payload being passed through this system but payloads that are
// this big are probably being handled improperly.
UNITY_DECLARE_INTERFACE(IUnityEventQueue)
{
public:
// size of 8196 required for PS4 system events
#define kMaxEventQueueEventSize 8196+sizeof(EventId)
virtual ~IUnityEventQueue() {
}
// The primary entry point for firing any
// event through the system. The templated
// version is simply syntatic sugar for extracting
// the EventId from the event object.
//
// This can be called from any thread.
template<typename T>
void SendEvent(T & payload)
{
// Ensure we never fire an event that we can't handle size wise.
Assert(sizeof(T) <= (kMaxEventQueueEventSize - sizeof(EventId)));
// NOTE: Keep this small to avoid code bloat.
// every line of code in here should be scrutinized
// as this and GetEventId could easily be sources
// of bloat if allowed to grow.
SendEventImpl(UnityEventQueue::GetEventId<T>(), (unsigned char*)(&payload), sizeof(T));
}
#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
// Some events want to have a destructor.
//
// You do this by creating a public Destroy()
// method on your Event payload. You then
// register the event with REGISTER_EVENT_ID_WITH_CLEANUP
//
// If your event will have someone listening to it right away
// then you do not need to do anything else.
//
// However, if there is a danger that your event will be fired
// before someone starts listening for it then you must
// call this method somewhere. This will manually register your
// class for cleanup. There is no harm in calling this even
// if it is not required. If in doubt and your event payload
// requires some form of destruction, call this method!
template<typename T>
void RegisterCleanup(T & payload)
{
EventHandler * eh = UnityEventQueue::GetEventDestructor<T>();
if (eh != NULL)
SetCleanupImpl(eh);
}
#endif
// These are not thread safe and must be done on the same thread
// as the dispatch thread. Doing otherwise risks race conditions.
// Fire the add handler / remove handler event if you need to
// schedule this from a different thread.
virtual void AddHandler(EventHandler * handler) = 0;
virtual void RemoveHandler(EventHandler * handler) = 0;
protected:
virtual void SendEventImpl(EventId id, unsigned char * data, int size) = 0;
#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
// This is an event destructor. You can register one of these
// per event type. This allows events to manage resource if
// they absolutely must. In general you should avoid handling
// resources in events as events usually imply cross thread activity.
virtual void SetCleanupImpl(EventHandler * handler) = 0;
#endif
};
}
REGISTER_EVENT_ID(0x19D736400584B24BULL, 0x98B9EFBE26D3F3C9ULL, AddEventHandler)
REGISTER_EVENT_ID(0x8D4A317C4F577F4AULL, 0x851D6E457566A905ULL, RemoveEventHandler)
UNITY_REGISTER_INTERFACE_GUID_IN_NAMESPACE(0x9959C347F5AE374DULL, 0x9BADE6FC8EF49E7FULL, IUnityEventQueue, UnityEventQueue)

57
engine/third_party/Unity/IUnityGraphics.h


// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an AS IS BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityInterface.h"
typedef enum UnityGfxRenderer
{
//kUnityGfxRendererOpenGL = 0, // Legacy OpenGL, removed
//kUnityGfxRendererD3D9 = 1, // Direct3D 9, removed
kUnityGfxRendererD3D11 = 2, // Direct3D 11
kUnityGfxRendererNull = 4, // "null" device (used in batch mode)
kUnityGfxRendererOpenGLES20 = 8, // OpenGL ES 2.0
kUnityGfxRendererOpenGLES30 = 11, // OpenGL ES 3.0
//kUnityGfxRendererGXM = 12, // PlayStation Vita, removed
kUnityGfxRendererPS4 = 13, // PlayStation 4
kUnityGfxRendererXboxOne = 14, // Xbox One
kUnityGfxRendererMetal = 16, // iOS Metal
kUnityGfxRendererOpenGLCore = 17, // OpenGL core
kUnityGfxRendererD3D12 = 18, // Direct3D 12
kUnityGfxRendererVulkan = 21, // Vulkan
kUnityGfxRendererNvn = 22, // Nintendo Switch NVN API
kUnityGfxRendererXboxOneD3D12 = 23 // MS XboxOne Direct3D 12
} UnityGfxRenderer;
typedef enum UnityGfxDeviceEventType
{
kUnityGfxDeviceEventInitialize = 0,
kUnityGfxDeviceEventShutdown = 1,
kUnityGfxDeviceEventBeforeReset = 2,
kUnityGfxDeviceEventAfterReset = 3,
} UnityGfxDeviceEventType;
typedef void (UNITY_INTERFACE_API * IUnityGraphicsDeviceEventCallback)(UnityGfxDeviceEventType eventType);
// Should only be used on the rendering thread unless noted otherwise.
UNITY_DECLARE_INTERFACE(IUnityGraphics)
{
UnityGfxRenderer(UNITY_INTERFACE_API * GetRenderer)(); // Thread safe
// This callback will be called when graphics device is created, destroyed, reset, etc.
// It is possible to miss the kUnityGfxDeviceEventInitialize event in case plugin is loaded at a later time,
// when the graphics device is already created.
void(UNITY_INTERFACE_API * RegisterDeviceEventCallback)(IUnityGraphicsDeviceEventCallback callback);
void(UNITY_INTERFACE_API * UnregisterDeviceEventCallback)(IUnityGraphicsDeviceEventCallback callback);
int(UNITY_INTERFACE_API * ReserveEventIDRange)(int count); // reserves 'count' event IDs. Plugins should use the result as a base index when issuing events back and forth to avoid event id clashes.
};
UNITY_REGISTER_INTERFACE_GUID(0x7CBA0A9CA4DDB544ULL, 0x8C5AD4926EB17B11ULL, IUnityGraphics)
// Certain Unity APIs (GL.IssuePluginEvent, CommandBuffer.IssuePluginEvent) can callback into native plugins.
// Provide them with an address to a function of this signature.
typedef void (UNITY_INTERFACE_API * UnityRenderingEvent)(int eventId);
typedef void (UNITY_INTERFACE_API * UnityRenderingEventAndData)(int eventId, void* data);

23
engine/third_party/Unity/IUnityGraphicsD3D11.h


// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an AS IS BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityInterface.h"
// Should only be used on the rendering thread unless noted otherwise.
UNITY_DECLARE_INTERFACE(IUnityGraphicsD3D11)
{
ID3D11Device* (UNITY_INTERFACE_API * GetDevice)();
ID3D11Resource* (UNITY_INTERFACE_API * TextureFromRenderBuffer)(UnityRenderBuffer buffer);
ID3D11Resource* (UNITY_INTERFACE_API * TextureFromNativeTexture)(UnityTextureID texture);
ID3D11RenderTargetView* (UNITY_INTERFACE_API * RTVFromRenderBuffer)(UnityRenderBuffer surface);
ID3D11ShaderResourceView* (UNITY_INTERFACE_API * SRVFromNativeTexture)(UnityTextureID texture);
};
UNITY_REGISTER_INTERFACE_GUID(0xAAB37EF87A87D748ULL, 0xBF76967F07EFB177ULL, IUnityGraphicsD3D11)

183
engine/third_party/Unity/IUnityGraphicsD3D12.h


// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an AS IS BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityInterface.h"
#ifndef __cplusplus
#include <stdbool.h>
#endif
struct RenderSurfaceBase;
typedef struct RenderSurfaceBase* UnityRenderBuffer;
typedef struct UnityGraphicsD3D12ResourceState UnityGraphicsD3D12ResourceState;
struct UnityGraphicsD3D12ResourceState
{
ID3D12Resource* resource; // Resource to barrier.
D3D12_RESOURCE_STATES expected; // Expected resource state before this command list is executed.
D3D12_RESOURCE_STATES current; // State this resource will be in after this command list is executed.
};
struct UnityGraphicsD3D12RecordingState
{
ID3D12GraphicsCommandList* commandList; // D3D12 command list that is currently recorded by Unity
};
enum UnityD3D12GraphicsQueueAccess
{
// No queue acccess, no work must be submitted to UnityD3D12Instance::graphicsQueue from the plugin event callback
kUnityD3D12GraphicsQueueAccess_DontCare,
// Make sure that Unity worker threads don't access the D3D12 graphics queue
// This disables access to the current Unity command buffer
kUnityD3D12GraphicsQueueAccess_Allow,
};
enum UnityD3D12EventConfigFlagBits
{
kUnityD3D12EventConfigFlag_EnsurePreviousFrameSubmission = (1 << 0), // default: (NOT SUPPORTED)
kUnityD3D12EventConfigFlag_FlushCommandBuffers = (1 << 1), // submit existing command buffers, default: not set
kUnityD3D12EventConfigFlag_SyncWorkerThreads = (1 << 2), // wait for worker threads to finish, default: not set
kUnityD3D12EventConfigFlag_ModifiesCommandBuffersState = (1 << 3), // should be set when descriptor set bindings, vertex buffer bindings, etc are changed (default: set)
};
struct UnityD3D12PluginEventConfig
{
UnityD3D12GraphicsQueueAccess graphicsQueueAccess;
UINT32 flags; // UnityD3D12EventConfigFlagBits to be used when invoking a native plugin
bool ensureActiveRenderTextureIsBound; // If true, the actively bound render texture will be bound prior the execution of the native plugin method.
};
typedef struct UnityGraphicsD3D12PhysicalVideoMemoryControlValues UnityGraphicsD3D12PhysicalVideoMemoryControlValues;
struct UnityGraphicsD3D12PhysicalVideoMemoryControlValues // all values in bytes
{
UINT64 reservation; // Minimum required physical memory for an application [default = 64MB].
UINT64 systemMemoryThreshold; // If free physical video memory drops below this threshold, resources will be allocated in system memory. [default = 64MB]
UINT64 residencyThreshold; // Minimum free physical video memory needed to start bringing evicted resources back after shrunken video memory budget expands again. [default = 128MB]
};
// Should only be used on the rendering/submission thread.
UNITY_DECLARE_INTERFACE(IUnityGraphicsD3D12v6)
{
ID3D12Device* (UNITY_INTERFACE_API * GetDevice)();
ID3D12Fence* (UNITY_INTERFACE_API * GetFrameFence)();
// Returns the value set on the frame fence once the current frame completes or the GPU is flushed
UINT64(UNITY_INTERFACE_API * GetNextFrameFenceValue)();
// Executes a given command list on a worker thread.
// [Optional] Declares expected and post-execution resource states.
// Returns the fence value.
UINT64(UNITY_INTERFACE_API * ExecuteCommandList)(ID3D12GraphicsCommandList * commandList, int stateCount, UnityGraphicsD3D12ResourceState * states);
void(UNITY_INTERFACE_API * SetPhysicalVideoMemoryControlValues)(const UnityGraphicsD3D12PhysicalVideoMemoryControlValues * memInfo);
ID3D12CommandQueue* (UNITY_INTERFACE_API * GetCommandQueue)();
ID3D12Resource* (UNITY_INTERFACE_API * TextureFromRenderBuffer)(UnityRenderBuffer * rb);
ID3D12Resource* (UNITY_INTERFACE_API * TextureFromNativeTexture)(UnityTextureID texture);
// Change the precondition for a specific user-defined event
// Should be called during initialization
void(UNITY_INTERFACE_API * ConfigureEvent)(int eventID, const UnityD3D12PluginEventConfig * pluginEventConfig);
bool(UNITY_INTERFACE_API * CommandRecordingState)(UnityGraphicsD3D12RecordingState* outCommandRecordingState);
};
UNITY_REGISTER_INTERFACE_GUID(0xA396DCE58CAC4D78ULL, 0xAFDD9B281F20B840ULL, IUnityGraphicsD3D12v6)
// Should only be used on the rendering/submission thread.
UNITY_DECLARE_INTERFACE(IUnityGraphicsD3D12v5)
{
ID3D12Device* (UNITY_INTERFACE_API * GetDevice)();
ID3D12Fence* (UNITY_INTERFACE_API * GetFrameFence)();
// Returns the value set on the frame fence once the current frame completes or the GPU is flushed
UINT64(UNITY_INTERFACE_API * GetNextFrameFenceValue)();
// Executes a given command list on a worker thread.
// [Optional] Declares expected and post-execution resource states.
// Returns the fence value.
UINT64(UNITY_INTERFACE_API * ExecuteCommandList)(ID3D12GraphicsCommandList * commandList, int stateCount, UnityGraphicsD3D12ResourceState * states);
void(UNITY_INTERFACE_API * SetPhysicalVideoMemoryControlValues)(const UnityGraphicsD3D12PhysicalVideoMemoryControlValues * memInfo);
ID3D12CommandQueue* (UNITY_INTERFACE_API * GetCommandQueue)();
ID3D12Resource* (UNITY_INTERFACE_API * TextureFromRenderBuffer)(UnityRenderBuffer * rb);
};
UNITY_REGISTER_INTERFACE_GUID(0xF5C8D8A37D37BC42ULL, 0xB02DFE93B5064A27ULL, IUnityGraphicsD3D12v5)
// Should only be used on the rendering/submission thread.
UNITY_DECLARE_INTERFACE(IUnityGraphicsD3D12v4)
{
ID3D12Device* (UNITY_INTERFACE_API * GetDevice)();
ID3D12Fence* (UNITY_INTERFACE_API * GetFrameFence)();
// Returns the value set on the frame fence once the current frame completes or the GPU is flushed
UINT64(UNITY_INTERFACE_API * GetNextFrameFenceValue)();
// Executes a given command list on a worker thread.
// [Optional] Declares expected and post-execution resource states.
// Returns the fence value.
UINT64(UNITY_INTERFACE_API * ExecuteCommandList)(ID3D12GraphicsCommandList * commandList, int stateCount, UnityGraphicsD3D12ResourceState * states);
void(UNITY_INTERFACE_API * SetPhysicalVideoMemoryControlValues)(const UnityGraphicsD3D12PhysicalVideoMemoryControlValues * memInfo);
ID3D12CommandQueue* (UNITY_INTERFACE_API * GetCommandQueue)();
};
UNITY_REGISTER_INTERFACE_GUID(0X498FFCC13EC94006ULL, 0XB18F8B0FF67778C8ULL, IUnityGraphicsD3D12v4)
// Should only be used on the rendering/submission thread.
UNITY_DECLARE_INTERFACE(IUnityGraphicsD3D12v3)
{
ID3D12Device* (UNITY_INTERFACE_API * GetDevice)();
ID3D12Fence* (UNITY_INTERFACE_API * GetFrameFence)();
// Returns the value set on the frame fence once the current frame completes or the GPU is flushed
UINT64(UNITY_INTERFACE_API * GetNextFrameFenceValue)();
// Executes a given command list on a worker thread.
// [Optional] Declares expected and post-execution resource states.
// Returns the fence value.
UINT64(UNITY_INTERFACE_API * ExecuteCommandList)(ID3D12GraphicsCommandList * commandList, int stateCount, UnityGraphicsD3D12ResourceState * states);
void(UNITY_INTERFACE_API * SetPhysicalVideoMemoryControlValues)(const UnityGraphicsD3D12PhysicalVideoMemoryControlValues * memInfo);
};
UNITY_REGISTER_INTERFACE_GUID(0x57C3FAFE59E5E843ULL, 0xBF4F5998474BB600ULL, IUnityGraphicsD3D12v3)
// Should only be used on the rendering/submission thread.
UNITY_DECLARE_INTERFACE(IUnityGraphicsD3D12v2)
{
ID3D12Device* (UNITY_INTERFACE_API * GetDevice)();
ID3D12Fence* (UNITY_INTERFACE_API * GetFrameFence)();
// Returns the value set on the frame fence once the current frame completes or the GPU is flushed
UINT64(UNITY_INTERFACE_API * GetNextFrameFenceValue)();
// Executes a given command list on a worker thread.
// [Optional] Declares expected and post-execution resource states.
// Returns the fence value.
UINT64(UNITY_INTERFACE_API * ExecuteCommandList)(ID3D12GraphicsCommandList * commandList, int stateCount, UnityGraphicsD3D12ResourceState * states);
};
UNITY_REGISTER_INTERFACE_GUID(0xEC39D2F18446C745ULL, 0xB1A2626641D6B11FULL, IUnityGraphicsD3D12v2)
// Obsolete
UNITY_DECLARE_INTERFACE(IUnityGraphicsD3D12)
{
ID3D12Device* (UNITY_INTERFACE_API * GetDevice)();
ID3D12CommandQueue* (UNITY_INTERFACE_API * GetCommandQueue)();
ID3D12Fence* (UNITY_INTERFACE_API * GetFrameFence)();
// Returns the value set on the frame fence once the current frame completes or the GPU is flushed
UINT64(UNITY_INTERFACE_API * GetNextFrameFenceValue)();
// Returns the state a resource will be in after the last command list is executed
bool(UNITY_INTERFACE_API * GetResourceState)(ID3D12Resource * resource, D3D12_RESOURCE_STATES * outState);
// Specifies the state a resource will be in after a plugin command list with resource barriers is executed
void(UNITY_INTERFACE_API * SetResourceState)(ID3D12Resource * resource, D3D12_RESOURCE_STATES state);
};
UNITY_REGISTER_INTERFACE_GUID(0xEF4CEC88A45F4C4CULL, 0xBD295B6F2A38D9DEULL, IUnityGraphicsD3D12)

74
engine/third_party/Unity/IUnityGraphicsMetal.h


// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an AS IS BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityInterface.h"
#ifndef __OBJC__
#error metal plugin is objc code.
#endif
#ifndef __clang__
#error only clang compiler is supported.
#endif
@class NSBundle;
@protocol MTLDevice;
@protocol MTLCommandBuffer;
@protocol MTLCommandEncoder;
@protocol MTLTexture;
@class MTLRenderPassDescriptor;
UNITY_DECLARE_INTERFACE(IUnityGraphicsMetalV1)
{
NSBundle* (UNITY_INTERFACE_API * MetalBundle)();
id<MTLDevice>(UNITY_INTERFACE_API * MetalDevice)();
id<MTLCommandBuffer>(UNITY_INTERFACE_API * CurrentCommandBuffer)();
// for custom rendering support there are two scenarios:
// you want to use current in-flight MTLCommandEncoder (NB: it might be nil)
id<MTLCommandEncoder>(UNITY_INTERFACE_API * CurrentCommandEncoder)();
// or you might want to create your own encoder.
// In that case you should end unity's encoder before creating your own and end yours before returning control to unity
void(UNITY_INTERFACE_API * EndCurrentCommandEncoder)();
// returns MTLRenderPassDescriptor used to create current MTLCommandEncoder
MTLRenderPassDescriptor* (UNITY_INTERFACE_API * CurrentRenderPassDescriptor)();
// converting trampoline UnityRenderBufferHandle into native RenderBuffer
UnityRenderBuffer(UNITY_INTERFACE_API * RenderBufferFromHandle)(void* bufferHandle);
// access to RenderBuffer's texure
// NB: you pass here *native* RenderBuffer, acquired by calling (C#) RenderBuffer.GetNativeRenderBufferPtr
// AAResolvedTextureFromRenderBuffer will return nil in case of non-AA RenderBuffer or if called for depth RenderBuffer
// StencilTextureFromRenderBuffer will return nil in case of no-stencil RenderBuffer or if called for color RenderBuffer
id<MTLTexture>(UNITY_INTERFACE_API * TextureFromRenderBuffer)(UnityRenderBuffer buffer);
id<MTLTexture>(UNITY_INTERFACE_API * AAResolvedTextureFromRenderBuffer)(UnityRenderBuffer buffer);
id<MTLTexture>(UNITY_INTERFACE_API * StencilTextureFromRenderBuffer)(UnityRenderBuffer buffer);
};
UNITY_REGISTER_INTERFACE_GUID(0x29F8F3D03833465EULL, 0x92138551C15D823DULL, IUnityGraphicsMetalV1)
// deprecated: please use versioned interface above
UNITY_DECLARE_INTERFACE(IUnityGraphicsMetal)
{
NSBundle* (UNITY_INTERFACE_API * MetalBundle)();
id<MTLDevice>(UNITY_INTERFACE_API * MetalDevice)();
id<MTLCommandBuffer>(UNITY_INTERFACE_API * CurrentCommandBuffer)();
id<MTLCommandEncoder>(UNITY_INTERFACE_API * CurrentCommandEncoder)();
void(UNITY_INTERFACE_API * EndCurrentCommandEncoder)();
MTLRenderPassDescriptor* (UNITY_INTERFACE_API * CurrentRenderPassDescriptor)();
UnityRenderBuffer(UNITY_INTERFACE_API * RenderBufferFromHandle)(void* bufferHandle);
id<MTLTexture>(UNITY_INTERFACE_API * TextureFromRenderBuffer)(UnityRenderBuffer buffer);
id<MTLTexture>(UNITY_INTERFACE_API * AAResolvedTextureFromRenderBuffer)(UnityRenderBuffer buffer);
id<MTLTexture>(UNITY_INTERFACE_API * StencilTextureFromRenderBuffer)(UnityRenderBuffer buffer);
};
UNITY_REGISTER_INTERFACE_GUID(0x992C8EAEA95811E5ULL, 0x9A62C4B5B9876117ULL, IUnityGraphicsMetal)

237
engine/third_party/Unity/IUnityGraphicsVulkan.h


// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an AS IS BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityInterface.h"
#ifndef UNITY_VULKAN_HEADER
#define UNITY_VULKAN_HEADER <vulkan/vulkan.h>
#endif
#include UNITY_VULKAN_HEADER
struct UnityVulkanInstance
{
VkPipelineCache pipelineCache; // Unity's pipeline cache is serialized to disk
VkInstance instance;
VkPhysicalDevice physicalDevice;
VkDevice device;
VkQueue graphicsQueue;
PFN_vkGetInstanceProcAddr getInstanceProcAddr; // vkGetInstanceProcAddr of the Vulkan loader, same as the one passed to UnityVulkanInitCallback
unsigned int queueFamilyIndex;
void* reserved[8];
};
struct UnityVulkanMemory
{
VkDeviceMemory memory; // Vulkan memory handle
VkDeviceSize offset; // offset within memory
VkDeviceSize size; // size in bytes, may be less than the total size of memory;
void* mapped; // pointer to mapped memory block, NULL if not mappable, offset is already applied, remaining block still has at least the given size.
VkMemoryPropertyFlags flags; // Vulkan memory properties
unsigned int memoryTypeIndex; // index into VkPhysicalDeviceMemoryProperties::memoryTypes
void* reserved[4];
};
enum UnityVulkanResourceAccessMode
{
// Does not imply any pipeline barriers, should only be used to query resource attributes
kUnityVulkanResourceAccess_ObserveOnly,
// Handles layout transition and barriers
kUnityVulkanResourceAccess_PipelineBarrier,
// Recreates the backing resource (VkBuffer/VkImage) but keeps the previous one alive if it's in use
kUnityVulkanResourceAccess_Recreate,
};
struct UnityVulkanImage
{
UnityVulkanMemory memory; // memory that backs the image
VkImage image; // Vulkan image handle
VkImageLayout layout; // current layout, may change resource access
VkImageAspectFlags aspect;
VkImageUsageFlags usage;
VkFormat format;
VkExtent3D extent;
VkImageTiling tiling;
VkImageType type;
VkSampleCountFlagBits samples;
int layers;
int mipCount;
void* reserved[4];
};
struct UnityVulkanBuffer
{
UnityVulkanMemory memory; // memory that backs the buffer
VkBuffer buffer; // Vulkan buffer handle
size_t sizeInBytes; // size of the buffer in bytes, may be less than memory size
VkBufferUsageFlags usage;
void* reserved[4];
};
struct UnityVulkanRecordingState
{
VkCommandBuffer commandBuffer; // Vulkan command buffer that is currently recorded by Unity
VkCommandBufferLevel commandBufferLevel;
VkRenderPass renderPass; // Current render pass, a compatible one or VK_NULL_HANDLE
VkFramebuffer framebuffer; // Current framebuffer or VK_NULL_HANDLE
int subPassIndex; // index of the current sub pass, -1 if not inside a render pass
// Resource life-time tracking counters, only relevant for resources allocated by the plugin
unsigned long long currentFrameNumber; // can be used to track lifetime of own resources
unsigned long long safeFrameNumber; // all resources that were used in this frame (or before) are safe to be released
void* reserved[4];
};
enum UnityVulkanEventRenderPassPreCondition
{
// Don't care about the state on Unity's current command buffer
// This is the default precondition
kUnityVulkanRenderPass_DontCare,
// Make sure that there is currently no RenderPass in progress.
// This allows e.g. resource uploads.
// There are no guarantees about the currently bound descriptor sets, vertex buffers, index buffers and pipeline objects
// Unity does however set dynamic pipeline set VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR based on the current settings
// If used in combination with the SRP RenderPass API the resuls is undefined
kUnityVulkanRenderPass_EnsureInside,
// Make sure that there is currently no RenderPass in progress.
// Ends the current render pass (and resumes it afterwards if needed)
// If used in combination with the SRP RenderPass API the resuls is undefined.
kUnityVulkanRenderPass_EnsureOutside
};
enum UnityVulkanGraphicsQueueAccess
{
// No queue acccess, no work must be submitted to UnityVulkanInstance::graphicsQueue from the plugin event callback
kUnityVulkanGraphicsQueueAccess_DontCare,
// Make sure that Unity worker threads don't access the Vulkan graphics queue
// This disables access to the current Unity command buffer
kUnityVulkanGraphicsQueueAccess_Allow,
};
enum UnityVulkanEventConfigFlagBits
{
kUnityVulkanEventConfigFlag_EnsurePreviousFrameSubmission = (1 << 0), // default: set
kUnityVulkanEventConfigFlag_FlushCommandBuffers = (1 << 1), // submit existing command buffers, default: not set
kUnityVulkanEventConfigFlag_SyncWorkerThreads = (1 << 2), // wait for worker threads to finish, default: not set
kUnityVulkanEventConfigFlag_ModifiesCommandBuffersState = (1 << 3), // should be set when descriptor set bindings, vertex buffer bindings, etc are changed (default: set)
};
struct UnityVulkanPluginEventConfig
{
UnityVulkanEventRenderPassPreCondition renderPassPrecondition;
UnityVulkanGraphicsQueueAccess graphicsQueueAccess;
uint32_t flags;
};
// Constant that can be used to reference the whole image
const VkImageSubresource* const UnityVulkanWholeImage = NULL;
// callback function, see InterceptInitialization
typedef PFN_vkGetInstanceProcAddr(UNITY_INTERFACE_API * UnityVulkanInitCallback)(PFN_vkGetInstanceProcAddr getInstanceProcAddr, void* userdata);
enum UnityVulkanSwapchainMode
{
kUnityVulkanSwapchainMode_Default,
kUnityVulkanSwapchainMode_Offscreen
};
struct UnityVulkanSwapchainConfiguration
{
UnityVulkanSwapchainMode mode;
};
UNITY_DECLARE_INTERFACE(IUnityGraphicsVulkan)
{
// Vulkan API hooks
//
// Must be called before kUnityGfxDeviceEventInitialize (preload plugin)
// Unity will call 'func' when initializing the Vulkan API
// The 'getInstanceProcAddr' passed to the callback is the function pointer from the Vulkan Loader
// The function pointer returned from UnityVulkanInitCallback may be a different implementation
// This allows intercepting all Vulkan API calls
//
// Most rules/restrictions for implementing a Vulkan layer apply
// Returns true on success, false on failure (typically because it is used too late)
bool(UNITY_INTERFACE_API * InterceptInitialization)(UnityVulkanInitCallback func, void* userdata);
// Intercept Vulkan API function of the given name with the given function
// In contrast to InterceptInitialization this interface can be used at any time
// The user must handle all synchronization
// Generally this cannot be used to wrap Vulkan object because there might because there may already be non-wrapped instances
// returns the previous function pointer
PFN_vkVoidFunction(UNITY_INTERFACE_API * InterceptVulkanAPI)(const char* name, PFN_vkVoidFunction func);
// Change the precondition for a specific user-defined event
// Should be called during initialization
void(UNITY_INTERFACE_API * ConfigureEvent)(int eventID, const UnityVulkanPluginEventConfig * pluginEventConfig);
// Access the Vulkan instance and render queue created by Unity
// UnityVulkanInstance does not change between kUnityGfxDeviceEventInitialize and kUnityGfxDeviceEventShutdown
UnityVulkanInstance(UNITY_INTERFACE_API * Instance)();
// Access the current command buffer
//
// outCommandRecordingState is invalidated by any resource access calls.
// queueAccess must be kUnityVulkanGraphicsQueueAccess_Allow when called from from a AccessQueue callback or from a event that is configured for queue access.
// Otherwise queueAccess must be kUnityVulkanGraphicsQueueAccess_DontCare.
bool(UNITY_INTERFACE_API * CommandRecordingState)(UnityVulkanRecordingState * outCommandRecordingState, UnityVulkanGraphicsQueueAccess queueAccess);
// Resource access
//
// Using the following resource query APIs will mark the resources as used for the current frame.
// Pipeline barriers will be inserted when needed.
//
// Resource access APIs may record commands, so the current UnityVulkanRecordingState is invalidated
// Must not be called from event callbacks configured for queue access (UnityVulkanGraphicsQueueAccess_Allow)
// or from a AccessQueue callback of an event
bool(UNITY_INTERFACE_API * AccessTexture)(void* nativeTexture, const VkImageSubresource * subResource, VkImageLayout layout,
VkPipelineStageFlags pipelineStageFlags, VkAccessFlags accessFlags, UnityVulkanResourceAccessMode accessMode, UnityVulkanImage * outImage);
bool(UNITY_INTERFACE_API * AccessRenderBufferTexture)(UnityRenderBuffer nativeRenderBuffer, const VkImageSubresource * subResource, VkImageLayout layout,
VkPipelineStageFlags pipelineStageFlags, VkAccessFlags accessFlags, UnityVulkanResourceAccessMode accessMode, UnityVulkanImage * outImage);
bool(UNITY_INTERFACE_API * AccessRenderBufferResolveTexture)(UnityRenderBuffer nativeRenderBuffer, const VkImageSubresource * subResource, VkImageLayout layout,
VkPipelineStageFlags pipelineStageFlags, VkAccessFlags accessFlags, UnityVulkanResourceAccessMode accessMode, UnityVulkanImage * outImage);
bool(UNITY_INTERFACE_API * AccessBuffer)(void* nativeBuffer, VkPipelineStageFlags pipelineStageFlags, VkAccessFlags accessFlags, UnityVulkanResourceAccessMode accessMode, UnityVulkanBuffer * outBuffer);
// Control current state of render pass
//
// Must not be called from event callbacks configured for queue access (UnityVulkanGraphicsQueueAccess_Allow, UnityVulkanGraphicsQueueAccess_FlushAndAllow)
// or from a AccessQueue callback of an event
// See kUnityVulkanRenderPass_EnsureInside, kUnityVulkanRenderPass_EnsureOutside
void(UNITY_INTERFACE_API * EnsureOutsideRenderPass)();
void(UNITY_INTERFACE_API * EnsureInsideRenderPass)();
// Allow command buffer submission to the the Vulkan graphics queue from the given UnityRenderingEventAndData callback.
// This is an alternative to using ConfigureEvent with kUnityVulkanGraphicsQueueAccess_Allow.
//
// eventId and userdata are passed to the callback
// This may or may not be called synchronously or from the submission thread.
// If flush is true then all Unity command buffers of this frame are submitted before UnityQueueAccessCallback
void(UNITY_INTERFACE_API * AccessQueue)(UnityRenderingEventAndData, int eventId, void* userData, bool flush);
// Configure swapchains that are created by Unity.
// Must be called before kUnityGfxDeviceEventInitialize (preload plugin)
bool(UNITY_INTERFACE_API * ConfigureSwapchain)(const UnityVulkanSwapchainConfiguration * swapChainConfig);
// see AccessTexture
// Accepts UnityTextureID (UnityRenderingExtTextureUpdateParamsV2::textureID, UnityRenderingExtCustomBlitParams::source)
bool(UNITY_INTERFACE_API * AccessTextureByID)(UnityTextureID textureID, const VkImageSubresource * subResource, VkImageLayout layout,
VkPipelineStageFlags pipelineStageFlags, VkAccessFlags accessFlags, UnityVulkanResourceAccessMode accessMode, UnityVulkanImage * outImage);
};
UNITY_REGISTER_INTERFACE_GUID(0x95355348d4ef4e11ULL, 0x9789313dfcffcc87ULL, IUnityGraphicsVulkan)

206
engine/third_party/Unity/IUnityInterface.h


// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an AS IS BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
// Unity native plugin API
// Compatible with C99
#if defined(__CYGWIN32__)
#define UNITY_INTERFACE_API __stdcall
#define UNITY_INTERFACE_EXPORT __declspec(dllexport)
#elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(WINAPI_FAMILY)
#define UNITY_INTERFACE_API __stdcall
#define UNITY_INTERFACE_EXPORT __declspec(dllexport)
#elif defined(__MACH__) || defined(__ANDROID__) || defined(__linux__) || defined(LUMIN)
#define UNITY_INTERFACE_API
#define UNITY_INTERFACE_EXPORT __attribute__ ((visibility ("default")))
#else
#define UNITY_INTERFACE_API
#define UNITY_INTERFACE_EXPORT
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// IUnityInterface is a registry of interfaces we choose to expose to plugins.
//
// USAGE:
// ---------
// To retrieve an interface a user can do the following from a plugin, assuming they have the header file for the interface:
//
// IMyInterface * ptr = registry->Get<IMyInterface>();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Unity Interface GUID
// Ensures global uniqueness.
//
// Template specialization is used to produce a means of looking up a GUID from its interface type at compile time.
// The net result should compile down to passing around the GUID.
//
// UNITY_REGISTER_INTERFACE_GUID should be placed in the header file of any interface definition outside of all namespaces.
// The interface structure and the registration GUID are all that is required to expose the interface to other systems.
struct UnityInterfaceGUID
{
#ifdef __cplusplus
UnityInterfaceGUID(unsigned long long high, unsigned long long low)
: m_GUIDHigh(high)
, m_GUIDLow(low)
{
}
UnityInterfaceGUID(const UnityInterfaceGUID& other)
{
m_GUIDHigh = other.m_GUIDHigh;
m_GUIDLow = other.m_GUIDLow;
}
UnityInterfaceGUID& operator=(const UnityInterfaceGUID& other)
{
m_GUIDHigh = other.m_GUIDHigh;
m_GUIDLow = other.m_GUIDLow;
return *this;
}
bool Equals(const UnityInterfaceGUID& other) const { return m_GUIDHigh == other.m_GUIDHigh && m_GUIDLow == other.m_GUIDLow; }
bool LessThan(const UnityInterfaceGUID& other) const { return m_GUIDHigh < other.m_GUIDHigh || (m_GUIDHigh == other.m_GUIDHigh && m_GUIDLow < other.m_GUIDLow); }
#endif
unsigned long long m_GUIDHigh;
unsigned long long m_GUIDLow;
};
#ifdef __cplusplus
inline bool operator==(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return left.Equals(right); }
inline bool operator!=(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return !left.Equals(right); }
inline bool operator<(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return left.LessThan(right); }
inline bool operator>(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return right.LessThan(left); }
inline bool operator>=(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return !operator<(left, right); }
inline bool operator<=(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return !operator>(left, right); }
#else
typedef struct UnityInterfaceGUID UnityInterfaceGUID;
#endif
#ifdef __cplusplus
#define UNITY_DECLARE_INTERFACE(NAME) \
struct NAME : IUnityInterface
// Generic version of GetUnityInterfaceGUID to allow us to specialize it
// per interface below. The generic version has no actual implementation
// on purpose.
//
// If you get errors about return values related to this method then
// you have forgotten to include UNITY_REGISTER_INTERFACE_GUID with
// your interface, or it is not visible at some point when you are
// trying to retrieve or add an interface.
template<typename TYPE>
inline const UnityInterfaceGUID GetUnityInterfaceGUID();
// This is the macro you provide in your public interface header
// outside of a namespace to allow us to map between type and GUID
// without the user having to worry about it when attempting to
// add or retrieve and interface from the registry.
#define UNITY_REGISTER_INTERFACE_GUID(HASHH, HASHL, TYPE) \
template<> \
inline const UnityInterfaceGUID GetUnityInterfaceGUID<TYPE>() \
{ \
return UnityInterfaceGUID(HASHH,HASHL); \
}
// Same as UNITY_REGISTER_INTERFACE_GUID but allows the interface to live in
// a particular namespace. As long as the namespace is visible at the time you call
// GetUnityInterfaceGUID< INTERFACETYPE >() or you explicitly qualify it in the template
// calls this will work fine, only the macro here needs to have the additional parameter
#define UNITY_REGISTER_INTERFACE_GUID_IN_NAMESPACE(HASHH, HASHL, TYPE, NAMESPACE) \
const UnityInterfaceGUID TYPE##_GUID(HASHH, HASHL); \
template<> \
inline const UnityInterfaceGUID GetUnityInterfaceGUID< NAMESPACE :: TYPE >() \
{ \
return UnityInterfaceGUID(HASHH,HASHL); \
}
// These macros allow for C compatibility in user code.
#define UNITY_GET_INTERFACE_GUID(TYPE) GetUnityInterfaceGUID< TYPE >()
#else
#define UNITY_DECLARE_INTERFACE(NAME) \
typedef struct NAME NAME; \
struct NAME
// NOTE: This has the downside that one some compilers it will not get stripped from all compilation units that
// can see a header containing this constant. However, it's only for C compatibility and thus should have
// minimal impact.
#define UNITY_REGISTER_INTERFACE_GUID(HASHH, HASHL, TYPE) \
const UnityInterfaceGUID TYPE##_GUID = {HASHH, HASHL};
// In general namespaces are going to be a problem for C code any interfaces we expose in a namespace are
// not going to be usable from C.
#define UNITY_REGISTER_INTERFACE_GUID_IN_NAMESPACE(HASHH, HASHL, TYPE, NAMESPACE)
// These macros allow for C compatibility in user code.
#define UNITY_GET_INTERFACE_GUID(TYPE) TYPE##_GUID
#endif
// Using this in user code rather than INTERFACES->Get<TYPE>() will be C compatible for those places in plugins where
// this may be needed. Unity code itself does not need this.
#define UNITY_GET_INTERFACE(INTERFACES, TYPE) (TYPE*)INTERFACES->GetInterfaceSplit (UNITY_GET_INTERFACE_GUID(TYPE).m_GUIDHigh, UNITY_GET_INTERFACE_GUID(TYPE).m_GUIDLow);
#ifdef __cplusplus
struct IUnityInterface
{
};
#else
typedef void IUnityInterface;
#endif
typedef struct IUnityInterfaces
{
// Returns an interface matching the guid.
// Returns nullptr if the given interface is unavailable in the active Unity runtime.
IUnityInterface* (UNITY_INTERFACE_API * GetInterface)(UnityInterfaceGUID guid);
// Registers a new interface.
void(UNITY_INTERFACE_API * RegisterInterface)(UnityInterfaceGUID guid, IUnityInterface * ptr);
// Split APIs for C
IUnityInterface* (UNITY_INTERFACE_API * GetInterfaceSplit)(unsigned long long guidHigh, unsigned long long guidLow);
void(UNITY_INTERFACE_API * RegisterInterfaceSplit)(unsigned long long guidHigh, unsigned long long guidLow, IUnityInterface * ptr);
#ifdef __cplusplus
// Helper for GetInterface.
template<typename INTERFACE>
INTERFACE* Get()
{
return static_cast<INTERFACE*>(GetInterface(GetUnityInterfaceGUID<INTERFACE>()));
}
// Helper for RegisterInterface.
template<typename INTERFACE>
void Register(IUnityInterface* ptr)
{
RegisterInterface(GetUnityInterfaceGUID<INTERFACE>(), ptr);
}
#endif
} IUnityInterfaces;
#ifdef __cplusplus
extern "C" {
#endif
// If exported by a plugin, this function will be called when the plugin is loaded.
void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces* unityInterfaces);
// If exported by a plugin, this function will be called when the plugin is about to be unloaded.
void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload();
#ifdef __cplusplus
}
#endif
struct RenderSurfaceBase;
typedef struct RenderSurfaceBase* UnityRenderBuffer;
typedef unsigned int UnityTextureID;

265
engine/third_party/Unity/IUnityProfiler.h


// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an AS IS BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityInterface.h"
#include <stdint.h>
// Unity Profiler Native plugin API provides an ability to register callbacks for Unity Profiler events.
// The basic functionality includes:
// 1. Ability to create a Unity Profiler Marker.
// 2. Begin and end sample.
// 3. Register a thread for profiling.
// 4. Obtain an information if profiler is available and enabled.
//
// Usage example:
//
// #include <IUnityInterface.h>
// #include <IUnityProfiler.h>
//
// static IUnityProfiler* s_UnityProfiler = NULL;
// static const UnityProfilerMarkerDesc* s_MyPluginMarker = NULL;
// static bool s_IsDevelopmentBuild = false;
//
// static void MyPluginWorkMethod()
// {
// if (s_IsDevelopmentBuild)
// s_UnityProfiler->BeginSample(s_MyPluginMarker);
//
// // Code I want to see in Unity Profiler as "MyPluginMethod".
// // ...
//
// if (s_IsDevelopmentBuild)
// s_UnityProfiler->EndSample(s_MyPluginMarker);
// }
//
// extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces* unityInterfaces)
// {
// s_UnityProfiler = unityInterfaces->Get<IUnityProfiler>();
// if (s_UnityProfiler == NULL)
// return;
// s_IsDevelopmentBuild = s_UnityProfiler->IsAvailable() != 0;
// s_UnityProfiler->CreateMarker(&s_MyPluginMarker, "MyPluginMethod", kUnityProfilerCategoryOther, kUnityProfilerMarkerFlagDefault, 0);
// }
//
// extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload()
// {
// }
typedef uint32_t UnityProfilerMarkerId;
enum UnityBuiltinProfilerCategory_
{
kUnityProfilerCategoryRender = 0,
kUnityProfilerCategoryScripts = 1,
kUnityProfilerCategoryManagedJobs = 2,
kUnityProfilerCategoryBurstJobs = 3,
kUnityProfilerCategoryGUI = 4,
kUnityProfilerCategoryPhysics = 5,
kUnityProfilerCategoryAnimation = 6,
kUnityProfilerCategoryAI = 7,
kUnityProfilerCategoryAudio = 8,
kUnityProfilerCategoryAudioJob = 9,
kUnityProfilerCategoryAudioUpdateJob = 10,
kUnityProfilerCategoryVideo = 11,
kUnityProfilerCategoryParticles = 12,
kUnityProfilerCategoryGi = 13,
kUnityProfilerCategoryNetwork = 14,
kUnityProfilerCategoryLoading = 15,
kUnityProfilerCategoryOther = 16,
kUnityProfilerCategoryGC = 17,
kUnityProfilerCategoryVSync = 18,
kUnityProfilerCategoryOverhead = 19,
kUnityProfilerCategoryPlayerLoop = 20,
kUnityProfilerCategoryDirector = 21,
kUnityProfilerCategoryVR = 22,
kUnityProfilerCategoryAllocation = 23, kUnityProfilerCategoryMemory = 23,
kUnityProfilerCategoryInternal = 24,
kUnityProfilerCategoryFileIO = 25,
kUnityProfilerCategoryUISystemLayout = 26,
kUnityProfilerCategoryUISystemRender = 27,
kUnityProfilerCategoryVFX = 28,
kUnityProfilerCategoryBuildInterface = 29,
kUnityProfilerCategoryInput = 30,
kUnityProfilerCategoryVirtualTexturing = 31,
};
typedef uint16_t UnityProfilerCategoryId;
typedef struct UnityProfilerCategoryDesc
{
// Incremental category index.
UnityProfilerCategoryId id;
// Reserved.
uint16_t reserved0;
// Internally associated category color which is in 0xRRGGBBAA format.
uint32_t rgbaColor;
// NULL-terminated string which is associated with the category.
const char* name;
} UnityProfilerCategoryDesc;
enum UnityProfilerMarkerFlag_
{
kUnityProfilerMarkerFlagDefault = 0,
kUnityProfilerMarkerFlagScriptUser = 1 << 1, // Markers created with C# API.
kUnityProfilerMarkerFlagScriptInvoke = 1 << 5, // Runtime invocations with ScriptingInvocation::Invoke.
kUnityProfilerMarkerFlagScriptEnterLeave = 1 << 6, // Deep profiler.
kUnityProfilerMarkerFlagAvailabilityEditor = 1 << 2, // Editor-only marker, doesn't present in dev and non-dev players.
kUnityProfilerMarkerFlagAvailabilityNonDev = 1 << 3, // Non-development marker, is present everywhere including release builds.
kUnityProfilerMarkerFlagWarning = 1 << 4, // Indicates undesirable, performance-wise suboptimal code path.
kCounter = 1 << 7, // Marker is also used as a counter.
kUnityProfilerMarkerFlagVerbosityDebug = 1 << 10, // Internal debug markers - e.g. JobSystem Idle.
kUnityProfilerMarkerFlagVerbosityInternal = 1 << 11, // Internal markers - e.g. Mutex/semaphore waits.
kUnityProfilerMarkerFlagVerbosityAdvanced = 1 << 12 // Markers which are useful for advanced users - e.g. Loading.
};
typedef uint16_t UnityProfilerMarkerFlags;
enum UnityProfilerMarkerEventType_
{
kUnityProfilerMarkerEventTypeBegin = 0,
kUnityProfilerMarkerEventTypeEnd = 1,
kUnityProfilerMarkerEventTypeSingle = 2
};
typedef uint16_t UnityProfilerMarkerEventType;
typedef struct UnityProfilerMarkerDesc
{
// Per-marker callback chain pointer. Don't use.
const void* callback;
// Event id.
UnityProfilerMarkerId id;
// UnityProfilerMarkerFlag_ value.
UnityProfilerMarkerFlags flags;
// Category index the marker belongs to.
UnityProfilerCategoryId categoryId;
// NULL-terminated string which is associated with the marker.
const char* name;
// Metadata descriptions chain. Don't use.
const void* metaDataDesc;
} UnityProfilerMarkerDesc;
enum UnityProfilerMarkerDataType_
{
kUnityProfilerMarkerDataTypeNone = 0,
kUnityProfilerMarkerDataTypeInstanceId = 1,
kUnityProfilerMarkerDataTypeInt32 = 2,
kUnityProfilerMarkerDataTypeUInt32 = 3,
kUnityProfilerMarkerDataTypeInt64 = 4,
kUnityProfilerMarkerDataTypeUInt64 = 5,
kUnityProfilerMarkerDataTypeFloat = 6,
kUnityProfilerMarkerDataTypeDouble = 7,
kUnityProfilerMarkerDataTypeString = 8,
kUnityProfilerMarkerDataTypeString16 = 9,
kUnityProfilerMarkerDataTypeBlob8 = 11,
kUnityProfilerMarkerDataTypeCount // Total count of data types
};
typedef uint8_t UnityProfilerMarkerDataType;
enum UnityProfilerMarkerDataUnit_
{
kUnityProfilerMarkerDataUnitUndefined = 0,
kUnityProfilerMarkerDataUnitTimeNanoseconds = 1,
kUnityProfilerMarkerDataUnitBytes = 2,
kUnityProfilerMarkerDataUnitCount = 3,
kUnityProfilerMarkerDataUnitPercent = 4,
kUnityProfilerMarkerDataUnitFrequencyHz = 5,
};
typedef uint8_t UnityProfilerMarkerDataUnit;
typedef struct UnityProfilerMarkerData
{
UnityProfilerMarkerDataType type;
uint8_t reserved0;
uint16_t reserved1;
uint32_t size;
const void* ptr;
} UnityProfilerMarkerData;
enum UnityProfilerFlowEventType_
{
// The flow began withing a current marker scope (enclosed scope).
kUnityProfilerFlowEventTypeBegin = 0,
// The flow continues with the next sample.
kUnityProfilerFlowEventTypeNext = 1,
// The flow ends with the next sample.
kUnityProfilerFlowEventTypeEnd = 2,
};
typedef uint8_t UnityProfilerFlowEventType;
typedef uint64_t UnityProfilerThreadId;
// Available since 2020.1
UNITY_DECLARE_INTERFACE(IUnityProfiler)
{
void BeginSample(const UnityProfilerMarkerDesc* markerDesc)
{
(this->EmitEvent)(markerDesc, kUnityProfilerMarkerEventTypeBegin, 0, NULL);
}
void BeginSample(const UnityProfilerMarkerDesc* markerDesc, uint16_t eventDataCount, const UnityProfilerMarkerData* eventData)
{
(this->EmitEvent)(markerDesc, kUnityProfilerMarkerEventTypeBegin, eventDataCount, eventData);
}
void EndSample(const UnityProfilerMarkerDesc* markerDesc)
{
(this->EmitEvent)(markerDesc, kUnityProfilerMarkerEventTypeEnd, 0, NULL);
}
// Create instrumentation event.
// \param markerDesc is a pointer to marker description struct.
// \param eventType is an event type - UnityProfilerMarkerEventType_.
// \param eventDataCount is an event metadata count passed in eventData. Must be less than eventDataCount specified in CreateMarker.
// \param eventData is a metadata array of eventDataCount elements.
void(UNITY_INTERFACE_API * EmitEvent)(const UnityProfilerMarkerDesc* markerDesc, UnityProfilerMarkerEventType eventType, uint16_t eventDataCount, const UnityProfilerMarkerData* eventData);
// Returns 1 if Unity Profiler is enabled, 0 overwise.
int(UNITY_INTERFACE_API * IsEnabled)();
// Returns 1 if Unity Profiler is available, 0 overwise.
// Profiler is available only in Development builds. Release builds have Unity Profiler compiled out.
// However individual markers can be available even in Release builds (e.g. GC.Collect) and be collected with
// Recorder API or forwarded to platform and other profilers (via IUnityProfilerCallbacks::RegisterMarkerEventCallback API).
// You can choose whenever you want or not emit profiler event in Development and Release builds using the cached result of this method.
int(UNITY_INTERFACE_API * IsAvailable)();
// Creates a new Unity Profiler marker.
// \param desc Pointer to the const UnityProfilerMarkerDesc* which is set to the created marker in a case of a succesful execution.
// \param name Marker name to be displayed in Unity Profiler.
// \param flags Marker flags. One of UnityProfilerMarkerFlag_ enum. Use kUnityProfilerMarkerFlagDefault if not sure.
// \param eventDataCount Maximum count of potential metadata parameters count.
// \return 0 on success and non-zero in case of error.
int(UNITY_INTERFACE_API * CreateMarker)(const UnityProfilerMarkerDesc** desc, const char* name, UnityProfilerCategoryId category, UnityProfilerMarkerFlags flags, int eventDataCount);
// Set a metadata description for the Unity Profiler marker.
// \param markerDesc is a pointer to marker description struct.
// \param index metadata index to set name for.
// \param metadataType Data type. Must be of UnityProfilerMarkerDataType_ enum.
// \param name Metadata name.
// \return 0 on success and non-zero in case of error.
int(UNITY_INTERFACE_API * SetMarkerMetadataName)(const UnityProfilerMarkerDesc* desc, int index, const char* metadataName, UnityProfilerMarkerDataType metadataType, UnityProfilerMarkerDataUnit metadataUnit);
// Registers current thread with Unity Profiler.
// Has no effect in Release Players.
// \param threadId Optional Unity Profiler thread identifier which it written on successful method call. Can be used with UnregisterThread.
// \param groupName Thread group name. Unity Profiler aggregates threads with the same group.
// \param name Thread name.
// \return 0 on success and non-zero in case of error.
int(UNITY_INTERFACE_API * RegisterThread)(UnityProfilerThreadId* threadId, const char* groupName, const char* name);
// Unregisters current thread from Unity Profiler and cleans up all associated memory.
// Has no effect in Release Players.
// \param threadId Unity Profiler thread identifier obtained with RegisterThread call. Use 0 to cleanup the current thread.
// \return 0 on success and non-zero in case of error.
int(UNITY_INTERFACE_API * UnregisterThread)(UnityProfilerThreadId threadId);
};
UNITY_REGISTER_INTERFACE_GUID(0x2CE79ED8316A4833ULL, 0x87076B2013E1571FULL, IUnityProfiler)

174
engine/third_party/Unity/IUnityProfilerCallbacks.h


// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an AS IS BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityInterface.h"
#include "IUnityProfiler.h"
#include <stdint.h>
// Unity Profiler Callbacks native plugin API provides an ability to register callbacks for Unity Profiler events.
// The basic functionality includes:
// 1. Profiler category creation callback - provides information about category name and color.
// 2. Profiler marker creation callback - provides information about new marker which is created internally or with C# API.
// 3. Marker event callback - allows to intercept begin/end events for the particular marker.
// 4. Frame event callback - provides information about logical CPU frame.
//
// Usage example:
//
// #include <IUnityInterface.h>
// #include <IUnityProfilerCallbacks.h>
//
// static IUnityProfilerCallbacks* s_UnityProfilerCallbacks = NULL;
//
// static void UNITY_INTERFACE_API MyProfilerEventCallback(const UnityProfilerMarkerDesc* markerDesc, UnityProfilerMarkerEventType eventType, unsigned short eventDataCount, const UnityProfilerMarkerData* eventData, void* userData)
// {
// switch (eventType)
// {
// case kUnityProfilerMarkerEventTypeBegin:
// {
// MyProfilerPushMarker(markerDesc->name);
// break;
// }
// case kUnityProfilerMarkerEventTypeEnd:
// {
// MyProfilerPopMarker(markerDesc->name);
// break;
// }
// }
// }
//
// static void UNITY_INTERFACE_API MyProfilerCreateMarkerCallback(const UnityProfilerMarkerDesc* markerDesc, void* userData)
// {
// s_UnityProfilerCallbacks->RegisterMarkerEventCallback(markerDesc, MyProfilerEventCallback, NULL);
// }
//
// extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces* unityInterfaces)
// {
// s_UnityProfilerCallbacks = unityInterfaces->Get<IUnityProfilerCallbacks>();
// s_UnityProfilerCallbacks->RegisterCreateMarkerCallback(&MyProfilerCreateMarkerCallback, NULL);
// }
//
// extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload()
// {
// s_UnityProfilerCallbacks->UnregisterCreateMarkerCallback(&MyProfilerCreateMarkerCallback, NULL);
// s_UnityProfilerCallbacks->UnregisterMarkerEventCallback(NULL, &MyProfilerEventCallback, NULL);
// }
typedef struct UnityProfilerThreadDesc
{
// Thread id c-casted to uint64_t.
UnityProfilerThreadId threadId;
// Thread group name. NULL-terminated.
const char* groupName;
// Thread name. NULL-terminated.
const char* name;
} UnityProfilerThreadDesc;
// Called when a new category is created. Up to 4 installed callbacks are supported.
// \param categoryDesc is a pointer to category description.
// \param userData is an optional context pointer passed with RegisterCreateCategoryCallback call.
typedef void (UNITY_INTERFACE_API * IUnityProfilerCreateCategoryCallback)(const UnityProfilerCategoryDesc* categoryDesc, void* userData);
// Called when a new profiler marker is created. Up to 4 installed callbacks are supported.
// \param markerDesc is a pointer to marker description.
// \param userData is an optional context pointer passed with RegisterCreateEventCallback call.
typedef void (UNITY_INTERFACE_API * IUnityProfilerCreateMarkerCallback)(const UnityProfilerMarkerDesc* markerDesc, void* userData);
// Called when a profiler event occurs.
// \param markerDesc is an marker description struct.
// \param eventType is an event type - UnityProfilerMarkerEventType_.
// \param eventDataCount is an event metadata count.
// \param eventData is a metadata array of eventDataCount elements.
// \param userData is an optional context pointer passed with RegisterCreateEventCallback call.
typedef void (UNITY_INTERFACE_API* IUnityProfilerMarkerEventCallback)(const UnityProfilerMarkerDesc* markerDesc, UnityProfilerMarkerEventType eventType, uint16_t eventDataCount, const UnityProfilerMarkerData* eventData, void* userData);
typedef void (UNITY_INTERFACE_API * IUnityProfilerBulkCounterDataEventCallback)(int counterGroup, size_t size, void* data, void* userData);
// Called when a profiler frame change occurs. Up to 4 installed callbacks are supported.
// \param userData is an optional context pointer passed with RegisterCreateEventCallback call.
typedef void (UNITY_INTERFACE_API * IUnityProfilerFrameCallback)(void* userData);
// Called when a profiler frame change occurs. Up to 4 installed callbacks are supported.
// \param userData is an optional context pointer passed with RegisterCreateEventCallback call.
typedef void (UNITY_INTERFACE_API * IUnityProfilerThreadCallback)(const UnityProfilerThreadDesc* threadDesc, void* userData);
// Called when a profiler flow event occurs.
// Flow events connect events across threads allowing to trace related activities initiated from a control(main) thread.
// \param flowEventType is a flow event type.
// \param flowId is an unique incremental identifier for the flow chain.
// \param userData is an optional context pointer passed with RegisterCreateEventCallback call.
typedef void (UNITY_INTERFACE_API * IUnityProfilerFlowEventCallback)(UnityProfilerFlowEventType flowEventType, uint32_t flowId, void* userData);
// Available since 2019.1
UNITY_DECLARE_INTERFACE(IUnityProfilerCallbacksV2)
{
// Register a callback which is called when a new category is created.
// Returns 0 on success and non-zero in case of error.
// Only up to 4 callbacks can be registered.
int(UNITY_INTERFACE_API * RegisterCreateCategoryCallback)(IUnityProfilerCreateCategoryCallback callback, void* userData);
int(UNITY_INTERFACE_API * UnregisterCreateCategoryCallback)(IUnityProfilerCreateCategoryCallback callback, void* userData);
// Register a callback which is called when a new marker is created.
// E.g. dynamically created in C# with "new PerformanceMarker(string)" or internally.
// Also is called for all existing markers when the callback is registered.
// Returns 0 on success and non-zero in case of error.
// Only up to 4 callbacks can be registered.
int(UNITY_INTERFACE_API * RegisterCreateMarkerCallback)(IUnityProfilerCreateMarkerCallback callback, void* userData);
int(UNITY_INTERFACE_API * UnregisterCreateMarkerCallback)(IUnityProfilerCreateMarkerCallback callback, void* userData);
// Register a callback which is called every time "PerformanceMarker.Begin(string)" is called or equivalent internal native counterpart.
// Returns 0 on success and non-zero in case of error.
// \param markerDesc is a pointer to marker description you want to install callback for.
int(UNITY_INTERFACE_API * RegisterMarkerEventCallback)(const UnityProfilerMarkerDesc * markerDesc, IUnityProfilerMarkerEventCallback callback, void* userData);
// Unregister per-marker callback.
// \param markerDesc is a pointer to marker description you want to remove callback from.
// \param userData optional context pointer.
// If markerDesc is NULL, callback is removed from all events which have (callback, userData) pair.
// If both markerDesc and userData are NULL, callback is removed from all events which have callback function pointer.
int(UNITY_INTERFACE_API * UnregisterMarkerEventCallback)(const UnityProfilerMarkerDesc * markerDesc, IUnityProfilerMarkerEventCallback callback, void* userData);
// Register a callback which is called every time Profiler.BeginSample is called or equivalent internal native counterpart.
// Returns 0 on success and non-zero in case of error.
// Only up to 4 callbacks can be registered.
int(UNITY_INTERFACE_API * RegisterFrameCallback)(IUnityProfilerFrameCallback callback, void* userData);
int(UNITY_INTERFACE_API * UnregisterFrameCallback)(IUnityProfilerFrameCallback callback, void* userData);
// Register a callback which is called every time a new thread is registered with profiler.
// Returns 0 on success and non-zero in case of error.
// Only up to 4 callbacks can be registered.
int(UNITY_INTERFACE_API * RegisterCreateThreadCallback)(IUnityProfilerThreadCallback callback, void* userData);
int(UNITY_INTERFACE_API * UnregisterCreateThreadCallback)(IUnityProfilerThreadCallback callback, void* userData);
// Register a callback which is called every time Unity generates a flow event.
// Returns 0 on success and non-zero in case of error.
// Note: Flow events are supported only in Development Players and Editor.
int(UNITY_INTERFACE_API * RegisterFlowEventCallback)(IUnityProfilerFlowEventCallback callback, void* userData);
// Unregister flow event callback.
// \param userData optional context pointer.
int(UNITY_INTERFACE_API * UnregisterFlowEventCallback)(IUnityProfilerFlowEventCallback callback, void* userData);
};
UNITY_REGISTER_INTERFACE_GUID(0x5DEB59E88F2D4571ULL, 0x81E8583069A5E33CULL, IUnityProfilerCallbacksV2)
// Available since 2018.2
UNITY_DECLARE_INTERFACE(IUnityProfilerCallbacks)
{
int(UNITY_INTERFACE_API * RegisterCreateCategoryCallback)(IUnityProfilerCreateCategoryCallback callback, void* userData);
int(UNITY_INTERFACE_API * UnregisterCreateCategoryCallback)(IUnityProfilerCreateCategoryCallback callback, void* userData);
int(UNITY_INTERFACE_API * RegisterCreateMarkerCallback)(IUnityProfilerCreateMarkerCallback callback, void* userData);
int(UNITY_INTERFACE_API * UnregisterCreateMarkerCallback)(IUnityProfilerCreateMarkerCallback callback, void* userData);
int(UNITY_INTERFACE_API * RegisterMarkerEventCallback)(const UnityProfilerMarkerDesc * markerDesc, IUnityProfilerMarkerEventCallback callback, void* userData);
int(UNITY_INTERFACE_API * UnregisterMarkerEventCallback)(const UnityProfilerMarkerDesc * markerDesc, IUnityProfilerMarkerEventCallback callback, void* userData);
int(UNITY_INTERFACE_API * RegisterFrameCallback)(IUnityProfilerFrameCallback callback, void* userData);
int(UNITY_INTERFACE_API * UnregisterFrameCallback)(IUnityProfilerFrameCallback callback, void* userData);
int(UNITY_INTERFACE_API * RegisterCreateThreadCallback)(IUnityProfilerThreadCallback callback, void* userData);
int(UNITY_INTERFACE_API * UnregisterCreateThreadCallback)(IUnityProfilerThreadCallback callback, void* userData);
};
UNITY_REGISTER_INTERFACE_GUID(0x572FDB38CE3C4B1FULL, 0xA6071A9A7C4F52D8ULL, IUnityProfilerCallbacks)

377
engine/third_party/Unity/IUnityRenderingExtensions.h


// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an AS IS BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityGraphics.h"
/*
Low-level Native Plugin Rendering Extensions
============================================
On top of the Low-level native plugin interface, Unity also supports low level rendering extensions that can receive callbacks when certain events happen.
This is mostly used to implement and control low-level rendering in your plugin and enable it to work with Unitys multithreaded rendering.
Due to the low-level nature of this extension the plugin might need to be preloaded before the devices get created.
Currently the convention is name-based namely the plugin name must be prefixed by GfxPlugin. Example: GfxPluginMyFancyNativePlugin.
<code>
// Native plugin code example
enum PluginCustomCommands
{
kPluginCustomCommandDownscale = kUnityRenderingExtUserEventsStart,
kPluginCustomCommandUpscale,
// insert your own events here
kPluginCustomCommandCount
};
static IUnityInterfaces* s_UnityInterfaces = NULL;
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
UnityPluginLoad(IUnityInterfaces* unityInterfaces)
{
// initialization code here...
}
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
UnityRenderingExtEvent(UnityRenderingExtEventType event, void* data)
{
switch (event)
{
case kUnityRenderingExtEventBeforeDrawCall:
// do some stuff
break;
case kUnityRenderingExtEventAfterDrawCall:
// undo some stuff
break;
case kPluginCustomCommandDownscale:
// downscale some stuff
break;
case kPluginCustomCommandUpscale:
// upscale some stuff
break;
}
}
</code>
*/
// These events will be propagated to all plugins that implement void UnityRenderingExtEvent(UnityRenderingExtEventType event, void* data);
typedef enum UnityRenderingExtEventType
{
kUnityRenderingExtEventSetStereoTarget, // issued during SetStereoTarget and carrying the current 'eye' index as parameter
kUnityRenderingExtEventSetStereoEye, // issued during stereo rendering at the beginning of each eye's rendering loop. It carries the current 'eye' index as parameter
kUnityRenderingExtEventStereoRenderingDone, // issued after the rendering has finished
kUnityRenderingExtEventBeforeDrawCall, // issued during BeforeDrawCall and carrying UnityRenderingExtBeforeDrawCallParams as parameter
kUnityRenderingExtEventAfterDrawCall, // issued during AfterDrawCall. This event doesn't carry any parameters
kUnityRenderingExtEventCustomGrab, // issued during GrabIntoRenderTexture since we can't simply copy the resources
// when custom rendering is used - we need to let plugin handle this. It carries over
// a UnityRenderingExtCustomBlitParams params = { X, source, dest, 0, 0 } ( X means it's irrelevant )
kUnityRenderingExtEventCustomBlit, // issued by plugin to insert custom blits. It carries over UnityRenderingExtCustomBlitParams as param.
kUnityRenderingExtEventUpdateTextureBegin, // Deprecated.
kUnityRenderingExtEventUpdateTextureEnd, // Deprecated.
kUnityRenderingExtEventUpdateTextureBeginV1 = kUnityRenderingExtEventUpdateTextureBegin, // Deprecated. Issued to update a texture. It carries over UnityRenderingExtTextureUpdateParamsV1
kUnityRenderingExtEventUpdateTextureEndV1 = kUnityRenderingExtEventUpdateTextureEnd, // Deprecated. Issued to signal the plugin that the texture update has finished. It carries over the same UnityRenderingExtTextureUpdateParamsV1 as kUnityRenderingExtEventUpdateTextureBeginV1
kUnityRenderingExtEventUpdateTextureBeginV2, // Issued to update a texture. It carries over UnityRenderingExtTextureUpdateParamsV2
kUnityRenderingExtEventUpdateTextureEndV2, // Issued to signal the plugin that the texture update has finished. It carries over the same UnityRenderingExtTextureUpdateParamsV2 as kUnityRenderingExtEventUpdateTextureBeginV2
// keep this last
kUnityRenderingExtEventCount,
kUnityRenderingExtUserEventsStart = kUnityRenderingExtEventCount
} UnityRenderingExtEventType;
typedef enum UnityRenderingExtCustomBlitCommands
{
kUnityRenderingExtCustomBlitVRFlush, // This event is mostly used in multi GPU configurations ( SLI, etc ) in order to allow the plugin to flush all GPU's targets
// keep this last
kUnityRenderingExtCustomBlitCount,
kUnityRenderingExtUserCustomBlitStart = kUnityRenderingExtCustomBlitCount
} UnityRenderingExtCustomBlitCommands;
/*
This will be propagated to all plugins implementing UnityRenderingExtQuery.
*/
typedef enum UnityRenderingExtQueryType
{
kUnityRenderingExtQueryOverrideViewport = 1 << 0, // The plugin handles setting up the viewport rects. Unity will skip its internal SetViewport calls
kUnityRenderingExtQueryOverrideScissor = 1 << 1, // The plugin handles setting up the scissor rects. Unity will skip its internal SetScissor calls
kUnityRenderingExtQueryOverrideVROcclussionMesh = 1 << 2, // The plugin handles its own VR occlusion mesh rendering. Unity will skip rendering its internal VR occlusion mask
kUnityRenderingExtQueryOverrideVRSinglePass = 1 << 3, // The plugin uses its own single pass stereo technique. Unity will only traverse and render the render node graph once.
// and it will clear the whole render target not just per-eye on demand.
kUnityRenderingExtQueryKeepOriginalDoubleWideWidth_DEPRECATED = 1 << 4, // Instructs unity to keep the original double wide width. By default unity will try and have a power-of-two width for mip-mapping requirements.
kUnityRenderingExtQueryRequestVRFlushCallback = 1 << 5, // Instructs unity to provide callbacks when the VR eye textures need flushing. Useful for multi GPU synchronization.
} UnityRenderingExtQueryType;
typedef enum UnityRenderingExtTextureFormat
{
kUnityRenderingExtFormatNone = 0, kUnityRenderingExtFormatFirst = kUnityRenderingExtFormatNone,
// sRGB formats
kUnityRenderingExtFormatR8_SRGB,
kUnityRenderingExtFormatR8G8_SRGB,
kUnityRenderingExtFormatR8G8B8_SRGB,
kUnityRenderingExtFormatR8G8B8A8_SRGB,
// 8 bit integer formats
kUnityRenderingExtFormatR8_UNorm,
kUnityRenderingExtFormatR8G8_UNorm,
kUnityRenderingExtFormatR8G8B8_UNorm,
kUnityRenderingExtFormatR8G8B8A8_UNorm,
kUnityRenderingExtFormatR8_SNorm,
kUnityRenderingExtFormatR8G8_SNorm,
kUnityRenderingExtFormatR8G8B8_SNorm,
kUnityRenderingExtFormatR8G8B8A8_SNorm,
kUnityRenderingExtFormatR8_UInt,
kUnityRenderingExtFormatR8G8_UInt,
kUnityRenderingExtFormatR8G8B8_UInt,
kUnityRenderingExtFormatR8G8B8A8_UInt,
kUnityRenderingExtFormatR8_SInt,
kUnityRenderingExtFormatR8G8_SInt,
kUnityRenderingExtFormatR8G8B8_SInt,
kUnityRenderingExtFormatR8G8B8A8_SInt,
// 16 bit integer formats
kUnityRenderingExtFormatR16_UNorm,
kUnityRenderingExtFormatR16G16_UNorm,
kUnityRenderingExtFormatR16G16B16_UNorm,
kUnityRenderingExtFormatR16G16B16A16_UNorm,
kUnityRenderingExtFormatR16_SNorm,
kUnityRenderingExtFormatR16G16_SNorm,
kUnityRenderingExtFormatR16G16B16_SNorm,
kUnityRenderingExtFormatR16G16B16A16_SNorm,
kUnityRenderingExtFormatR16_UInt,
kUnityRenderingExtFormatR16G16_UInt,
kUnityRenderingExtFormatR16G16B16_UInt,
kUnityRenderingExtFormatR16G16B16A16_UInt,
kUnityRenderingExtFormatR16_SInt,
kUnityRenderingExtFormatR16G16_SInt,
kUnityRenderingExtFormatR16G16B16_SInt,
kUnityRenderingExtFormatR16G16B16A16_SInt,
// 32 bit integer formats
kUnityRenderingExtFormatR32_UInt,
kUnityRenderingExtFormatR32G32_UInt,
kUnityRenderingExtFormatR32G32B32_UInt,
kUnityRenderingExtFormatR32G32B32A32_UInt,
kUnityRenderingExtFormatR32_SInt,
kUnityRenderingExtFormatR32G32_SInt,
kUnityRenderingExtFormatR32G32B32_SInt,
kUnityRenderingExtFormatR32G32B32A32_SInt,
// HDR formats
kUnityRenderingExtFormatR16_SFloat,
kUnityRenderingExtFormatR16G16_SFloat,
kUnityRenderingExtFormatR16G16B16_SFloat,
kUnityRenderingExtFormatR16G16B16A16_SFloat,
kUnityRenderingExtFormatR32_SFloat,
kUnityRenderingExtFormatR32G32_SFloat,
kUnityRenderingExtFormatR32G32B32_SFloat,
kUnityRenderingExtFormatR32G32B32A32_SFloat,
// Luminance and Alpha format
kUnityRenderingExtFormatL8_UNorm,
kUnityRenderingExtFormatA8_UNorm,
kUnityRenderingExtFormatA16_UNorm,
// BGR formats
kUnityRenderingExtFormatB8G8R8_SRGB,
kUnityRenderingExtFormatB8G8R8A8_SRGB,
kUnityRenderingExtFormatB8G8R8_UNorm,
kUnityRenderingExtFormatB8G8R8A8_UNorm,
kUnityRenderingExtFormatB8G8R8_SNorm,
kUnityRenderingExtFormatB8G8R8A8_SNorm,
kUnityRenderingExtFormatB8G8R8_UInt,
kUnityRenderingExtFormatB8G8R8A8_UInt,
kUnityRenderingExtFormatB8G8R8_SInt,
kUnityRenderingExtFormatB8G8R8A8_SInt,
// 16 bit packed formats
kUnityRenderingExtFormatR4G4B4A4_UNormPack16,
kUnityRenderingExtFormatB4G4R4A4_UNormPack16,
kUnityRenderingExtFormatR5G6B5_UNormPack16,
kUnityRenderingExtFormatB5G6R5_UNormPack16,
kUnityRenderingExtFormatR5G5B5A1_UNormPack16,
kUnityRenderingExtFormatB5G5R5A1_UNormPack16,
kUnityRenderingExtFormatA1R5G5B5_UNormPack16,
// Packed formats
kUnityRenderingExtFormatE5B9G9R9_UFloatPack32,
kUnityRenderingExtFormatB10G11R11_UFloatPack32,
kUnityRenderingExtFormatA2B10G10R10_UNormPack32,
kUnityRenderingExtFormatA2B10G10R10_UIntPack32,
kUnityRenderingExtFormatA2B10G10R10_SIntPack32,
kUnityRenderingExtFormatA2R10G10B10_UNormPack32,
kUnityRenderingExtFormatA2R10G10B10_UIntPack32,
kUnityRenderingExtFormatA2R10G10B10_SIntPack32,
kUnityRenderingExtFormatA2R10G10B10_XRSRGBPack32,
kUnityRenderingExtFormatA2R10G10B10_XRUNormPack32,
kUnityRenderingExtFormatR10G10B10_XRSRGBPack32,
kUnityRenderingExtFormatR10G10B10_XRUNormPack32,
kUnityRenderingExtFormatA10R10G10B10_XRSRGBPack32,
kUnityRenderingExtFormatA10R10G10B10_XRUNormPack32,
// ARGB formats... TextureFormat legacy
kUnityRenderingExtFormatA8R8G8B8_SRGB,
kUnityRenderingExtFormatA8R8G8B8_UNorm,
kUnityRenderingExtFormatA32R32G32B32_SFloat,
// Depth Stencil for formats
kUnityRenderingExtFormatD16_UNorm,
kUnityRenderingExtFormatD24_UNorm,
kUnityRenderingExtFormatD24_UNorm_S8_UInt,
kUnityRenderingExtFormatD32_SFloat,
kUnityRenderingExtFormatD32_SFloat_S8_Uint,
kUnityRenderingExtFormatS8_Uint,
// Compression formats
kUnityRenderingExtFormatRGBA_DXT1_SRGB,
kUnityRenderingExtFormatRGBA_DXT1_UNorm,
kUnityRenderingExtFormatRGBA_DXT3_SRGB,
kUnityRenderingExtFormatRGBA_DXT3_UNorm,
kUnityRenderingExtFormatRGBA_DXT5_SRGB,
kUnityRenderingExtFormatRGBA_DXT5_UNorm,
kUnityRenderingExtFormatR_BC4_UNorm,
kUnityRenderingExtFormatR_BC4_SNorm,
kUnityRenderingExtFormatRG_BC5_UNorm,
kUnityRenderingExtFormatRG_BC5_SNorm,
kUnityRenderingExtFormatRGB_BC6H_UFloat,
kUnityRenderingExtFormatRGB_BC6H_SFloat,
kUnityRenderingExtFormatRGBA_BC7_SRGB,
kUnityRenderingExtFormatRGBA_BC7_UNorm,
kUnityRenderingExtFormatRGB_PVRTC_2Bpp_SRGB,
kUnityRenderingExtFormatRGB_PVRTC_2Bpp_UNorm,
kUnityRenderingExtFormatRGB_PVRTC_4Bpp_SRGB,
kUnityRenderingExtFormatRGB_PVRTC_4Bpp_UNorm,
kUnityRenderingExtFormatRGBA_PVRTC_2Bpp_SRGB,
kUnityRenderingExtFormatRGBA_PVRTC_2Bpp_UNorm,
kUnityRenderingExtFormatRGBA_PVRTC_4Bpp_SRGB,
kUnityRenderingExtFormatRGBA_PVRTC_4Bpp_UNorm,
kUnityRenderingExtFormatRGB_ETC_UNorm,
kUnityRenderingExtFormatRGB_ETC2_SRGB,
kUnityRenderingExtFormatRGB_ETC2_UNorm,
kUnityRenderingExtFormatRGB_A1_ETC2_SRGB,
kUnityRenderingExtFormatRGB_A1_ETC2_UNorm,
kUnityRenderingExtFormatRGBA_ETC2_SRGB,
kUnityRenderingExtFormatRGBA_ETC2_UNorm,
kUnityRenderingExtFormatR_EAC_UNorm,
kUnityRenderingExtFormatR_EAC_SNorm,
kUnityRenderingExtFormatRG_EAC_UNorm,
kUnityRenderingExtFormatRG_EAC_SNorm,
kUnityRenderingExtFormatRGBA_ASTC4X4_SRGB,
kUnityRenderingExtFormatRGBA_ASTC4X4_UNorm,
kUnityRenderingExtFormatRGBA_ASTC5X5_SRGB,
kUnityRenderingExtFormatRGBA_ASTC5X5_UNorm,
kUnityRenderingExtFormatRGBA_ASTC6X6_SRGB,
kUnityRenderingExtFormatRGBA_ASTC6X6_UNorm,
kUnityRenderingExtFormatRGBA_ASTC8X8_SRGB,
kUnityRenderingExtFormatRGBA_ASTC8X8_UNorm,
kUnityRenderingExtFormatRGBA_ASTC10X10_SRGB,
kUnityRenderingExtFormatRGBA_ASTC10X10_UNorm,
kUnityRenderingExtFormatRGBA_ASTC12X12_SRGB,
kUnityRenderingExtFormatRGBA_ASTC12X12_UNorm,
// Video formats
kUnityRenderingExtFormatYUV2,
// Automatic formats, back-end decides
kUnityRenderingExtFormatDepthAuto,
kUnityRenderingExtFormatShadowAuto,
kUnityRenderingExtFormatVideoAuto,
// ASTC hdr profile
kUnityRenderingExtFormatRGBA_ASTC4X4_UFloat,
kUnityRenderingExtFormatRGBA_ASTC5X5_UFloat,
kUnityRenderingExtFormatRGBA_ASTC6X6_UFloat,
kUnityRenderingExtFormatRGBA_ASTC8X8_UFloat,
kUnityRenderingExtFormatRGBA_ASTC10X10_UFloat,
kUnityRenderingExtFormatRGBA_ASTC12X12_UFloat,
kUnityRenderingExtFormatLast = kUnityRenderingExtFormatRGBA_ASTC12X12_UFloat, // Remove?
} UnityRenderingExtTextureFormat;
typedef struct UnityRenderingExtBeforeDrawCallParams
{
void* vertexShader; // bound vertex shader (platform dependent)
void* fragmentShader; // bound fragment shader (platform dependent)
void* geometryShader; // bound geometry shader (platform dependent)
void* hullShader; // bound hull shader (platform dependent)
void* domainShader; // bound domain shader (platform dependent)
int eyeIndex; // the index of the current stereo "eye" being currently rendered.
} UnityRenderingExtBeforeDrawCallParams;
typedef struct UnityRenderingExtCustomBlitParams
{
UnityTextureID source; // source texture
UnityRenderBuffer destination; // destination surface
unsigned int command; // command for the custom blit - could be any UnityRenderingExtCustomBlitCommands command or custom ones.
unsigned int commandParam; // custom parameters for the command
unsigned int commandFlags; // custom flags for the command
} UnityRenderingExtCustomBlitParams;
// Deprecated. Use UnityRenderingExtTextureUpdateParamsV2 and CommandBuffer.IssuePluginCustomTextureUpdateV2 instead.
// Only supports DX11, GLES, Metal
typedef struct UnityRenderingExtTextureUpdateParamsV1
{
void* texData; // source data for the texture update. Must be set by the plugin
unsigned int userData; // user defined data. Set by the plugin
unsigned int textureID; // texture ID of the texture to be updated.
UnityRenderingExtTextureFormat format; // format of the texture to be updated
unsigned int width; // width of the texture
unsigned int height; // height of the texture
unsigned int bpp; // texture bytes per pixel.
} UnityRenderingExtTextureUpdateParamsV1;
// Deprecated. Use UnityRenderingExtTextureUpdateParamsV2 and CommandBuffer.IssuePluginCustomTextureUpdateV2 instead.
// Only supports DX11, GLES, Metal
typedef UnityRenderingExtTextureUpdateParamsV1 UnityRenderingExtTextureUpdateParams;
// Type of the "data" parameter passed when callbacks registered with CommandBuffer.IssuePluginCustomTextureUpdateV2 are called.
// Supports DX11, GLES, Metal, and Switch (also possibly PS4, PSVita in the future)
typedef struct UnityRenderingExtTextureUpdateParamsV2
{
void* texData; // source data for the texture update. Must be set by the plugin
intptr_t textureID; // texture ID of the texture to be updated.
unsigned int userData; // user defined data. Set by the plugin
UnityRenderingExtTextureFormat format; // format of the texture to be updated
unsigned int width; // width of the texture
unsigned int height; // height of the texture
unsigned int bpp; // texture bytes per pixel.
} UnityRenderingExtTextureUpdateParamsV2;
// Certain Unity APIs (GL.IssuePluginEventAndData, CommandBuffer.IssuePluginEventAndData) can callback into native plugins.
// Provide them with an address to a function of this signature.
typedef void (UNITY_INTERFACE_API * UnityRenderingEventAndData)(int eventId, void* data);
#ifdef __cplusplus
extern "C" {
#endif
// If exported by a plugin, this function will be called for all the events in UnityRenderingExtEventType
void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityRenderingExtEvent(UnityRenderingExtEventType event, void* data);
// If exported by a plugin, this function will be called to query the plugin for the queries in UnityRenderingExtQueryType
bool UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityRenderingExtQuery(UnityRenderingExtQueryType query);
#ifdef __cplusplus
}
#endif

210
engine/third_party/Unity/IUnityShaderCompilerAccess.h


// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an AS IS BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityGraphics.h"
/*
Low-level Native Plugin Shader Compiler Access
==============================================
On top of the Low-level native plugin interface, Unity also supports low level access to the shader compiler, allowing the user to inject different variants into a shader.
It is also an event driven approach in which the plugin will receive callbacks when certain builtin events happen.
*/
enum UnityShaderCompilerExtCompilerPlatform
{
kUnityShaderCompilerExtCompPlatformUnused0 = 0,
kUnityShaderCompilerExtCompPlatformUnused1,
kUnityShaderCompilerExtCompPlatformUnused2,
kUnityShaderCompilerExtCompPlatformUnused3,
kUnityShaderCompilerExtCompPlatformD3D11, // Direct3D 11 (FL10.0 and up), compiled with MS D3DCompiler
kUnityShaderCompilerExtCompPlatformGLES20, // OpenGL ES 2.0 / WebGL 1.0, compiled with MS D3DCompiler + HLSLcc
kUnityShaderCompilerExtCompPlatformUnused6,
kUnityShaderCompilerExtCompPlatformUnused7,
kUnityShaderCompilerExtCompPlatformUnused8,
kUnityShaderCompilerExtCompPlatformGLES3Plus, // OpenGL ES 3.0+ / WebGL 2.0, compiled with MS D3DCompiler + HLSLcc
kUnityShaderCompilerExtCompPlatformUnused10,
kUnityShaderCompilerExtCompPlatformPS4, // Sony PS4
kUnityShaderCompilerExtCompPlatformXboxOne, // MS XboxOne
kUnityShaderCompilerExtCompPlatformUnused13,
kUnityShaderCompilerExtCompPlatformMetal, // Apple Metal, compiled with MS D3DCompiler + HLSLcc
kUnityShaderCompilerExtCompPlatformOpenGLCore, // Desktop OpenGL 3+, compiled with MS D3DCompiler + HLSLcc
kUnityShaderCompilerExtCompPlatformUnused16,
kUnityShaderCompilerExtCompPlatformUnused17,
kUnityShaderCompilerExtCompPlatformVulkan, // Vulkan SPIR-V, compiled with MS D3DCompiler + HLSLcc
kUnityShaderCompilerExtCompPlatformSwitch, // Nintendo Switch (NVN)
kUnityShaderCompilerExtCompPlatformXboxOneD3D12, // Xbox One D3D12
kUnityShaderCompilerExtCompPlatformCount
};
enum UnityShaderCompilerExtShaderType
{
kUnityShaderCompilerExtShaderNone = 0,
kUnityShaderCompilerExtShaderVertex = 1,
kUnityShaderCompilerExtShaderFragment = 2,
kUnityShaderCompilerExtShaderGeometry = 3,
kUnityShaderCompilerExtShaderHull = 4,
kUnityShaderCompilerExtShaderDomain = 5,
kUnityShaderCompilerExtShaderRayTracing = 6,
kUnityShaderCompilerExtShaderTypeCount // keep this last!
};
enum UnityShaderCompilerExtGPUProgramType
{
kUnityShaderCompilerExtGPUProgramTargetUnknown = 0,
kUnityShaderCompilerExtGPUProgramTargetGLLegacy = 1, // removed
kUnityShaderCompilerExtGPUProgramTargetGLES31AEP = 2,
kUnityShaderCompilerExtGPUProgramTargetGLES31 = 3,
kUnityShaderCompilerExtGPUProgramTargetGLES3 = 4,
kUnityShaderCompilerExtGPUProgramTargetGLES = 5,
kUnityShaderCompilerExtGPUProgramTargetGLCore32 = 6,
kUnityShaderCompilerExtGPUProgramTargetGLCore41 = 7,
kUnityShaderCompilerExtGPUProgramTargetGLCore43 = 8,
kUnityShaderCompilerExtGPUProgramTargetDX9VertexSM20 = 9, // removed
kUnityShaderCompilerExtGPUProgramTargetDX9VertexSM30 = 10, // removed
kUnityShaderCompilerExtGPUProgramTargetDX9PixelSM20 = 11, // removed
kUnityShaderCompilerExtGPUProgramTargetDX9PixelSM30 = 12, // removed
kUnityShaderCompilerExtGPUProgramTargetDX10Level9Vertex = 13,
kUnityShaderCompilerExtGPUProgramTargetDX10Level9Pixel = 14,
kUnityShaderCompilerExtGPUProgramTargetDX11VertexSM40 = 15,
kUnityShaderCompilerExtGPUProgramTargetDX11VertexSM50 = 16,
kUnityShaderCompilerExtGPUProgramTargetDX11PixelSM40 = 17,
kUnityShaderCompilerExtGPUProgramTargetDX11PixelSM50 = 18,
kUnityShaderCompilerExtGPUProgramTargetDX11GeometrySM40 = 19,
kUnityShaderCompilerExtGPUProgramTargetDX11GeometrySM50 = 20,
kUnityShaderCompilerExtGPUProgramTargetDX11HullSM50 = 21,
kUnityShaderCompilerExtGPUProgramTargetDX11DomainSM50 = 22,
kUnityShaderCompilerExtGPUProgramTargetMetalVS = 23,
kUnityShaderCompilerExtGPUProgramTargetMetalFS = 24,
kUnityShaderCompilerExtGPUProgramTargetSPIRV = 25,
kUnityShaderCompilerExtGPUProgramTargetUnused1 = 26,
kUnityShaderCompilerExtGPUProgramTargetUnused2 = 27,
kUnityShaderCompilerExtGPUProgramTargetUnused3 = 28,
kUnityShaderCompilerExtGPUProgramTargetUnused4 = 29,
kUnityShaderCompilerExtGPUProgramTargetUnused5 = 30,
kUnityShaderCompilerExtGPUProgramTargetRayTracing = 31,
kUnityShaderCompilerExtGPUProgramTargetCount
};
enum UnityShaderCompilerExtGPUProgram
{
kUnityShaderCompilerExtGPUProgramVS = 1 << kUnityShaderCompilerExtShaderVertex,
kUnityShaderCompilerExtGPUProgramPS = 1 << kUnityShaderCompilerExtShaderFragment,
kUnityShaderCompilerExtGPUProgramGS = 1 << kUnityShaderCompilerExtShaderGeometry,
kUnityShaderCompilerExtGPUProgramHS = 1 << kUnityShaderCompilerExtShaderHull,
kUnityShaderCompilerExtGPUProgramDS = 1 << kUnityShaderCompilerExtShaderDomain,
kUnityShaderCompilerExtGPUProgramCustom = 1 << kUnityShaderCompilerExtShaderTypeCount
};
enum UnityShaderCompilerExtEventType
{
kUnityShaderCompilerExtEventCreateCustomSourceVariant, // The plugin can create a new variant based on the initial snippet. The callback will receive UnityShaderCompilerExtCustomSourceVariantParams as data.
kUnityShaderCompilerExtEventCreateCustomSourceVariantCleanup, // Typically received after the kUnityShaderCompilerExtEventCreateCustomVariant event so the plugin has a chance to cleanup after itself. (outputSnippet & outputKeyword)
kUnityShaderCompilerExtEventCreateCustomBinaryVariant, // The plugin can create a new variant based on the initial snippet. The callback will receive UnityShaderCompilerExtCustomBinaryVariantParams as data.
kUnityShaderCompilerExtEventCreateCustomBinaryVariantCleanup, // Typically received after the kUnityShaderCompilerExtEventCreateCustomVariant event so the plugin has a chance to cleanup after itself. (outputSnippet & outputKeyword)
kUnityShaderCompilerExtEventPluginConfigure, // Event sent so the plugin can configure itself. It receives IUnityShaderCompilerExtPluginConfigure* as data
// keep these last
kUnityShaderCompilerExtEventCount,
kUnityShaderCompilerExtUserEventsStart = kUnityShaderCompilerExtEventCount
};
struct UnityShaderCompilerExtCustomSourceVariantParams
{
char* outputSnippet; // snippet after the plugin has finished processing it.
char* outputKeywords; // keywords exported by the plugin for this specific variant
const char* inputSnippet; // the source shader snippet
bool vr; // is VR enabled / supported ?
UnityShaderCompilerExtCompilerPlatform platform; // compiler platform
UnityShaderCompilerExtShaderType shaderType; // source code type
};
struct UnityShaderCompilerExtCustomBinaryVariantParams
{
void** outputBinaryShader; // output of the plugin generated binary shader (platform dependent)
const unsigned char* inputByteCode; // the shader byteCode (platform dependent)
unsigned int inputByteCodeSize; // shader bytecode size
unsigned int programTypeMask; // a mask of UnityShaderCompilerExtGPUProgram values
UnityShaderCompilerExtCompilerPlatform platform; // compiler platform
};
/*
This class is queried by unity to get information about the plugin.
The plugin has to set all the relevant values during the kUnityShaderCompilerExtEventPluginConfigure event.
<code>
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
UnityShaderCompilerExtEvent(UnityShaderCompilerExtEventType event, void* data)
{
switch (event)
{
...
case kUnityShaderCompilerExtEventPluginConfigure:
{
unsigned int GPUCompilerMask = (1 << kUnityShaderCompilerExtGPUProgramTargetDX11VertexSM40)
| (1 << kUnityShaderCompilerExtGPUProgramTargetDX11VertexSM50)
| (1 << kUnityShaderCompilerExtGPUProgramTargetDX11PixelSM40)
| (1 << kUnityShaderCompilerExtGPUProgramTargetDX11PixelSM50)
| (1 << kUnityShaderCompilerExtGPUProgramTargetDX11GeometrySM40)
| (1 << kUnityShaderCompilerExtGPUProgramTargetDX11GeometrySM50)
| (1 << kUnityShaderCompilerExtGPUProgramTargetDX11HullSM50)
| (1 << kUnityShaderCompilerExtGPUProgramTargetDX11DomainSM50);
unsigned int ShaderMask = kUnityShaderCompilerExtGPUProgramVS | kUnityShaderCompilerExtGPUProgramDS;
IUnityShaderCompilerExtPluginConfigure* pluginConfig = (IUnityShaderCompilerExtPluginConfigure*)data;
pluginConfig->ReserveKeyword(SHADER_KEYWORDS);
pluginConfig->SetGPUProgramCompilerMask(GPUCompilerMask);
pluginConfig->SetShaderProgramMask(ShaderMask);
break;
}
}
}
</code>
*/
class IUnityShaderCompilerExtPluginConfigure
{
public:
virtual ~IUnityShaderCompilerExtPluginConfigure() {}
virtual void ReserveKeyword(const char* keyword) = 0; // Allow the plugin to reserve its keyword so unity can include it in calculating the variants
virtual void SetGPUProgramCompilerMask(unsigned int mask) = 0; // Specifies a bit mask of UnityShaderCompilerExtGPUProgramType programs the plugin supports compiling
virtual void SetShaderProgramMask(unsigned int mask) = 0; // Specifies a bit mask of UnityShaderCompilerExtGPUProgram programs the plugin supports compiling
};
// Interface to help setup / configure both unity and the plugin.
#ifdef __cplusplus
extern "C" {
#endif
// If exported by a plugin, this function will be called for all the events in UnityShaderCompilerExtEventType
void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityShaderCompilerExtEvent(UnityShaderCompilerExtEventType event, void* data);
#ifdef __cplusplus
}
#endif

5
engine/third_party/Unity/LICENSE.md


Unity Native Plugin API copyright © 2015 Unity Technologies ApS
Licensed under the Unity Companion License for Unity-dependent projects--see [Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. Please review the license for details on these and other terms and conditions.
正在加载...
取消
保存