├── .gitattributes ├── .gitignore ├── .stignore ├── LICENSE.txt ├── OfficialVeldrid.SDL.Samples ├── OfficialVeldrid.SDL.Samples.csproj └── Readme.md ├── README.md ├── Veldrid.Maui.Samples ├── Veldrid.Maui.Controls │ ├── AssetPrimitives │ │ ├── AssetPrimitives.cs │ │ ├── BinaryExtensions.cs │ │ ├── ByteArraySerializer.cs │ │ ├── DefaultSerializers.cs │ │ ├── KtxFile.cs │ │ ├── ProcessedModel.cs │ │ └── ProcessedTexture.cs │ ├── AssetProcessor │ │ ├── BinaryAssetProcessor.cs │ │ ├── ImageProcessor.Android.cs │ │ ├── ImageProcessor.cs │ │ ├── ImageProcessor.iOS.cs │ │ └── KtxFileProcessor.cs │ ├── Base │ │ ├── BaseCamera.cs │ │ ├── BaseGpuDrawable.cs │ │ ├── BaseVeldridPlatformInterface.cs │ │ ├── IVeldridPlatformInterface.cs │ │ ├── PlatformType.cs │ │ └── SimpleCamera.cs │ ├── Handlers │ │ ├── IVeldridView.cs │ │ ├── VeldridViewHandler.Android.cs │ │ ├── VeldridViewHandler.Standard.cs │ │ ├── VeldridViewHandler.Windows.cs │ │ ├── VeldridViewHandler.cs │ │ └── VeldridViewHandler.iOS.cs │ ├── Hosts │ │ └── AppHostBuilderExtensions.cs.cs │ ├── Platform │ │ ├── Android │ │ │ ├── ValueAnimator.Android.cs │ │ │ ├── VeldridPlatformInterface.cs │ │ │ └── VeldridPlatformView.cs │ │ ├── README.txt │ │ ├── Tizen │ │ │ └── PlatformClass1.cs │ │ ├── Windows │ │ │ ├── ValueAnimator.Windows.cs │ │ │ ├── VeldridPlatformInterface.cs │ │ │ └── VeldridPlatformView.cs │ │ └── iOSMac │ │ │ ├── ValueAnimator.iOS.cs │ │ │ ├── VeldridPlatformInterface.cs │ │ │ └── VeldridPlatformView.cs │ ├── Veldrid.Maui.Controls.csproj │ └── VeldridView.cs ├── Veldrid.Maui.Samples.Core │ ├── AnimatedMesh │ │ ├── AnimatedMeshApplication.cs │ │ ├── AnimatedVertex.cs │ │ ├── Assets │ │ │ ├── goblin.dae │ │ │ └── goblin_bc3_unorm.ktx │ │ ├── BoneAnimInfo.cs │ │ ├── Extensions.cs │ │ └── ProcessedAssets │ │ │ ├── goblin.binary │ │ │ └── goblin_bc3_unorm.binary │ ├── ComputeParticles │ │ ├── BaseGpuDrawableExtension.cs │ │ ├── ComputeParticlesApplication.cs │ │ └── Shaders │ │ │ ├── Compute.glsl │ │ │ ├── Fragment.glsl │ │ │ └── Vertex.glsl │ ├── ComputeTexture │ │ ├── ComputeTextureApplication.cs │ │ └── Shaders │ │ │ ├── Compute.glsl │ │ │ ├── Fragment.glsl │ │ │ └── Vertex.glsl │ ├── GettingStarted │ │ ├── Assets │ │ │ └── OpenSans-Regular.ttf │ │ ├── BaseGpuDrawableExtension.cs │ │ ├── GettingStarted.cs │ │ ├── spirvFragmentCode.cs │ │ └── spirvVertexCode.cs │ ├── Headless │ │ ├── BaseGpuDrawableExtension.cs │ │ ├── HeaderlessGraphicsDevice.cs │ │ ├── HeaderlessTextures.cs │ │ └── HeadlessHelloTriangle.cs │ ├── Instancing │ │ ├── Assets │ │ │ ├── lavaplanet_bc3_unorm.ktx │ │ │ ├── lavaplanet_etc2_unorm.ktx │ │ │ ├── rock01.dae │ │ │ ├── sphere.obj │ │ │ ├── texturearray_rocks_bc3_unorm.ktx │ │ │ └── texturearray_rocks_etc2_unorm.ktx │ │ ├── InstancingApplication.cs │ │ ├── ProcessedAssets │ │ │ ├── lavaplanet_bc3_unorm.binary │ │ │ ├── lavaplanet_etc2_unorm.binary │ │ │ ├── rock01.binary │ │ │ ├── sphere.binary │ │ │ ├── texturearray_rocks_bc3_unorm.binary │ │ │ └── texturearray_rocks_etc2_unorm.binary │ │ └── Shaders │ │ │ ├── Instance-fragment.glsl │ │ │ ├── Instance-vertex.glsl │ │ │ ├── Planet-fragment.glsl │ │ │ ├── Planet-vertex.glsl │ │ │ ├── Starfield-fragment.glsl │ │ │ └── Starfield-vertex.glsl │ ├── LearnOpenGL │ │ ├── Assets │ │ │ ├── Images │ │ │ │ ├── awesomeface.png │ │ │ │ ├── container.jpg │ │ │ │ └── wall.jpg │ │ │ └── ProcessedImages │ │ │ │ ├── awesomeface.binary │ │ │ │ ├── container.binary │ │ │ │ └── wall.binary │ │ ├── BaseGpuDrawableExtension.cs │ │ ├── Camera_LookAt.cs │ │ ├── Camera_WalkAround.cs │ │ ├── CoordinateSystems_Going3D.cs │ │ ├── CoordinateSystems_More3D.cs │ │ ├── CoordinateSystems_MoreCubes.cs │ │ ├── HelloTriangle.cs │ │ ├── HelloTriangle_ElementBufferObject.cs │ │ ├── Shaders_InsAndOuts.cs │ │ ├── Shaders_MoreAttributes.cs │ │ ├── Shaders_Uniform.cs │ │ ├── Textures.cs │ │ ├── Textures_ApplyingTextures.cs │ │ ├── Textures_TextureUnits.cs │ │ └── Transformations_InPractice.cs │ ├── Offscreen │ │ ├── Assets │ │ │ ├── chinesedragon.dae │ │ │ ├── darkmetal_bc3_unorm.ktx │ │ │ └── plane2.dae │ │ ├── Model.cs │ │ ├── OffscreenApplication.cs │ │ ├── RawList.cs │ │ └── Shaders │ │ │ ├── Mirror-fragment.glsl │ │ │ ├── Mirror-vertex.glsl │ │ │ ├── Phong-fragment.glsl │ │ │ └── Phong-vertex.glsl │ ├── RenderDocCapture.cs │ ├── TexturedCube │ │ ├── Assets │ │ │ ├── Images │ │ │ │ └── spnza_bricks_a_diff.png │ │ │ ├── ProcessedImages │ │ │ │ └── spnza_bricks_a_diff.binary │ │ │ └── Shaders │ │ │ │ ├── frag.glsl │ │ │ │ └── vert.glsl │ │ ├── BaseGpuDrawableExtension.cs │ │ └── TexturedCubeDrawable.cs │ └── Veldrid.Maui.Samples.Core.csproj └── Veldrid.Maui.Samples │ ├── App.xaml │ ├── App.xaml.cs │ ├── AppShell.xaml │ ├── AppShell.xaml.cs │ ├── MainPage.xaml │ ├── MainPage.xaml.cs │ ├── MauiProgram.cs │ ├── Platforms │ ├── Android │ │ ├── AndroidManifest.xml │ │ ├── MainActivity.cs │ │ ├── MainApplication.cs │ │ └── Resources │ │ │ └── values │ │ │ └── colors.xml │ ├── MacCatalyst │ │ ├── AppDelegate.cs │ │ ├── Info.plist │ │ └── Program.cs │ ├── Tizen │ │ ├── Main.cs │ │ └── tizen-manifest.xml │ ├── Windows │ │ ├── App.xaml │ │ ├── App.xaml.cs │ │ ├── Package.appxmanifest │ │ └── app.manifest │ └── iOS │ │ ├── AppDelegate.cs │ │ ├── Info.plist │ │ └── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Resources │ ├── AppIcon │ │ ├── appicon.svg │ │ └── appiconfg.svg │ ├── Fonts │ │ ├── OpenSans-Regular.ttf │ │ └── OpenSans-Semibold.ttf │ ├── Images │ │ └── dotnet_bot.svg │ ├── Raw │ │ └── AboutAssets.txt │ ├── Splash │ │ └── splash.svg │ └── Styles │ │ ├── Colors.xaml │ │ └── Styles.xaml │ └── Veldrid.Maui.Samples.csproj ├── Veldrid.SDL.Samples ├── Base │ ├── VeldridPlatformInterface.cs │ └── VeldridPlatformWindow.cs ├── Program.cs └── Veldrid.SDL.Samples.csproj ├── Veldrid.Samples.sln ├── Veldrid.Wpf.Samples ├── App.xaml ├── App.xaml.cs ├── AssemblyInfo.cs ├── MainWindow.xaml ├── MainWindow.xaml.cs ├── Veldrid.Wpf.Samples.csproj ├── VeldridComponent.cs ├── VeldridPlatformInterface.cs ├── VeldridPlatformView.cs └── Win32HwndControl.cs └── Veldrid.macOS.Samples ├── Veldrid.macOS.Samples.sln └── Veldrid.macOS.Samples ├── AppDelegate.cs ├── AppGlobals.cs ├── Assets.xcassets ├── AppIcon.appiconset │ ├── Contents.json │ ├── Icon1024.png │ ├── Icon128.png │ ├── Icon16.png │ ├── Icon256.png │ ├── Icon32.png │ ├── Icon512.png │ └── Icon64.png └── Contents.json ├── Entitlements.plist ├── Info.plist ├── Main.cs ├── Main.storyboard ├── Veldrid.macOS.Samples.csproj ├── VeldridPlatformInterface.cs ├── VeldridPlatformView.cs ├── ViewController.cs ├── ViewController.designer.cs ├── ViewController.old.cs └── ViewController.old.designer.cs /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.stignore: -------------------------------------------------------------------------------- 1 | bin 2 | obj 3 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) [year] [fullname] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /OfficialVeldrid.SDL.Samples/OfficialVeldrid.SDL.Samples.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net7.0 6 | enable 7 | enable 8 | True 9 | 10 | 11 | 12 | 13 | SDLBase\%(RecursiveDir)%(FileName)%(Extension) 14 | 15 | 16 | AssetPrimitives\%(RecursiveDir)%(FileName)%(Extension) 17 | 18 | 19 | AssetProcessor\%(RecursiveDir)%(FileName)%(Extension) 20 | 21 | 22 | Base\%(RecursiveDir)%(FileName)%(Extension) 23 | 24 | 25 | 26 | 27 | 28 | LearnOpenGL\%(RecursiveDir)%(FileName)%(Extension) 29 | 30 | 31 | LearnOpenGL\Assets\Images\%(RecursiveDir)%(FileName)%(Extension) 32 | 33 | 34 | LearnOpenGL\Assets\ProcessedImages\%(RecursiveDir)%(FileName)%(Extension) 35 | 36 | 37 | Headless\%(RecursiveDir)%(FileName)%(Extension) 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /OfficialVeldrid.SDL.Samples/Readme.md: -------------------------------------------------------------------------------- 1 | This project use official veldrid nuget packages, to verify my veldrid is same as official veldrid. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Veldrid.Samples 2 | This project convert [veldrid-samples](https://github.com/mellinoe/veldrid-samples) and [Veldrid.Views ](https://github.com/PhilippeMonteil/Veldrid.Views) to net6.0, show how to use Veldrid in Maui, WPF, dotnet6.0-macOS, it use a [VeldridView](https://github.com/xtuzy/Veldrid.Maui.Controls) let you can use Gpu draw 3D graphics in Maui. 3 | 4 | # Notice 5 | VeldridView be moved to https://github.com/xtuzy/Veldrid.Maui.Controls 6 | 7 | # Demo screenshot 8 | Windows(D3D11): 9 | 10 | https://user-images.githubusercontent.com/17793881/205241391-f77ead46-a311-4700-881a-ae8d5675bef4.mp4 11 | 12 | Android(Vulkan) 13 | 14 | https://user-images.githubusercontent.com/17793881/207059132-8e349065-ea73-4f22-8329-6f4997a54258.mp4 15 | 16 | MacOS(Vulkan) 17 | 18 | https://user-images.githubusercontent.com/17793881/207260570-b8a9a6cd-41b4-4133-b84e-590d094a15d2.mp4 19 | 20 | Other: 21 | [see more platform result](https://github.com/xtuzy/Veldrid.Samples/issues/1) 22 | 23 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/AssetPrimitives/AssetPrimitives.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | 3 | namespace Veldrid.Maui.Controls.AssetPrimitives 4 | { 5 | public abstract class BinaryAssetSerializer 6 | { 7 | public abstract object Read(BinaryReader reader); 8 | public abstract void Write(BinaryWriter writer, object value); 9 | } 10 | 11 | public abstract class BinaryAssetSerializer : BinaryAssetSerializer 12 | { 13 | public override void Write(BinaryWriter writer, object value) => WriteT(writer, (T)value); 14 | public override object Read(BinaryReader reader) => ReadT(reader); 15 | 16 | public abstract T ReadT(BinaryReader reader); 17 | public abstract void WriteT(BinaryWriter writer, T value); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/AssetPrimitives/BinaryExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Runtime.CompilerServices; 4 | using System.Runtime.InteropServices; 5 | 6 | namespace Veldrid.Maui.Controls.AssetPrimitives 7 | { 8 | public static class BinaryExtensions 9 | { 10 | public static unsafe T ReadEnum(this BinaryReader reader) 11 | { 12 | int i32 = reader.ReadInt32(); 13 | return Unsafe.Read(&i32); 14 | } 15 | 16 | public static void WriteEnum(this BinaryWriter writer, T value) 17 | { 18 | int i32 = Convert.ToInt32(value); 19 | writer.Write(i32); 20 | } 21 | 22 | public static byte[] ReadByteArray(this BinaryReader reader) 23 | { 24 | int byteCount = reader.ReadInt32(); 25 | return reader.ReadBytes(byteCount); 26 | } 27 | 28 | public static void WriteByteArray(this BinaryWriter writer, byte[] array) 29 | { 30 | writer.Write(array.Length); 31 | writer.Write(array); 32 | } 33 | 34 | public static void WriteObjectArray(this BinaryWriter writer, T[] array, Action writeFunc) 35 | { 36 | writer.Write(array.Length); 37 | foreach (T item in array) 38 | { 39 | writeFunc(writer, item); 40 | } 41 | } 42 | 43 | public static T[] ReadObjectArray(this BinaryReader reader, Func readFunc) 44 | { 45 | int length = reader.ReadInt32(); 46 | T[] ret = new T[length]; 47 | for (int i = 0; i < length; i++) 48 | { 49 | ret[i] = readFunc(reader); 50 | } 51 | 52 | return ret; 53 | } 54 | 55 | public static unsafe void WriteBlittableArray(this BinaryWriter writer, T[] array) 56 | { 57 | int sizeofT = Unsafe.SizeOf(); 58 | int totalBytes = array.Length * sizeofT; 59 | 60 | GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned); 61 | byte* ptr = (byte*)handle.AddrOfPinnedObject(); 62 | 63 | writer.Write(array.Length); 64 | for (int i = 0; i < totalBytes; i++) 65 | { 66 | writer.Write(ptr[i]); 67 | } 68 | 69 | handle.Free(); 70 | } 71 | 72 | public static unsafe T[] ReadBlittableArray(this BinaryReader reader) 73 | { 74 | int sizeofT = Unsafe.SizeOf(); 75 | int length = reader.ReadInt32(); 76 | T[] ret = new T[length]; 77 | GCHandle handle = GCHandle.Alloc(ret, GCHandleType.Pinned); 78 | 79 | int totalBytes = length * sizeofT; 80 | byte* ptr = (byte*)handle.AddrOfPinnedObject(); 81 | for (int i = 0; i < totalBytes; i++) 82 | { 83 | ptr[i] = reader.ReadByte(); 84 | } 85 | 86 | handle.Free(); 87 | 88 | return ret; 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/AssetPrimitives/ByteArraySerializer.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | 3 | namespace Veldrid.Maui.Controls.AssetPrimitives 4 | { 5 | public class ByteArraySerializer : BinaryAssetSerializer 6 | { 7 | public override byte[] ReadT(BinaryReader reader) 8 | { 9 | return reader.ReadByteArray(); 10 | } 11 | 12 | public override void WriteT(BinaryWriter writer, byte[] value) 13 | { 14 | writer.WriteByteArray(value); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/AssetPrimitives/DefaultSerializers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Veldrid.Maui.Controls.AssetPrimitives 5 | { 6 | public static class DefaultSerializers 7 | { 8 | public static Dictionary Get() 9 | { 10 | return new Dictionary() 11 | { 12 | { typeof(ProcessedTexture), new ProcessedTextureDataSerializer() }, 13 | { typeof(ProcessedModel), new ProcessedModelSerializer() }, 14 | { typeof(byte[]), new ByteArraySerializer() } 15 | }; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/AssetPrimitives/ProcessedTexture.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using Veldrid; 4 | 5 | namespace Veldrid.Maui.Controls.AssetPrimitives 6 | { 7 | public class ProcessedTexture 8 | { 9 | public PixelFormat Format { get; set; } 10 | public TextureType Type { get; set; } 11 | public uint Width { get; set; } 12 | public uint Height { get; set; } 13 | public uint Depth { get; set; } 14 | public uint MipLevels { get; set; } 15 | public uint ArrayLayers { get; set; } 16 | public byte[] TextureData { get; set; } 17 | 18 | public ProcessedTexture( 19 | PixelFormat format, 20 | TextureType type, 21 | uint width, 22 | uint height, 23 | uint depth, 24 | uint mipLevels, 25 | uint arrayLayers, 26 | byte[] textureData) 27 | { 28 | Format = format; 29 | Type = type; 30 | Width = width; 31 | Height = height; 32 | Depth = depth; 33 | MipLevels = mipLevels; 34 | ArrayLayers = arrayLayers; 35 | TextureData = textureData; 36 | } 37 | 38 | public unsafe Texture CreateDeviceTexture(GraphicsDevice gd, ResourceFactory rf, TextureUsage usage) 39 | { 40 | Texture texture = rf.CreateTexture(new TextureDescription( 41 | Width, Height, Depth, MipLevels, ArrayLayers, Format, usage, Type)); 42 | 43 | Texture staging = rf.CreateTexture(new TextureDescription( 44 | Width, Height, Depth, MipLevels, ArrayLayers, Format, TextureUsage.Staging, Type)); 45 | 46 | ulong offset = 0; 47 | fixed (byte* texDataPtr = &TextureData[0]) 48 | { 49 | for (uint level = 0; level < MipLevels; level++) 50 | { 51 | uint mipWidth = GetDimension(Width, level); 52 | uint mipHeight = GetDimension(Height, level); 53 | uint mipDepth = GetDimension(Depth, level); 54 | uint subresourceSize = mipWidth * mipHeight * mipDepth * GetFormatSize(Format); 55 | 56 | for (uint layer = 0; layer < ArrayLayers; layer++) 57 | { 58 | gd.UpdateTexture( 59 | staging, (IntPtr)(texDataPtr + offset), subresourceSize, 60 | 0, 0, 0, mipWidth, mipHeight, mipDepth, 61 | level, layer); 62 | offset += subresourceSize; 63 | } 64 | } 65 | } 66 | 67 | CommandList cl = rf.CreateCommandList(); 68 | cl.Begin(); 69 | cl.CopyTexture(staging, texture); 70 | cl.End(); 71 | gd.SubmitCommands(cl); 72 | 73 | return texture; 74 | } 75 | 76 | private uint GetFormatSize(PixelFormat format) 77 | { 78 | switch (format) 79 | { 80 | case PixelFormat.R8_G8_B8_A8_UNorm: return 4; 81 | case PixelFormat.BC3_UNorm: return 1; 82 | default: throw new NotImplementedException(); 83 | } 84 | } 85 | 86 | public static uint GetDimension(uint largestLevelDimension, uint mipLevel) 87 | { 88 | uint ret = largestLevelDimension; 89 | for (uint i = 0; i < mipLevel; i++) 90 | { 91 | ret /= 2; 92 | } 93 | 94 | return Math.Max(1, ret); 95 | } 96 | } 97 | 98 | public class ProcessedTextureDataSerializer : BinaryAssetSerializer 99 | { 100 | public override ProcessedTexture ReadT(BinaryReader reader) 101 | { 102 | return new ProcessedTexture( 103 | reader.ReadEnum(), 104 | reader.ReadEnum(), 105 | reader.ReadUInt32(), 106 | reader.ReadUInt32(), 107 | reader.ReadUInt32(), 108 | reader.ReadUInt32(), 109 | reader.ReadUInt32(), 110 | reader.ReadByteArray()); 111 | } 112 | 113 | public override void WriteT(BinaryWriter writer, ProcessedTexture ptd) 114 | { 115 | writer.WriteEnum(ptd.Format); 116 | writer.WriteEnum(ptd.Type); 117 | writer.Write(ptd.Width); 118 | writer.Write(ptd.Height); 119 | writer.Write(ptd.Depth); 120 | writer.Write(ptd.MipLevels); 121 | writer.Write(ptd.ArrayLayers); 122 | writer.WriteByteArray(ptd.TextureData); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/AssetProcessor/BinaryAssetProcessor.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | 3 | namespace Veldrid.Maui.Controls.AssetProcessor 4 | { 5 | public abstract class BinaryAssetProcessor 6 | { 7 | public abstract object Process(Stream stream, string extension); 8 | } 9 | 10 | public abstract class BinaryAssetProcessor : BinaryAssetProcessor 11 | { 12 | public override object Process(Stream stream, string extension) => ProcessT(stream, extension); 13 | 14 | public abstract T ProcessT(Stream stream, string extension); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/AssetProcessor/ImageProcessor.Android.cs: -------------------------------------------------------------------------------- 1 | #if ANDROID 2 | using Android.Graphics; 3 | using Java.IO; 4 | using Java.Lang; 5 | using System.Diagnostics; 6 | using System.Runtime.CompilerServices; 7 | using System.Runtime.InteropServices; 8 | using Veldrid.Maui.Controls.AssetPrimitives; 9 | using Image = Android.Graphics.Bitmap; 10 | using Math = System.Math; 11 | 12 | namespace Veldrid.Maui.Controls.AssetProcessor 13 | { 14 | /// 15 | /// 可以用来在Android App运行时加载, 但由于Android处理图像可能较慢和使用了RgbaF16占内存较大, 建议在构建时处理, 运行时直接加载处理后的数据. 16 | /// 17 | public class ImageProcessor : BinaryAssetProcessor 18 | { 19 | public unsafe override ProcessedTexture ProcessT(Stream stream, string extension) 20 | { 21 | var options = new BitmapFactory.Options(); 22 | options.InPreferredConfig = Bitmap.Config.Argb8888; 23 | int formatSize = 4; 24 | Image image = BitmapFactory.DecodeStream(stream, null, options); 25 | Image[] mipmaps = GenerateMipmaps(image, formatSize, out int totalSize); 26 | 27 | byte[] allTexData = new byte[totalSize]; 28 | int offset = 0; 29 | /*foreach (var mipmap in mipmaps) 30 | { 31 | int mipSize = mipmap.Width * mipmap.Height * formatSize; 32 | using MemoryStream baos = new MemoryStream(); 33 | mipmap.Compress(Bitmap.CompressFormat.Png, 100, baos); 34 | baos.Read(allTexData, offset, mipSize); 35 | 36 | offset += mipSize; 37 | }*/ 38 | fixed (byte* allTexDataPtr = allTexData) 39 | { 40 | foreach (var mipmap in mipmaps) 41 | { 42 | int mipSize = (int)mipmap.Width * (int)mipmap.Height * formatSize; 43 | var data = bitmapToRgba(mipmap); 44 | fixed (byte* pixelPtr = data) 45 | { 46 | Buffer.MemoryCopy(pixelPtr, allTexDataPtr + offset, mipSize, mipSize); 47 | } 48 | offset += mipSize; 49 | } 50 | } 51 | 52 | ProcessedTexture texData = new ProcessedTexture( 53 | PixelFormat.R8_G8_B8_A8_UNorm, TextureType.Texture2D, 54 | (uint)image.Width, (uint)image.Height, 1, 55 | (uint)mipmaps.Length, 1, 56 | allTexData); 57 | return texData; 58 | } 59 | 60 | // Taken from Veldrid.ImageSharp 61 | 62 | private static Image[] GenerateMipmaps(Image baseImage, int formatSize, out int totalSize) 63 | { 64 | int mipLevelCount = ComputeMipLevels(baseImage.Width, baseImage.Height); 65 | Image[] mipLevels = new Image[mipLevelCount]; 66 | mipLevels[0] = baseImage; 67 | totalSize = baseImage.Width * baseImage.Height * formatSize; 68 | int i = 1; 69 | 70 | int currentWidth = baseImage.Width; 71 | int currentHeight = baseImage.Height; 72 | while (currentWidth != 1 || currentHeight != 1) 73 | { 74 | int newWidth = Math.Max(1, currentWidth / 2); 75 | int newHeight = Math.Max(1, currentHeight / 2); 76 | //Image newImage = baseImage.Clone(context => context.Resize(newWidth, newHeight, KnownResamplers.Lanczos3)); 77 | Image newImage = Bitmap.CreateScaledBitmap(baseImage, newWidth, newHeight, false); 78 | Debug.Assert(i < mipLevelCount); 79 | mipLevels[i] = newImage; 80 | 81 | totalSize += newWidth * newHeight * formatSize; 82 | i++; 83 | currentWidth = newWidth; 84 | currentHeight = newHeight; 85 | } 86 | 87 | Debug.Assert(i == mipLevelCount); 88 | 89 | return mipLevels; 90 | } 91 | 92 | public static int ComputeMipLevels(int width, int height) 93 | { 94 | return 1 + (int)Math.Floor(Math.Log(Math.Max(width, height), 2)); 95 | } 96 | 97 | /// 98 | /// https://stackoverflow.com/questions/59786742/android-bitmap-to-rgba-and-back 99 | /// 100 | /// 101 | /// 102 | /// 103 | public static byte[] bitmapToRgba(Bitmap bitmap) 104 | { 105 | if (bitmap.GetConfig() != Bitmap.Config.Argb8888) 106 | throw new IllegalArgumentException("Bitmap must be in ARGB_8888 format"); 107 | int[] pixels = new int[bitmap.Width * bitmap.Height]; 108 | byte[] bytes = new byte[pixels.Length * 4]; 109 | bitmap.GetPixels(pixels, 0, bitmap.Width, 0, 0, bitmap.Width, bitmap.Height); 110 | int i = 0; 111 | foreach (int pixel in pixels) 112 | { 113 | // Get components assuming is ARGB 114 | int A = (pixel >> 24) & 0xff; 115 | int R = (pixel >> 16) & 0xff; 116 | int G = (pixel >> 8) & 0xff; 117 | int B = pixel & 0xff; 118 | bytes[i++] = (byte)R; 119 | bytes[i++] = (byte)G; 120 | bytes[i++] = (byte)B; 121 | bytes[i++] = (byte)A; 122 | } 123 | return bytes; 124 | } 125 | 126 | public static Bitmap bitmapFromRgba(int width, int height, byte[] bytes) 127 | { 128 | int[] pixels = new int[bytes.Length / 4]; 129 | int j = 0; 130 | 131 | for (int i = 0; i < pixels.Length; i++) 132 | { 133 | int R = bytes[j++] & 0xff; 134 | int G = bytes[j++] & 0xff; 135 | int B = bytes[j++] & 0xff; 136 | int A = bytes[j++] & 0xff; 137 | 138 | int pixel = (A << 24) | (R << 16) | (G << 8) | B; 139 | pixels[i] = pixel; 140 | } 141 | 142 | 143 | Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888); 144 | bitmap.SetPixels(pixels, 0, width, 0, 0, width, height); 145 | return bitmap; 146 | } 147 | } 148 | } 149 | #endif -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/AssetProcessor/ImageProcessor.cs: -------------------------------------------------------------------------------- 1 | #if !ANDROID //&& !IOS && !MACCATALYST 2 | using SixLabors.ImageSharp; 3 | using SixLabors.ImageSharp.Advanced; 4 | using SixLabors.ImageSharp.PixelFormats; 5 | using SixLabors.ImageSharp.Processing; 6 | using System; 7 | using System.Diagnostics; 8 | using System.IO; 9 | using System.Runtime.CompilerServices; 10 | using Veldrid; 11 | using AssetPrimitives = Veldrid.Maui.Controls.AssetPrimitives; 12 | using Veldrid.Maui.Controls.AssetPrimitives; 13 | using System.Runtime.InteropServices; 14 | using Image = SixLabors.ImageSharp.Image; 15 | 16 | namespace Veldrid.Maui.Controls.AssetProcessor 17 | { 18 | /// 19 | /// 没有对Android,iOS,Maccatalyst,WinUI平台暴露, 只暴露给net6.0目标, 因此其目的是让开发者在App构建时处理图片. 20 | /// 21 | public class ImageProcessor : BinaryAssetProcessor 22 | { 23 | public unsafe override ProcessedTexture ProcessT(Stream stream, string extension) 24 | { 25 | Image image = Image.Load(stream); 26 | Image[] mipmaps = GenerateMipmaps(image, out int totalSize); 27 | 28 | byte[] allTexData = new byte[totalSize]; 29 | long offset = 0; 30 | fixed (byte* allTexDataPtr = allTexData) 31 | { 32 | foreach (Image mipmap in mipmaps) 33 | { 34 | long mipSize = mipmap.Width * mipmap.Height * sizeof(Rgba32); 35 | if (!mipmap.TryGetSinglePixelSpan(out Span pixelSpan)) 36 | { 37 | throw new VeldridException("Unable to get image pixelspan."); 38 | } 39 | fixed (void* pixelPtr = &MemoryMarshal.GetReference(pixelSpan)) 40 | { 41 | Buffer.MemoryCopy(pixelPtr, allTexDataPtr + offset, mipSize, mipSize); 42 | } 43 | 44 | offset += mipSize; 45 | } 46 | } 47 | 48 | ProcessedTexture texData = new ProcessedTexture( 49 | PixelFormat.R8_G8_B8_A8_UNorm, TextureType.Texture2D, 50 | (uint)image.Width, (uint)image.Height, 1, 51 | (uint)mipmaps.Length, 1, 52 | allTexData); 53 | return texData; 54 | } 55 | 56 | // Taken from Veldrid.ImageSharp 57 | 58 | private static Image[] GenerateMipmaps(Image baseImage, out int totalSize) where T : unmanaged, IPixel 59 | { 60 | int mipLevelCount = ComputeMipLevels(baseImage.Width, baseImage.Height); 61 | Image[] mipLevels = new Image[mipLevelCount]; 62 | mipLevels[0] = baseImage; 63 | totalSize = baseImage.Width * baseImage.Height * Unsafe.SizeOf(); 64 | int i = 1; 65 | 66 | int currentWidth = baseImage.Width; 67 | int currentHeight = baseImage.Height; 68 | while (currentWidth != 1 || currentHeight != 1) 69 | { 70 | int newWidth = Math.Max(1, currentWidth / 2); 71 | int newHeight = Math.Max(1, currentHeight / 2); 72 | Image newImage = baseImage.Clone(context => context.Resize(newWidth, newHeight, KnownResamplers.Lanczos3)); 73 | Debug.Assert(i < mipLevelCount); 74 | mipLevels[i] = newImage; 75 | 76 | totalSize += newWidth * newHeight * Unsafe.SizeOf(); 77 | i++; 78 | currentWidth = newWidth; 79 | currentHeight = newHeight; 80 | } 81 | 82 | Debug.Assert(i == mipLevelCount); 83 | 84 | return mipLevels; 85 | } 86 | 87 | public static int ComputeMipLevels(int width, int height) 88 | { 89 | return 1 + (int)Math.Floor(Math.Log(Math.Max(width, height), 2)); 90 | } 91 | } 92 | } 93 | #endif -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/AssetProcessor/KtxFileProcessor.cs: -------------------------------------------------------------------------------- 1 | using AssetPrimitives = Veldrid.Maui.Controls.AssetPrimitives; 2 | using Veldrid.Maui.Controls.AssetPrimitives; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Diagnostics; 6 | using System.IO; 7 | using Veldrid; 8 | 9 | namespace Veldrid.Maui.Controls.AssetProcessor 10 | { 11 | public class KtxFileProcessor : BinaryAssetProcessor 12 | { 13 | public override byte[] ProcessT(Stream stream, string extension) 14 | { 15 | MemoryStream ms = new MemoryStream(); 16 | stream.CopyTo(ms); 17 | return ms.ToArray(); 18 | 19 | //KtxFile ktx = KtxFile.Load(stream, false); 20 | 21 | //uint width = ktx.Header.PixelWidth; 22 | //uint height = ktx.Header.PixelHeight; 23 | //if (height == 0) height = width; 24 | 25 | //uint arrayLayers = Math.Max(1, ktx.Header.NumberOfArrayElements); 26 | //uint mipLevels = Math.Max(1, ktx.Header.NumberOfMipmapLevels); 27 | 28 | //// Copy texture data into single array 29 | //List bytes = new List(); 30 | //for (uint level = 0; level < mipLevels; level++) 31 | //{ 32 | // KtxMipmapLevel mipmap = ktx.Mipmaps[level]; 33 | // for (uint layer = 0; layer < arrayLayers; layer++) 34 | // { 35 | // KtxArrayElement ktxLayer = mipmap.ArrayElements[layer]; 36 | // Debug.Assert(ktxLayer.Faces.Length == 1); 37 | // byte[] pixelData = ktxLayer.Faces[0].Data; 38 | // bytes.AddRange(pixelData); 39 | // } 40 | //} 41 | 42 | //return new ProcessedTexture( 43 | // PixelFormat.BC3_UNorm, // TODO translate KtxFile.Header.GlFormat 44 | // TextureType.Texture2D, 45 | // width, 46 | // height, 47 | // 1, 48 | // mipLevels, 49 | // arrayLayers, 50 | // bytes.ToArray()); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Base/BaseCamera.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | using System.Runtime.InteropServices; 4 | using Veldrid; 5 | 6 | namespace Veldrid.Maui.Controls.Base 7 | { 8 | public abstract class BaseCamera 9 | { 10 | private float _fov = 1f; 11 | private float _near = 1f; 12 | private float _far = 1000f; 13 | 14 | private Matrix4x4 _viewMatrix; 15 | private Matrix4x4 _projectionMatrix; 16 | 17 | private Vector3 _position = new Vector3(0, 3, 0); 18 | private Vector3 _lookDirection = new Vector3(0, -.3f, -1f); 19 | private float _moveSpeed = 10.0f; 20 | 21 | private float _yaw; 22 | private float _pitch; 23 | 24 | internal float _windowWidth; 25 | internal float _windowHeight; 26 | 27 | public event Action ProjectionChanged; 28 | public event Action ViewChanged; 29 | 30 | public BaseCamera(): this(0, 0) 31 | { 32 | 33 | } 34 | 35 | public BaseCamera(float width, float height) 36 | { 37 | _windowWidth = width; 38 | _windowHeight = height; 39 | UpdatePerspectiveMatrix(); 40 | UpdateViewMatrix(); 41 | } 42 | 43 | public Matrix4x4 ViewMatrix => _viewMatrix; 44 | public Matrix4x4 ProjectionMatrix => _projectionMatrix; 45 | 46 | public Vector3 Position { get => _position; set { _position = value; UpdateViewMatrix(); } } 47 | 48 | public float FarDistance { get => _far; set { _far = value; UpdatePerspectiveMatrix(); } } 49 | public float FieldOfView => _fov; 50 | public float NearDistance { get => _near; set { _near = value; UpdatePerspectiveMatrix(); } } 51 | 52 | public float AspectRatio => _windowWidth / _windowHeight; 53 | 54 | public float Yaw { get => _yaw; set { _yaw = value; UpdateViewMatrix(); } } 55 | public float Pitch { get => _pitch; set { _pitch = value; UpdateViewMatrix(); } } 56 | 57 | public float MoveSpeed { get => _moveSpeed; set => _moveSpeed = value; } 58 | public Vector3 Forward => GetLookDir(); 59 | 60 | public abstract void Update(float deltaMillisecond); 61 | 62 | protected float Clamp(float value, float min, float max) 63 | { 64 | return value > max 65 | ? max 66 | : value < min 67 | ? min 68 | : value; 69 | } 70 | 71 | public void WindowResized(float width, float height) 72 | { 73 | _windowWidth = width; 74 | _windowHeight = height; 75 | UpdatePerspectiveMatrix(); 76 | } 77 | 78 | private void UpdatePerspectiveMatrix() 79 | { 80 | _projectionMatrix = Matrix4x4.CreatePerspectiveFieldOfView(_fov, _windowWidth / _windowHeight, _near, _far); 81 | ProjectionChanged?.Invoke(_projectionMatrix); 82 | } 83 | 84 | protected void UpdateViewMatrix() 85 | { 86 | Vector3 lookDir = GetLookDir(); 87 | _lookDirection = lookDir; 88 | _viewMatrix = Matrix4x4.CreateLookAt(_position, _position + _lookDirection, Vector3.UnitY); 89 | ViewChanged?.Invoke(_viewMatrix); 90 | } 91 | 92 | private Vector3 GetLookDir() 93 | { 94 | Quaternion lookRotation = Quaternion.CreateFromYawPitchRoll(Yaw, Pitch, 0f); 95 | Vector3 lookDir = Vector3.Transform(-Vector3.UnitZ, lookRotation); 96 | return lookDir; 97 | } 98 | 99 | public CameraInfo GetCameraInfo() => new CameraInfo 100 | { 101 | CameraPosition_WorldSpace = _position, 102 | CameraLookDirection = _lookDirection 103 | }; 104 | } 105 | 106 | [StructLayout(LayoutKind.Sequential)] 107 | public struct CameraInfo 108 | { 109 | public Vector3 CameraPosition_WorldSpace; 110 | private float _padding1; 111 | public Vector3 CameraLookDirection; 112 | private float _padding2; 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Base/BaseVeldridPlatformInterface.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Veldrid; 3 | 4 | namespace Veldrid.Maui.Controls.Base 5 | { 6 | public abstract class BaseVeldridPlatformInterface : IDisposable 7 | { 8 | BaseGpuDrawable drawable; 9 | public BaseGpuDrawable Drawable 10 | { 11 | get 12 | { 13 | return drawable; 14 | } 15 | set 16 | { 17 | var newDrawable = value; 18 | var oldDrawable = drawable; 19 | 20 | if (oldDrawable != null) 21 | { 22 | oldDrawable.TryRemoveFrom(this); 23 | } 24 | if(newDrawable != null) 25 | newDrawable.TryAddTo(this); 26 | drawable = newDrawable; 27 | } 28 | } 29 | 30 | public abstract bool AutoReDraw { get; set; } 31 | public GraphicsDeviceOptions? Options = null; 32 | 33 | public PlatformType PlatformType { get; protected set; } 34 | 35 | public event Action Rendering; 36 | public event Action GraphicsDeviceCreated; 37 | public event Action GraphicsDeviceDestroyed; 38 | public event Action Resized; 39 | 40 | //event Action KeyPressed; 41 | public void InvokeRendering(float deltaMilliseconds) => Rendering?.Invoke(deltaMilliseconds); 42 | public void InvokeGraphicsDeviceCreated() => GraphicsDeviceCreated?.Invoke(); 43 | public void InvokeGraphicsDeviceDestroyed() => GraphicsDeviceDestroyed?.Invoke(); 44 | public void InvokeResized() => Resized?.Invoke(); 45 | 46 | /// 47 | /// Pixel Width 48 | /// 49 | public abstract uint Width { get; } 50 | /// 51 | /// Pixel Height 52 | /// 53 | public abstract uint Height { get; } 54 | 55 | public GraphicsDevice _graphicsDevice { get; protected set; } 56 | public Swapchain _swapChain { get; protected set; } 57 | public ResourceFactory _resources { get; protected set; } 58 | 59 | public virtual void Dispose() 60 | { 61 | _resources = null; 62 | _swapChain?.Dispose(); 63 | _swapChain = null; 64 | _graphicsDevice?.Dispose(); 65 | _graphicsDevice = null; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Base/IVeldridPlatformInterface.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Veldrid; 3 | 4 | namespace Veldrid.Maui.Controls.Base 5 | { 6 | public interface IVeldridPlatformInterface 7 | { 8 | PlatformType PlatformType { get; } 9 | 10 | event Action Rendering; 11 | event Action GraphicsDeviceCreated; 12 | event Action GraphicsDeviceDestroyed; 13 | event Action Resized; 14 | //event Action KeyPressed; 15 | 16 | uint Width { get; } 17 | uint Height { get; } 18 | } 19 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Base/PlatformType.cs: -------------------------------------------------------------------------------- 1 | namespace Veldrid.Maui.Controls.Base 2 | { 3 | public enum PlatformType 4 | { 5 | Desktop, 6 | Mobile, 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Base/SimpleCamera.cs: -------------------------------------------------------------------------------- 1 | using System.Numerics; 2 | 3 | namespace Veldrid.Maui.Controls.Base 4 | { 5 | public class SimpleCamera : BaseCamera 6 | { 7 | private Vector2 _previousMouseTotalDelta; 8 | private Vector2 _currentMouseTotalDelta; 9 | public void UpdatePanPoint(float x, float y) 10 | { 11 | if (_previousMouseTotalDelta == default) 12 | _currentMouseTotalDelta = _previousMouseTotalDelta = new Vector2(x, y); 13 | else 14 | { 15 | _previousMouseTotalDelta = _currentMouseTotalDelta; 16 | _currentMouseTotalDelta = new Vector2(x, y); 17 | } 18 | } 19 | 20 | public override void Update(float deltaSeconds) 21 | { 22 | Vector2 mouseDelta = _currentMouseTotalDelta - _previousMouseTotalDelta; 23 | 24 | Yaw += -mouseDelta.X * 0.01f; 25 | Pitch += -mouseDelta.Y * 0.01f; 26 | Pitch = Clamp(Pitch, -1.55f, 1.55f); 27 | 28 | UpdateViewMatrix(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Handlers/IVeldridView.cs: -------------------------------------------------------------------------------- 1 | using Veldrid.Maui.Controls.Base; 2 | 3 | namespace Veldrid.Maui.Controls.Handlers 4 | { 5 | public interface IVeldridView : IView//, ApplicationWindow 6 | { 7 | //IGPUDrawable Drawable 8 | BaseGpuDrawable Drawable { set; get; } 9 | 10 | /// 11 | /// Set Backend which you want use. 12 | /// On Android, if you don't set it, Veldrid will detect if Vulkan works, if not, use OpenGL. 13 | /// On iOS, if you don't set it, it use Metal, current not support Vulkan, notice Apple have deprecated OpenGL. 14 | /// On Windows, you only use D3D11. 15 | /// 16 | GraphicsBackend Backend { set; get; } 17 | 18 | /// 19 | /// 是否使用像游戏循环一样不断调用 20 | /// 21 | bool AutoReDraw { set; get; } 22 | 23 | GraphicsDeviceOptions? Options { set; get; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Handlers/VeldridViewHandler.Android.cs: -------------------------------------------------------------------------------- 1 | #if __ANDROID__ 2 | using Android.Content; 3 | using Microsoft.Maui.Handlers; 4 | using Veldrid; 5 | using Veldrid.Maui.Controls.Platforms.Android; 6 | 7 | namespace Veldrid.Maui.Controls.Handlers 8 | { 9 | public partial class VeldridViewHandler : ViewHandler 10 | { 11 | protected override VeldridPlatformView CreatePlatformView() 12 | { 13 | GraphicsBackend backend; 14 | if (VirtualView.Backend == default) 15 | backend = GraphicsDevice.IsBackendSupported(GraphicsBackend.Vulkan) ? GraphicsBackend.Vulkan : GraphicsBackend.OpenGLES; 16 | else 17 | backend = VirtualView.Backend; 18 | var view = new VeldridPlatformView(Context); 19 | window = new VeldridPlatformInterface(view, backend); 20 | 21 | return view; 22 | } 23 | 24 | private static void MapDrawable(VeldridViewHandler handler, IVeldridView mauiView) 25 | { 26 | handler.window.Drawable = mauiView.Drawable; 27 | } 28 | 29 | protected override void ConnectHandler(VeldridPlatformView platformView) 30 | { 31 | base.ConnectHandler(platformView); 32 | } 33 | } 34 | } 35 | #endif 36 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Handlers/VeldridViewHandler.Standard.cs: -------------------------------------------------------------------------------- 1 | #if NET && !__IOS__ && !__ANDROID__ && !WINDOWS 2 | using Microsoft.Maui.Handlers; 3 | using System; 4 | 5 | namespace Veldrid.Maui.Controls.Handlers 6 | { 7 | public partial class VeldridViewHandler : ViewHandler 8 | { 9 | protected override object CreatePlatformView() => throw new NotImplementedException(); 10 | 11 | 12 | private static void MapDrawable(VeldridViewHandler arg1, IVeldridView arg2) 13 | { 14 | throw new NotImplementedException(); 15 | } 16 | } 17 | } 18 | #endif -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Handlers/VeldridViewHandler.Windows.cs: -------------------------------------------------------------------------------- 1 | #if WINDOWS 2 | using Microsoft.Maui.Controls; 3 | using Microsoft.Maui.Handlers; 4 | using Microsoft.UI.Xaml; 5 | using Veldrid; 6 | using Veldrid.Maui.Controls.Platforms.Windows; 7 | 8 | namespace Veldrid.Maui.Controls.Handlers 9 | { 10 | public partial class VeldridViewHandler : ViewHandler 11 | { 12 | protected override VeldridPlatformView CreatePlatformView() 13 | { 14 | var view = new VeldridPlatformView(); 15 | window = new VeldridPlatformInterface(view); 16 | return view; 17 | } 18 | 19 | private static void MapDrawable(VeldridViewHandler handler, IVeldridView mauiView) 20 | { 21 | handler.window.Drawable = mauiView.Drawable; 22 | } 23 | 24 | protected override void ConnectHandler(VeldridPlatformView platformView) 25 | { 26 | base.ConnectHandler(platformView); 27 | } 28 | } 29 | } 30 | #endif 31 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Handlers/VeldridViewHandler.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Maui.Handlers; 2 | using Veldrid.Maui.Controls.Base; 3 | 4 | namespace Veldrid.Maui.Controls.Handlers 5 | { 6 | public partial class VeldridViewHandler 7 | { 8 | BaseVeldridPlatformInterface window; 9 | 10 | public static IPropertyMapper Mapper = new PropertyMapper(ViewHandler.ViewMapper) 11 | { 12 | [nameof(IVeldridView.Drawable)] = MapDrawable, 13 | [nameof(IVeldridView.Background)] = MapBackground, 14 | [nameof(IVeldridView.AutoReDraw)] = MapAutoReDraw, 15 | [nameof(IVeldridView.Options)] = MapOptions 16 | }; 17 | 18 | private static void MapBackground(VeldridViewHandler arg1, IVeldridView arg2) 19 | { 20 | //throw new NotImplementedException(); 21 | } 22 | 23 | private static void MapAutoReDraw(VeldridViewHandler handler, IVeldridView mauiView) 24 | { 25 | handler.window.AutoReDraw = mauiView.AutoReDraw; 26 | } 27 | 28 | private static void MapOptions(VeldridViewHandler handler, IVeldridView mauiView) 29 | { 30 | handler.window.Options = mauiView.Options; 31 | } 32 | 33 | public static CommandMapper CommandMapper = new(ViewCommandMapper) 34 | { 35 | }; 36 | 37 | public VeldridViewHandler() : base(Mapper, CommandMapper) 38 | { 39 | } 40 | 41 | public VeldridViewHandler(IPropertyMapper? mapper = null, CommandMapper? commandMapper = null) 42 | : base(mapper ?? Mapper, commandMapper ?? CommandMapper) 43 | { 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Handlers/VeldridViewHandler.iOS.cs: -------------------------------------------------------------------------------- 1 | #if __IOS__ 2 | using Microsoft.Maui.Controls; 3 | using Microsoft.Maui.Handlers; 4 | using UIKit; 5 | using Veldrid; 6 | using Veldrid.Maui.Controls.Platforms.iOS; 7 | 8 | namespace Veldrid.Maui.Controls.Handlers 9 | { 10 | public partial class VeldridViewHandler : ViewHandler 11 | { 12 | protected override VeldridPlatformView CreatePlatformView() 13 | { 14 | var view = new VeldridPlatformView(); 15 | GraphicsBackend backend; 16 | if (VirtualView.Backend == default) 17 | backend = GraphicsBackend.Metal; 18 | else 19 | backend = VirtualView.Backend; 20 | window = new VeldridPlatformInterface(view, backend); 21 | return view; 22 | } 23 | 24 | public override Size GetDesiredSize(double widthConstraint, double heightConstraint) 25 | { 26 | var size = base.GetDesiredSize(widthConstraint, heightConstraint); 27 | return size; 28 | } 29 | 30 | private static void MapDrawable(VeldridViewHandler handler, IVeldridView mauiView) 31 | { 32 | handler.window.Drawable = mauiView.Drawable; 33 | } 34 | 35 | protected override void ConnectHandler(VeldridPlatformView platformView) 36 | { 37 | base.ConnectHandler(platformView); 38 | } 39 | } 40 | } 41 | #endif 42 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Hosts/AppHostBuilderExtensions.cs.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Veldrid.Maui.Controls.Handlers; 7 | 8 | namespace Veldrid.Maui.Controls.Hosts 9 | { 10 | public static class AppHostBuilderExtensions 11 | { 12 | public static MauiAppBuilder UseVeldridView(this MauiAppBuilder builder) 13 | { 14 | builder.ConfigureMauiHandlers(handlers => 15 | { 16 | handlers.AddHandler(typeof(VeldridView), typeof(VeldridViewHandler)); 17 | }); 18 | 19 | return builder; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Platform/Android/ValueAnimator.Android.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | namespace Veldrid.Maui.Controls.Platforms.Android 4 | { 5 | /// 6 | /// https://stackoverflow.com/questions/61594608/ios-equivalent-of-androids-valueanimator 7 | /// 8 | internal class ValueAnimator 9 | { 10 | Action Action { get; set; } 11 | public bool isRunning = false; 12 | public void set(Action action) 13 | { 14 | Action = action; 15 | } 16 | 17 | public void start() 18 | { 19 | isRunning = true; 20 | Task.Factory.StartNew(() => Loop(), TaskCreationOptions.LongRunning); 21 | } 22 | 23 | int frameTime = 1000 / 60;//每秒60帧 24 | private void Loop() 25 | { 26 | while (isRunning) 27 | { 28 | try 29 | { 30 | Thread.Sleep(frameTime); 31 | 32 | update(); 33 | } 34 | catch (Exception e) 35 | { 36 | Debug.WriteLine("Encountered an error while rendering: " + e); 37 | //throw; 38 | } 39 | } 40 | } 41 | 42 | private void update() 43 | { 44 | if (isRunning) 45 | { 46 | Action?.Invoke(); 47 | } 48 | } 49 | 50 | public void cancel() 51 | { 52 | isRunning = false; 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Platform/Android/VeldridPlatformInterface.cs: -------------------------------------------------------------------------------- 1 | using Android.Runtime; 2 | using Android.Views; 3 | using Veldrid.Maui.Controls.Base; 4 | using Veldrid.Utilities; 5 | 6 | namespace Veldrid.Maui.Controls.Platforms.Android 7 | { 8 | public class VeldridPlatformInterface : BaseVeldridPlatformInterface 9 | { 10 | private VeldridPlatformView _view; 11 | 12 | private readonly GraphicsBackend _backend; 13 | 14 | // This is supposed to be a DisposeCollectorResourceFactory but it crashes mono, so change it. 15 | //private DisposeCollectorResourceFactory _resources; 16 | //private ResourceFactory _resources; 17 | 18 | //Android的View在代码中宽高本身使用像素为单位, 无需转换 19 | public override uint Width => (uint)_view.Width; 20 | public override uint Height => (uint)_view.Height; 21 | 22 | public VeldridPlatformInterface(VeldridPlatformView view, GraphicsBackend backend = GraphicsBackend.OpenGLES) 23 | { 24 | PlatformType = PlatformType.Mobile; 25 | 26 | if (!(backend == GraphicsBackend.Vulkan || backend == GraphicsBackend.OpenGLES)) 27 | { 28 | throw new NotSupportedException($"{backend} is not supported on Android."); 29 | } 30 | _backend = backend; 31 | 32 | _view = view; 33 | _view.AndroidSurfaceCreated += CreateGraphicsDevice; 34 | _view.AndroidSurfaceChanged += OnViewSizeChanged; 35 | _view.AndroidSurfaceDestoryed += DestroyGraphicsDevice; 36 | } 37 | 38 | private void DestroyGraphicsDevice() 39 | { 40 | if (_graphicsDevice != null) 41 | { 42 | var tempDevice = _graphicsDevice; 43 | _graphicsDevice = null;//先设置null阻止渲染循环 44 | 45 | InvokeGraphicsDeviceDestroyed(); 46 | tempDevice.WaitForIdle(); 47 | //_resources.DisposeCollector.DisposeAll(); 48 | tempDevice.Dispose(); 49 | } 50 | } 51 | 52 | private void OnViewSizeChanged() 53 | { 54 | if (_graphicsDevice != null) 55 | { 56 | _swapChain.Resize((uint)Width, (uint)Height); 57 | InvokeResized(); 58 | } 59 | } 60 | 61 | private void CreateGraphicsDevice(ISurfaceHolder holder) 62 | { 63 | if (Options == null) 64 | Options = new GraphicsDeviceOptions(false, PixelFormat.R16_UNorm, false, ResourceBindingModel.Improved, true, true); 65 | 66 | if (_backend == GraphicsBackend.Vulkan) 67 | { 68 | SwapchainSource ss = SwapchainSource.CreateAndroidSurface(holder.Surface.Handle, JNIEnv.Handle); 69 | SwapchainDescription sd = new SwapchainDescription( 70 | ss, 71 | (uint)Width, 72 | (uint)Height, 73 | Options.Value.SwapchainDepthFormat, 74 | Options.Value.SyncToVerticalBlank); 75 | 76 | if (_graphicsDevice == null) 77 | { 78 | _graphicsDevice = GraphicsDevice.CreateVulkan(Options.Value, sd); 79 | } 80 | 81 | //_swapChain = GraphicsDevice.ResourceFactory.CreateSwapchain(sd); 82 | _swapChain = _graphicsDevice.MainSwapchain; 83 | } 84 | else 85 | { 86 | SwapchainSource ss = SwapchainSource.CreateAndroidSurface(holder.Surface.Handle, JNIEnv.Handle); 87 | SwapchainDescription sd = new SwapchainDescription( 88 | ss, 89 | (uint)Width, 90 | (uint)Height, 91 | Options.Value.SwapchainDepthFormat, 92 | Options.Value.SyncToVerticalBlank); 93 | _graphicsDevice = GraphicsDevice.CreateOpenGLES(Options.Value, sd); 94 | _swapChain = _graphicsDevice.MainSwapchain; 95 | } 96 | 97 | _resources = new DisposeCollectorResourceFactory(_graphicsDevice.ResourceFactory); 98 | //_resources = _graphicsDevice.ResourceFactory; 99 | InvokeGraphicsDeviceCreated(); 100 | 101 | Animator = new ValueAnimator(); 102 | Animator.set(RenderLoop); 103 | if (AutoReDraw == true) 104 | Animator.start(); 105 | } 106 | 107 | ValueAnimator Animator = null; 108 | bool autoReDraw = false; 109 | public override bool AutoReDraw 110 | { 111 | set 112 | { 113 | if (_graphicsDevice != null)//如果图形设备已经创建,那么动画对象已经创建,只需要判断是否开关 114 | { 115 | if (value == true) 116 | { 117 | Animator.cancel(); 118 | Animator.start(); 119 | } 120 | else 121 | Animator.cancel(); 122 | } 123 | autoReDraw = value; 124 | } 125 | 126 | get 127 | { 128 | return autoReDraw; 129 | } 130 | } 131 | 132 | private void RenderLoop() 133 | { 134 | if (_graphicsDevice != null) InvokeRendering(16); 135 | } 136 | 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Platform/Android/VeldridPlatformView.cs: -------------------------------------------------------------------------------- 1 | using Android.Content; 2 | using Android.Graphics; 3 | using Android.Runtime; 4 | using Android.Views; 5 | using System.Diagnostics; 6 | 7 | namespace Veldrid.Maui.Controls.Platforms.Android 8 | { 9 | public class VeldridPlatformView : SurfaceView, ISurfaceHolderCallback 10 | { 11 | public event Action AndroidSurfaceCreated; 12 | public event Action AndroidSurfaceDestoryed; 13 | public event Action AndroidSurfaceChanged; 14 | 15 | public VeldridPlatformView(Context context):base(context) 16 | { 17 | Holder.AddCallback(this); 18 | } 19 | 20 | public void SurfaceCreated(ISurfaceHolder holder) 21 | { 22 | AndroidSurfaceCreated?.Invoke(holder); 23 | } 24 | 25 | public void SurfaceDestroyed(ISurfaceHolder holder) 26 | { 27 | AndroidSurfaceDestoryed?.Invoke(); 28 | } 29 | 30 | public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height) 31 | { 32 | AndroidSurfaceChanged?.Invoke(); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Platform/README.txt: -------------------------------------------------------------------------------- 1 | Code of iOS and Windows from https://github.com/PhilippeMonteil/Veldrid.Views 2 | Code of Android from https://github.com/slango0513/VeldridFormsSamples -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Platform/Tizen/PlatformClass1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Veldrid.Maui.Controls 4 | { 5 | // All the code in this file is only included on Tizen. 6 | public class PlatformClass1 7 | { 8 | } 9 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Platform/Windows/ValueAnimator.Windows.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.UI.Xaml.Media; 2 | using System.Diagnostics; 3 | 4 | namespace Veldrid.Maui.Controls.Platforms.Windows 5 | { 6 | /// 7 | /// https://stackoverflow.com/questions/61594608/ios-equivalent-of-androids-valueanimator 8 | /// 9 | internal class ValueAnimator 10 | { 11 | Action Action { get; set; } 12 | public bool isRunning = false; 13 | public void set(Action action) 14 | { 15 | Action = action; 16 | } 17 | 18 | public void start() 19 | { 20 | isRunning = true; 21 | CompositionTarget.Rendering += RenderLoop; 22 | } 23 | 24 | private void RenderLoop(object sender, object e) 25 | { 26 | update(); 27 | } 28 | 29 | private void update() 30 | { 31 | if (isRunning) 32 | { 33 | Action?.Invoke(); 34 | } 35 | } 36 | 37 | public void cancel() 38 | { 39 | isRunning = false; 40 | CompositionTarget.Rendering -= RenderLoop; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Platform/Windows/VeldridPlatformInterface.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using Veldrid; 4 | using Veldrid.Utilities; 5 | using Microsoft.UI.Xaml.Controls; 6 | using Microsoft.UI.Xaml.Media; 7 | using Veldrid.Maui.Controls.Base; 8 | 9 | namespace Veldrid.Maui.Controls.Platforms.Windows 10 | { 11 | public sealed partial class VeldridPlatformInterface : 12 | BaseVeldridPlatformInterface 13 | { 14 | public VeldridPlatformView _view; 15 | 16 | public VeldridPlatformInterface(VeldridPlatformView view) 17 | { 18 | _view = view; 19 | _view.CompositionScaleChanged += OnViewScaleChanged; 20 | _view.SizeChanged += OnViewSizeChanged; 21 | 22 | _view.Loaded += OnLoaded; 23 | _view.Unloaded += OnUnloaded; 24 | } 25 | 26 | public PlatformType PlatformType => PlatformType.Desktop; 27 | public override uint Width => (uint)(_view.RenderSize.Width * _view.CompositionScaleX); 28 | public override uint Height => (uint)(_view.RenderSize.Height * _view.CompositionScaleY); 29 | 30 | private void OnUnloaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) 31 | { 32 | DestroyGraphicsDevice(); 33 | } 34 | 35 | private void OnLoaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) 36 | { 37 | CreateGraphicsDevice(); 38 | } 39 | 40 | private void DestroyGraphicsDevice() 41 | { 42 | if (_graphicsDevice != null) 43 | { 44 | var tempDevice = _graphicsDevice; 45 | _graphicsDevice = null;//先设置null阻止渲染循环 46 | 47 | InvokeGraphicsDeviceDestroyed(); 48 | tempDevice.WaitForIdle(); 49 | (_resources as DisposeCollectorResourceFactory).DisposeCollector.DisposeAll(); 50 | tempDevice.Dispose(); 51 | } 52 | } 53 | 54 | private void CreateGraphicsDevice() 55 | { 56 | if(Options == null) 57 | Options = new GraphicsDeviceOptions(false, PixelFormat.R32_Float, true, ResourceBindingModel.Improved); 58 | var logicalDpi = 96.0f * _view.CompositionScaleX; 59 | var renderWidth = _view.RenderSize.Width; 60 | var renderHeight = _view.RenderSize.Height; 61 | _graphicsDevice = GraphicsDevice.CreateD3D11(Options.Value, this._view, renderWidth, renderHeight, logicalDpi); 62 | _resources = new DisposeCollectorResourceFactory(_graphicsDevice.ResourceFactory); 63 | _swapChain = _graphicsDevice.MainSwapchain; 64 | InvokeGraphicsDeviceCreated(); 65 | Animator = new ValueAnimator(); 66 | Animator.set(RenderLoop); 67 | if (AutoReDraw == true) 68 | Animator.start(); 69 | } 70 | 71 | ValueAnimator Animator = null; 72 | bool autoReDraw = false; 73 | public override bool AutoReDraw 74 | { 75 | set 76 | { 77 | if (_graphicsDevice != null)//如果图形设备已经创建,那么动画对象已经创建,只需要判断是否开关 78 | { 79 | if (value == true) 80 | { 81 | Animator.cancel(); 82 | Animator.start(); 83 | } 84 | else 85 | Animator.cancel(); 86 | } 87 | autoReDraw = value; 88 | } 89 | 90 | get 91 | { 92 | return autoReDraw; 93 | } 94 | } 95 | 96 | /// 97 | /// View will still run it. 98 | /// 99 | private void RenderLoop() 100 | { 101 | if (_graphicsDevice != null) 102 | { 103 | try 104 | { 105 | InvokeRendering(16); 106 | } 107 | catch (Exception ex) 108 | { 109 | Debug.WriteLine("Encountered an error while rendering: " + ex); 110 | //throw; 111 | } 112 | } 113 | } 114 | 115 | private void OnViewSizeChanged(object sender, Microsoft.UI.Xaml.SizeChangedEventArgs e) 116 | { 117 | if (_graphicsDevice != null) 118 | { 119 | _swapChain.Resize(Width, Height); 120 | InvokeResized(); 121 | } 122 | } 123 | 124 | private void OnViewScaleChanged(SwapChainPanel sender, object args) 125 | { 126 | if (_graphicsDevice != null) 127 | { 128 | _swapChain.Resize(Width, Height); 129 | InvokeResized(); 130 | } 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Platform/Windows/VeldridPlatformView.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Microsoft.UI.Xaml.Controls; 7 | 8 | namespace Veldrid.Maui.Controls.Platforms.Windows 9 | { 10 | public class VeldridPlatformView : SwapChainPanel 11 | { 12 | public VeldridPlatformView() 13 | { 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Platform/iOSMac/ValueAnimator.iOS.cs: -------------------------------------------------------------------------------- 1 | using CoreAnimation; 2 | using Foundation; 3 | 4 | namespace Veldrid.Maui.Controls.Platforms.iOS 5 | { 6 | /// 7 | /// https://stackoverflow.com/questions/61594608/ios-equivalent-of-androids-valueanimator 8 | /// 9 | internal class ValueAnimator 10 | { 11 | CADisplayLink displayLink; 12 | Action Action { get; set; } 13 | public bool isRunning = false; 14 | public void set(Action action) 15 | { 16 | Action = action; 17 | } 18 | 19 | public void start() 20 | { 21 | isRunning = true; 22 | displayLink = CADisplayLink.Create(update); 23 | displayLink?.AddToRunLoop(NSRunLoop.Current, NSRunLoopMode.Default); 24 | } 25 | 26 | private void update() 27 | { 28 | if (isRunning) 29 | { 30 | Action?.Invoke(); 31 | } 32 | } 33 | 34 | public void cancel() 35 | { 36 | isRunning = false; 37 | this.displayLink?.RemoveFromRunLoop(NSRunLoop.Current, NSRunLoopMode.Default); 38 | this.displayLink = null; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Platform/iOSMac/VeldridPlatformInterface.cs: -------------------------------------------------------------------------------- 1 | using CoreAnimation; 2 | using Foundation; 3 | using Intents; 4 | using System.Diagnostics; 5 | using Veldrid.Maui.Controls.Base; 6 | using Veldrid.Utilities; 7 | 8 | namespace Veldrid.Maui.Controls.Platforms.iOS 9 | { 10 | public class VeldridPlatformInterface : //UIViewController, 11 | BaseVeldridPlatformInterface 12 | { 13 | private VeldridPlatformView _view; 14 | 15 | private readonly GraphicsBackend _backend; 16 | 17 | public override uint Width => (uint)(_view.Frame.Width * DeviceDisplay.Current.MainDisplayInfo.Density); 18 | public override uint Height => (uint)(_view.Frame.Height * DeviceDisplay.Current.MainDisplayInfo.Density); 19 | 20 | public VeldridPlatformInterface(VeldridPlatformView view, GraphicsBackend backend = GraphicsBackend.Metal) 21 | { 22 | PlatformType = PlatformType.Mobile; 23 | 24 | if (!(backend == GraphicsBackend.Metal || backend == GraphicsBackend.OpenGLES || backend == GraphicsBackend.Vulkan)) 25 | throw new NotSupportedException($"Not support {backend} backend on iOS or Maccatalyst."); 26 | _backend = backend; 27 | 28 | _view = view; 29 | _view.ViewLoaded += CreateGraphicsDevice; 30 | _view.SizeChanged += OnViewSizeChanged; 31 | _view.ViewRemoved += DestroyGraphicsDevice; 32 | } 33 | 34 | private void RenderLoop() 35 | { 36 | if (_graphicsDevice != null) 37 | { 38 | try 39 | { 40 | InvokeRendering(16); 41 | } 42 | catch (Exception e) 43 | { 44 | Debug.WriteLine("Encountered an error while rendering: " + e); 45 | //throw; 46 | } 47 | } 48 | } 49 | 50 | private void DestroyGraphicsDevice() 51 | { 52 | if (_graphicsDevice != null) 53 | { 54 | var tempDevice = _graphicsDevice; 55 | _graphicsDevice = null;//先设置null阻止渲染循环 56 | 57 | InvokeGraphicsDeviceDestroyed(); 58 | tempDevice.WaitForIdle(); 59 | (_resources as DisposeCollectorResourceFactory)?.DisposeCollector.DisposeAll(); 60 | tempDevice.Dispose(); 61 | } 62 | } 63 | 64 | private void CreateGraphicsDevice() 65 | { 66 | if (Options == null) 67 | //_options = new GraphicsDeviceOptions(false, null, false, ResourceBindingModel.Improved); 68 | Options = new GraphicsDeviceOptions(false, null, false, ResourceBindingModel.Improved, true, true); 69 | 70 | SwapchainSource ss = SwapchainSource.CreateUIView(_view.Handle); 71 | SwapchainDescription scd = new SwapchainDescription( 72 | ss, 73 | (uint)_view.Frame.Width,//MTLSwapchain内部自动转换成Pixel 74 | (uint)_view.Frame.Height, 75 | PixelFormat.R32_Float, 76 | false); 77 | if (_backend == GraphicsBackend.Metal) 78 | { 79 | //_gd = GraphicsDevice.CreateMetal(_options); 80 | //_sc = _gd.ResourceFactory.CreateSwapchain(ref scd); 81 | _graphicsDevice = GraphicsDevice.CreateMetal(Options.Value, scd); 82 | _swapChain = _graphicsDevice.MainSwapchain; 83 | } 84 | else if (_backend == GraphicsBackend.OpenGLES) 85 | { 86 | _graphicsDevice = GraphicsDevice.CreateOpenGLES(Options.Value, scd); 87 | _swapChain = _graphicsDevice.MainSwapchain; 88 | } 89 | else if (_backend == GraphicsBackend.Vulkan) 90 | { 91 | //need use MoltenVK nuget package 92 | _graphicsDevice = GraphicsDevice.CreateVulkan(Options.Value, scd); 93 | _swapChain = _graphicsDevice.MainSwapchain; 94 | //throw new NotImplementedException("Current not support Vulkan on iOS"); 95 | } 96 | _resources = new DisposeCollectorResourceFactory(_graphicsDevice.ResourceFactory); 97 | InvokeGraphicsDeviceCreated(); 98 | 99 | Animator = new ValueAnimator(); 100 | Animator.set(RenderLoop); 101 | if (AutoReDraw == true) 102 | Animator.start(); 103 | } 104 | 105 | ValueAnimator Animator = null; 106 | bool autoReDraw = false; 107 | public override bool AutoReDraw 108 | { 109 | set 110 | { 111 | if (_graphicsDevice != null)//如果图形设备已经创建,那么动画对象已经创建,只需要判断是否开关 112 | { 113 | if (value == true) 114 | { 115 | Animator.cancel(); 116 | Animator.start(); 117 | } 118 | else 119 | Animator.cancel(); 120 | } 121 | autoReDraw = value; 122 | } 123 | 124 | get 125 | { 126 | return autoReDraw; 127 | } 128 | } 129 | 130 | private void OnViewSizeChanged() 131 | { 132 | if (_graphicsDevice != null) 133 | { 134 | //MTLSwapchain内部自动转换成Pixel 135 | _swapChain.Resize((uint)_view.Frame.Width, (uint)_view.Frame.Height); 136 | InvokeResized(); 137 | } 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Platform/iOSMac/VeldridPlatformView.cs: -------------------------------------------------------------------------------- 1 | using CoreAnimation; 2 | using CoreGraphics; 3 | using UIKit; 4 | namespace Veldrid.Maui.Controls.Platforms.iOS 5 | { 6 | public class VeldridPlatformView : UIView 7 | { 8 | public VeldridPlatformView() 9 | { 10 | this.Layer.MasksToBounds = true; // IMPORTANT 11 | 12 | //this.BackgroundColor = UIColor.Gray; 13 | } 14 | 15 | CGSize oldFrame = CGSize.Empty; 16 | /// 17 | /// 构建GraphicsDevice时大小不能为0, Maui会调用此方法计算UIView的大小,因此在该方法中判断何时大小不为0 18 | /// 19 | /// 20 | /// 21 | public override CGSize SizeThatFits(CGSize size) 22 | { 23 | var result = base.SizeThatFits(size); 24 | if (this.firstTimeLoad && result.Width > 0 && result.Height > 0)//初次有大小 25 | { 26 | ViewLoaded?.Invoke(); 27 | firstTimeLoad = false; 28 | oldFrame = result; 29 | } 30 | else if (result != oldFrame)//大小更新 31 | { 32 | SizeChanged?.Invoke(); 33 | oldFrame = result; 34 | } 35 | return result; 36 | } 37 | 38 | public Action SizeChanged; 39 | public Action ViewLoaded; 40 | public Action ViewRemoved; 41 | bool firstTimeLoad = true; 42 | public override void MovedToWindow() 43 | { 44 | base.MovedToWindow(); 45 | /*if (firstTimeLoad) 46 | { 47 | ViewLoaded?.Invoke(); 48 | firstTimeLoad = false; 49 | } 50 | else*/ 51 | if (!firstTimeLoad) 52 | { 53 | ViewRemoved?.Invoke(); 54 | firstTimeLoad = true; 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/Veldrid.Maui.Controls.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0;net7.0-android;net7.0-ios;net7.0-maccatalyst 5 | $(TargetFrameworks);net7.0-windows10.0.19041.0 6 | 7 | 8 | true 9 | true 10 | enable 11 | 12 | 14.2 13 | 14.0 14 | 21.0 15 | 10.0.17763.0 16 | 10.0.17763.0 17 | 6.5 18 | True 19 | 20 | 21 | 22 | 4.9.0-beta8 23 | True 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Controls/VeldridView.cs: -------------------------------------------------------------------------------- 1 | using Veldrid.Maui.Controls.Base; 2 | using Veldrid.Maui.Controls.Handlers; 3 | 4 | namespace Veldrid.Maui.Controls 5 | { 6 | // All the code in this file is included in all platforms. 7 | public class VeldridView : View, IVeldridView 8 | { 9 | public static readonly BindableProperty DrawableProperty = 10 | BindableProperty.Create(nameof(Drawable), typeof(BaseGpuDrawable), typeof(VeldridView), null); 11 | public static readonly BindableProperty BackendProperty = 12 | BindableProperty.Create(nameof(Backend), typeof(GraphicsBackend), typeof(VeldridView), null); 13 | public static readonly BindableProperty AutoReDrawProperty = 14 | BindableProperty.Create(nameof(AutoReDraw), typeof(bool), typeof(VeldridView), false); 15 | public static readonly BindableProperty OptionsProperty = 16 | BindableProperty.Create(nameof(Options), typeof(GraphicsDeviceOptions?), typeof(VeldridView), null); 17 | 18 | public BaseGpuDrawable Drawable 19 | { 20 | set 21 | { 22 | SetValue(DrawableProperty, value); 23 | } 24 | get { return (BaseGpuDrawable)GetValue(DrawableProperty); } 25 | } 26 | 27 | #if WINDOWS 28 | /// 29 | /// Windows中运行时提示SwrapChain不能设置背景 30 | /// 31 | public new Color Background 32 | { 33 | set 34 | { 35 | SetValue(DrawableProperty, value); 36 | } 37 | get { return (Color)GetValue(BackgroundProperty); } 38 | } 39 | #endif 40 | 41 | public GraphicsBackend Backend 42 | { 43 | set 44 | { 45 | SetValue(BackendProperty, value); 46 | } 47 | get { return (GraphicsBackend)GetValue(BackendProperty); } 48 | } 49 | 50 | public bool AutoReDraw 51 | { 52 | set 53 | { 54 | SetValue(AutoReDrawProperty, value); 55 | } 56 | get { return (bool)GetValue(AutoReDrawProperty); } 57 | } 58 | 59 | public GraphicsDeviceOptions? Options 60 | { 61 | set 62 | { 63 | SetValue(OptionsProperty, value); 64 | } 65 | get { return (GraphicsDeviceOptions?)GetValue(OptionsProperty); } 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/AnimatedMesh/AnimatedVertex.cs: -------------------------------------------------------------------------------- 1 | using System.Numerics; 2 | 3 | namespace Veldrid.Maui.Samples.Core.AnimatedMesh 4 | { 5 | public unsafe struct AnimatedVertex 6 | { 7 | public Vector3 Position; 8 | public Vector2 UV; 9 | public Vector4 BoneWeights; 10 | public UInt4 BoneIndices; 11 | 12 | public void AddBone(uint id, float weight) 13 | { 14 | if (BoneWeights.X == 0) 15 | { 16 | BoneWeights.X = weight; 17 | BoneIndices.X = id; 18 | } 19 | else if (BoneWeights.Y == 0) 20 | { 21 | BoneWeights.Y = weight; 22 | BoneIndices.Y = id; 23 | } 24 | else if (BoneWeights.Z == 0) 25 | { 26 | BoneWeights.Z = weight; 27 | BoneIndices.Z = id; 28 | } 29 | else if (BoneWeights.W == 0) 30 | { 31 | BoneWeights.W = weight; 32 | BoneIndices.W = id; 33 | } 34 | } 35 | } 36 | 37 | public struct UInt4 38 | { 39 | public uint X, Y, Z, W; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/AnimatedMesh/Assets/goblin_bc3_unorm.ktx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/AnimatedMesh/Assets/goblin_bc3_unorm.ktx -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/AnimatedMesh/BoneAnimInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Numerics; 2 | using System.Runtime.CompilerServices; 3 | 4 | namespace Veldrid.Maui.Samples.Core.AnimatedMesh 5 | { 6 | public unsafe struct BoneAnimInfo 7 | { 8 | public Matrix4x4[] BonesTransformations; 9 | 10 | public Blittable GetBlittable() 11 | { 12 | Blittable b; 13 | fixed (Matrix4x4* ptr = BonesTransformations) 14 | { 15 | Unsafe.CopyBlock(&b, ptr, 64 * 64); 16 | } 17 | 18 | return b; 19 | } 20 | 21 | public struct Blittable 22 | { 23 | public fixed float BoneData[16 * 64]; 24 | } 25 | 26 | internal static BoneAnimInfo New() 27 | { 28 | return new BoneAnimInfo() { BonesTransformations = new Matrix4x4[64] }; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/AnimatedMesh/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.Numerics; 2 | using System.Runtime.CompilerServices; 3 | 4 | namespace Veldrid.Maui.Samples.Core.AnimatedMesh 5 | { 6 | internal unsafe static class Extensions 7 | { 8 | public static Matrix4x4 ToSystemMatrix(this Assimp.Matrix4x4 mat) 9 | { 10 | return Unsafe.Read(&mat); 11 | } 12 | 13 | public static Matrix4x4 ToSystemMatrixTransposed(this Assimp.Matrix4x4 mat) 14 | { 15 | return Matrix4x4.Transpose(Unsafe.Read(&mat)); 16 | } 17 | 18 | 19 | public static Quaternion ToSystemQuaternion(this Assimp.Quaternion quat) 20 | { 21 | return new Quaternion(quat.X, quat.Y, quat.Z, quat.W); 22 | } 23 | 24 | public static Vector3 ToSystemVector3(this Assimp.Vector3D v3) 25 | { 26 | return new Vector3(v3.X, v3.Y, v3.Z); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/AnimatedMesh/ProcessedAssets/goblin.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/AnimatedMesh/ProcessedAssets/goblin.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/AnimatedMesh/ProcessedAssets/goblin_bc3_unorm.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/AnimatedMesh/ProcessedAssets/goblin_bc3_unorm.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/ComputeParticles/BaseGpuDrawableExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Xml.Linq; 3 | using Veldrid.Maui.Controls.Base; 4 | 5 | namespace Veldrid.Maui.Samples.Core.ComputeParticles 6 | { 7 | internal static class BaseGpuDrawableExtension 8 | { 9 | public static string ReadEmbedAssetPath(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 10 | { 11 | if (type == null) 12 | { 13 | Assembly assembly = Assembly.GetExecutingAssembly(); 14 | List resourceNames = new List(assembly.GetManifestResourceNames()); 15 | resourcePath = resourcePath.Replace(@"/", "."); 16 | resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath)); 17 | } 18 | else 19 | { 20 | List resourceNames = new List(type.Assembly.GetManifestResourceNames()); 21 | resourcePath = resourcePath.Replace(@"/", "."); 22 | resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath)); 23 | } 24 | 25 | if (resourcePath == null) 26 | throw new FileNotFoundException("Resource not found"); 27 | return resourcePath; 28 | } 29 | 30 | public static byte[] ReadEmbedAsset(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 31 | { 32 | resourcePath = ReadEmbedAssetPath(drawable, resourcePath); 33 | return drawable.ReadEmbeddedAssetBytes(resourcePath); 34 | } 35 | 36 | public static Stream ReadEmbedAssetStream(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 37 | { 38 | var bytes = ReadEmbedAsset(drawable, resourcePath); 39 | MemoryStream destination = new MemoryStream(bytes); 40 | return destination; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/ComputeParticles/Shaders/Compute.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | #define PARTICLE_COUNT 1024 4 | 5 | struct ParticleInfo 6 | { 7 | vec2 Position; 8 | vec2 Velocity; 9 | vec4 Color; 10 | }; 11 | 12 | layout(std140, set = 0, binding = 0) buffer ParticlesBuffer 13 | { 14 | ParticleInfo Particles[]; 15 | }; 16 | 17 | layout(set = 1, binding = 0) uniform ScreenSizeBuffer 18 | { 19 | float ScreenWidth; 20 | float ScreenHeight; 21 | vec2 Padding_; 22 | }; 23 | 24 | layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; 25 | 26 | void main() 27 | { 28 | uint index = gl_GlobalInvocationID.x; 29 | if (index > PARTICLE_COUNT) 30 | { 31 | return; 32 | } 33 | 34 | vec2 pos = Particles[index].Position; 35 | vec2 vel = Particles[index].Velocity; 36 | 37 | vec2 newPos = pos + vel; 38 | vec2 newVel = vel; 39 | if (newPos.x > ScreenWidth) 40 | { 41 | newPos.x -= (newPos.x - ScreenWidth); 42 | newVel.x *= -1; 43 | } 44 | if (newPos.x < 0) 45 | { 46 | newPos.x *= -1; 47 | newVel.x *= -1; 48 | } 49 | if (newPos.y > ScreenHeight) 50 | { 51 | newPos.y -= (newPos.y - ScreenHeight); 52 | newVel.y *= -1; 53 | } 54 | if (newPos.y < 0) 55 | { 56 | newPos.y = -newPos.y; 57 | newVel.y *= -1; 58 | } 59 | 60 | Particles[index].Position = newPos; 61 | Particles[index].Velocity = newVel; 62 | } 63 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/ComputeParticles/Shaders/Fragment.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout (location = 0) in vec4 fsin_color; 4 | layout (location = 0) out vec4 fsout_color; 5 | 6 | void main() 7 | { 8 | fsout_color = fsin_color; 9 | } 10 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/ComputeParticles/Shaders/Vertex.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | struct ParticleInfo 4 | { 5 | vec2 Position; 6 | vec2 Velocity; 7 | vec4 Color; 8 | }; 9 | 10 | layout(std140, set = 0, binding = 0) readonly buffer ParticlesBuffer 11 | { 12 | ParticleInfo Particles[]; 13 | }; 14 | 15 | layout(set = 1, binding = 0) uniform ScreenSizeBuffer 16 | { 17 | float ScreenWidth; 18 | float ScreenHeight; 19 | vec2 Padding_; 20 | }; 21 | 22 | layout (location = 0) out vec4 fsin_color; 23 | 24 | 25 | 26 | void main() 27 | { 28 | gl_PointSize = 1; 29 | gl_Position = vec4(Particles[gl_VertexIndex].Position / vec2(ScreenWidth, ScreenHeight), 0, 1); 30 | gl_Position.xy = 2 * (gl_Position.xy - vec2(0.5, 0.5)); 31 | fsin_color = Particles[gl_VertexIndex].Color; 32 | } 33 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/ComputeTexture/Shaders/Compute.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(set = 0, binding = 1) uniform ScreenSizeBuffer 4 | { 5 | float ScreenWidth; 6 | float ScreenHeight; 7 | vec2 Padding_; 8 | }; 9 | 10 | layout(set = 0, binding = 2) uniform ShiftBuffer 11 | { 12 | float RShift; 13 | float GShift; 14 | float BShift; 15 | float Padding1_; 16 | }; 17 | 18 | layout(set = 0, binding = 0, rgba32f) uniform image2D Tex; 19 | 20 | layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in; 21 | 22 | void main() 23 | { 24 | float x = (gl_GlobalInvocationID.x + RShift); 25 | float y = (gl_GlobalInvocationID.y + GShift); 26 | 27 | imageStore(Tex, ivec2(gl_GlobalInvocationID.xy), vec4(x / ScreenWidth, y / ScreenHeight, BShift, 1)); 28 | } 29 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/ComputeTexture/Shaders/Fragment.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(set = 0, binding = 0) uniform texture2D Tex; 4 | layout(set = 0, binding = 1) uniform texture2D Tex11; 5 | layout(set = 0, binding = 2) uniform texture2D Tex22; 6 | layout(set = 0, binding = 3) uniform sampler SS; 7 | 8 | layout(location = 0) in vec2 fsin_TexCoords; 9 | layout(location = 0) out vec4 OutColor; 10 | 11 | void main() 12 | { 13 | OutColor = texture(sampler2D(Tex, SS), fsin_TexCoords) + texture(sampler2D(Tex11, SS), fsin_TexCoords) * .01 + texture(sampler2D(Tex22, SS), fsin_TexCoords) * .01; 14 | } 15 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/ComputeTexture/Shaders/Vertex.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout (location = 0) in vec2 Position; 4 | layout (location = 1) in vec2 TexCoords; 5 | layout (location = 0) out vec2 fsin_TexCoords; 6 | 7 | void main() 8 | { 9 | fsin_TexCoords = TexCoords; 10 | gl_Position = vec4(Position, 0, 1); 11 | } 12 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/GettingStarted/Assets/OpenSans-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/GettingStarted/Assets/OpenSans-Regular.ttf -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/GettingStarted/BaseGpuDrawableExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Xml.Linq; 3 | using Veldrid.Maui.Controls.Base; 4 | 5 | namespace Veldrid.Maui.Samples.Core.GettingStarted 6 | { 7 | internal static class BaseGpuDrawableExtension 8 | { 9 | public static string ReadEmbedAssetPath(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 10 | { 11 | if (type == null) 12 | { 13 | Assembly assembly = Assembly.GetExecutingAssembly(); 14 | List resourceNames = new List(assembly.GetManifestResourceNames()); 15 | resourcePath = resourcePath.Replace(@"/", "."); 16 | resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath)); 17 | } 18 | else 19 | { 20 | List resourceNames = new List(type.Assembly.GetManifestResourceNames()); 21 | resourcePath = resourcePath.Replace(@"/", "."); 22 | resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath)); 23 | } 24 | 25 | if (resourcePath == null) 26 | throw new FileNotFoundException("Resource not found"); 27 | return resourcePath; 28 | } 29 | 30 | public static byte[] ReadEmbedAsset(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 31 | { 32 | resourcePath = ReadEmbedAssetPath(drawable, resourcePath); 33 | return drawable.ReadEmbeddedAssetBytes(resourcePath); 34 | } 35 | 36 | public static Stream ReadEmbedAssetStream(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 37 | { 38 | var bytes = ReadEmbedAsset(drawable, resourcePath); 39 | MemoryStream destination = new MemoryStream(bytes); 40 | return destination; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/GettingStarted/spirvFragmentCode.cs: -------------------------------------------------------------------------------- 1 | namespace GettingStarted 2 | { 3 | partial class Program 4 | { 5 | public static byte[] spirvFragmentCode = 6 | { 7 | 0x03, 0x02, 0x23, 0x07, 0x00, 0x06, 0x01, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x0d, 0x00, 0x00, 0x00, // ..#............. 8 | 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, // ................ 9 | 0x01, 0x00, 0x00, 0x00, 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30, // ....GLSL.std.450 10 | 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ................ 11 | 0x0f, 0x00, 0x07, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, // ............main 12 | 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x10, 0x00, 0x03, 0x00, // ................ 13 | 0x04, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, // ................ 14 | 0xc2, 0x01, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, // ............main 15 | 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, 0x66, 0x73, 0x6f, 0x75, // ............fsou 16 | 0x74, 0x5f, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x05, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, // t_Color......... 17 | 0x66, 0x73, 0x69, 0x6e, 0x5f, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, // fsin_Color..G... 18 | 0x09, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, // ............G... 19 | 0x0b, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, // ................ 20 | 0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // ....!........... 21 | 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, // ........ ....... 22 | 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, // ............ ... 23 | 0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, // ............;... 24 | 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, // ............ ... 25 | 0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, // ............;... 26 | 0x0a, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, // ............6... 27 | 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // ................ 28 | 0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, // ........=....... 29 | 0x0c, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x09, 0x00, 0x00, 0x00, // ........>....... 30 | 0x0c, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00 // ........8... 31 | }; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Headless/BaseGpuDrawableExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Xml.Linq; 3 | using Veldrid.Maui.Controls.Base; 4 | 5 | namespace Veldrid.Maui.Samples.Core.Headless 6 | { 7 | internal static class BaseGpuDrawableExtension 8 | { 9 | public static string ReadEmbedAssetPath(this HeaderlessTextures drawable, string resourcePath = "foler.fileName.extention", Type type = null) 10 | { 11 | if (type == null) 12 | { 13 | Assembly assembly = Assembly.GetExecutingAssembly(); 14 | List resourceNames = new List(assembly.GetManifestResourceNames()); 15 | resourcePath = resourcePath.Replace(@"/", "."); 16 | resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath)); 17 | } 18 | else 19 | { 20 | List resourceNames = new List(type.Assembly.GetManifestResourceNames()); 21 | resourcePath = resourcePath.Replace(@"/", "."); 22 | resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath)); 23 | } 24 | 25 | if (resourcePath == null) 26 | throw new FileNotFoundException("Resource not found"); 27 | return resourcePath; 28 | } 29 | 30 | public static byte[] ReadEmbedAsset(this HeaderlessTextures drawable, string resourcePath = "foler.fileName.extention", Type type = null) 31 | { 32 | resourcePath = ReadEmbedAssetPath(drawable, resourcePath); 33 | return drawable.ReadEmbeddedAssetBytes(resourcePath); 34 | } 35 | 36 | public static Stream ReadEmbedAssetStream(this HeaderlessTextures drawable, string resourcePath = "foler.fileName.extention", Type type = null) 37 | { 38 | var bytes = ReadEmbedAsset(drawable, resourcePath); 39 | MemoryStream destination = new MemoryStream(bytes); 40 | return destination; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Headless/HeaderlessGraphicsDevice.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Veldrid.Maui.Samples.Core.Headless 9 | { 10 | internal class HeaderlessGraphicsDevice 11 | { 12 | #region Constructors 13 | 14 | /// 15 | /// Initialize using Vulkan drivers 16 | /// 17 | /// New render 18 | public static GraphicsDevice InitFromVulkan(bool invertBGR = false) 19 | { 20 | var options = new GraphicsDeviceOptions(true, null, false, ResourceBindingModel.Improved, true, true); 21 | 22 | var gd = GraphicsDevice.CreateVulkan(options); 23 | return gd; 24 | } 25 | 26 | /// 27 | /// Initialize using Direct3D 11 drivers 28 | /// 29 | /// New render 30 | public static GraphicsDevice InitFromD3D11(bool invertBGR = false) 31 | { 32 | var options = new GraphicsDeviceOptions(true, null, false, ResourceBindingModel.Improved, true, true); 33 | 34 | var gd = GraphicsDevice.CreateD3D11(options); 35 | return gd; 36 | } 37 | 38 | /// 39 | /// Initialize using Metal drivers 40 | /// 41 | /// Provide a MetalKit View handle 42 | /// Metal based render 43 | public static GraphicsDevice InitFromMetal(IntPtr handle) 44 | { 45 | try 46 | { 47 | var gd = GraphicsDevice.CreateMetal(new GraphicsDeviceOptions(), new SwapchainDescription(SwapchainSource.CreateUIView(handle), 20, 20, null, false)); 48 | gd.ResourceFactory.CreateSwapchain(new SwapchainDescription(SwapchainSource.CreateUIView(handle), 20, 20, null, false)).Resize(20, 20); 49 | gd.WaitForIdle(); 50 | 51 | return gd; 52 | } 53 | catch (Exception ex) 54 | { 55 | Debug.WriteLine(ex); 56 | } 57 | return null; 58 | } 59 | 60 | public static GraphicsDevice InitFromMetal() 61 | { 62 | try 63 | { 64 | #if IOS || MACCATALYST 65 | //GPU won't always load without these 66 | Veldrid.MetalBindings.MTLDevice.MTLCreateSystemDefaultDevice(); 67 | Metal.MTLDevice.SystemDefault.Dispose(); 68 | 69 | SwapchainSource scs = SwapchainSource.CreateUIView(new UIView().Handle);//Apparently necessary to not native crash when creating Color buffer on A10 processors(A12 won't need) 70 | //SwapchainSource scs = SwapchainSource.CreateUIView(UIApplication.SharedApplication.KeyWindow.RootViewController.View.Handle);//Apparently necessary to not native crash when creating Color buffer on A10 processors(A12 won't need); 71 | 72 | var gd = GraphicsDevice.CreateMetal(new GraphicsDeviceOptions(), new SwapchainDescription(scs, 20, 20, null, false)); 73 | 74 | gd.WaitForIdle(); 75 | 76 | gd.ResizeMainWindow(270, 800); 77 | 78 | return gd; 79 | #endif 80 | } 81 | catch (Exception ex) 82 | { 83 | Debug.WriteLine(ex); 84 | } 85 | return null; 86 | } 87 | 88 | static GraphicsDevice GraphicsDevice; 89 | public static GraphicsDevice Init() 90 | { 91 | //if (GraphicsDevice == null) 92 | { 93 | if (OperatingSystem.IsWindows()) 94 | { 95 | if (GraphicsDevice.IsBackendSupported(GraphicsBackend.Direct3D11)) 96 | { 97 | GraphicsDevice = InitFromD3D11();//bug 98 | } 99 | else if (GraphicsDevice.IsBackendSupported(GraphicsBackend.Vulkan)) 100 | { 101 | GraphicsDevice = InitFromVulkan();//winui3 can use it if headless 102 | } 103 | } 104 | else if (OperatingSystem.IsAndroid() || OperatingSystem.IsMacOS()) 105 | { 106 | if (GraphicsDevice.IsBackendSupported(GraphicsBackend.Vulkan)) 107 | { 108 | GraphicsDevice = InitFromVulkan(); 109 | } 110 | } 111 | else if (OperatingSystem.IsIOS() || OperatingSystem.IsMacCatalyst()) 112 | { 113 | if (GraphicsDevice.IsBackendSupported(GraphicsBackend.Metal)) 114 | { 115 | GraphicsDevice = InitFromMetal(); 116 | } 117 | else if (GraphicsDevice.IsBackendSupported(GraphicsBackend.Vulkan)) 118 | { 119 | GraphicsDevice = InitFromVulkan(); 120 | } 121 | } 122 | } 123 | if (GraphicsDevice != null) 124 | return GraphicsDevice; 125 | throw new NotSupportedException("No supported GPU device found for auto"); 126 | } 127 | #endregion 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Assets/lavaplanet_bc3_unorm.ktx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Assets/lavaplanet_bc3_unorm.ktx -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Assets/lavaplanet_etc2_unorm.ktx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Assets/lavaplanet_etc2_unorm.ktx -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Assets/texturearray_rocks_bc3_unorm.ktx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Assets/texturearray_rocks_bc3_unorm.ktx -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Assets/texturearray_rocks_etc2_unorm.ktx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Assets/texturearray_rocks_etc2_unorm.ktx -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/lavaplanet_bc3_unorm.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/lavaplanet_bc3_unorm.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/lavaplanet_etc2_unorm.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/lavaplanet_etc2_unorm.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/rock01.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/rock01.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/sphere.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/sphere.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/texturearray_rocks_bc3_unorm.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/texturearray_rocks_bc3_unorm.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/texturearray_rocks_etc2_unorm.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/ProcessedAssets/texturearray_rocks_etc2_unorm.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Shaders/Instance-fragment.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(set = 0, binding = 0) uniform LightInfo 4 | { 5 | vec3 LightDirection; 6 | float padding0; 7 | vec3 CameraPosition; 8 | float padding1; 9 | }; 10 | 11 | layout(set = 1, binding = 0) uniform texture2DArray Tex; 12 | layout(set = 1, binding = 1) uniform sampler Samp; 13 | 14 | layout(location = 0) in vec3 fsin_Position_WorldSpace; 15 | layout(location = 1) in vec3 fsin_Normal; 16 | layout(location = 2) in vec3 fsin_TexCoord; 17 | 18 | layout(location = 0) out vec4 outputColor; 19 | 20 | void main() 21 | { 22 | vec4 texColor = texture(sampler2DArray(Tex, Samp), fsin_TexCoord); 23 | 24 | float diffuseIntensity = clamp(dot(fsin_Normal, -LightDirection), 0, 1); 25 | vec4 diffuseColor = texColor * diffuseIntensity; 26 | 27 | // Specular color 28 | vec4 specColor = vec4(0, 0, 0, 0); 29 | vec3 lightColor = vec3(1, 1, 1); 30 | float specPower = 5.0f; 31 | float specIntensity = 0.3f; 32 | vec3 vertexToEye = -normalize(fsin_Position_WorldSpace - CameraPosition); 33 | vec3 lightReflect = normalize(reflect(LightDirection, fsin_Normal)); 34 | float specularFactor = dot(vertexToEye, lightReflect); 35 | if (specularFactor > 0) 36 | { 37 | specularFactor = pow(abs(specularFactor), specPower); 38 | specColor = vec4(lightColor * specIntensity * specularFactor, 1.0f) * texColor; 39 | } 40 | 41 | outputColor = diffuseColor + specColor; 42 | } 43 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Shaders/Instance-vertex.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | #extension GL_ARB_separate_shader_objects : enable 3 | #extension GL_ARB_shading_language_420pack : enable 4 | 5 | layout(set = 0, binding = 1) uniform ProjView 6 | { 7 | mat4 View; 8 | mat4 Proj; 9 | }; 10 | 11 | layout(set = 0, binding = 2) uniform RotationInfo 12 | { 13 | float LocalRotation; 14 | float GlobalRotation; 15 | vec2 padding0; 16 | }; 17 | 18 | layout(location = 0) in vec3 Position; 19 | layout(location = 1) in vec3 Normal; 20 | layout(location = 2) in vec2 TexCoord; 21 | layout(location = 3) in vec3 InstancePosition; 22 | layout(location = 4) in vec3 InstanceRotation; 23 | layout(location = 5) in vec3 InstanceScale; 24 | layout(location = 6) in int InstanceTexArrayIndex; 25 | 26 | layout(location = 0) out vec3 fsin_Position_WorldSpace; 27 | layout(location = 1) out vec3 fsin_Normal; 28 | layout(location = 2) out vec3 fsin_TexCoord; 29 | 30 | void main() 31 | { 32 | float cosX = cos(InstanceRotation.x); 33 | float sinX = sin(InstanceRotation.x); 34 | mat3 instanceRotX = mat3( 35 | 1, 0, 0, 36 | 0, cosX, -sinX, 37 | 0, sinX, cosX); 38 | 39 | float cosY = cos(InstanceRotation.y + LocalRotation); 40 | float sinY = sin(InstanceRotation.y + LocalRotation); 41 | mat3 instanceRotY = mat3( 42 | cosY, 0, sinY, 43 | 0, 1, 0, 44 | -sinY, 0, cosY); 45 | 46 | float cosZ = cos(InstanceRotation.z); 47 | float sinZ = sin(InstanceRotation.z); 48 | mat3 instanceRotZ =mat3( 49 | cosZ, -sinZ, 0, 50 | sinZ, cosZ, 0, 51 | 0, 0, 1); 52 | 53 | mat3 instanceRotFull = instanceRotZ * instanceRotY * instanceRotZ; 54 | mat3 scalingMat = mat3(InstanceScale.x, 0, 0, 0, InstanceScale.y, 0, 0, 0, InstanceScale.z); 55 | 56 | float globalCos = cos(-GlobalRotation); 57 | float globalSin = sin(-GlobalRotation); 58 | 59 | mat3 globalRotMat = mat3( 60 | globalCos, 0, globalSin, 61 | 0, 1, 0, 62 | -globalSin, 0, globalCos); 63 | 64 | vec3 transformedPos = (scalingMat * instanceRotFull * Position) + InstancePosition; 65 | transformedPos = globalRotMat * transformedPos; 66 | vec4 pos = vec4(transformedPos, 1); 67 | fsin_Position_WorldSpace = transformedPos; 68 | gl_Position = Proj * View * pos; 69 | fsin_Normal = normalize(globalRotMat * instanceRotFull * Normal); 70 | fsin_TexCoord = vec3(TexCoord, InstanceTexArrayIndex); 71 | } 72 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Shaders/Planet-fragment.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(set = 0, binding = 0) uniform LightInfo 4 | { 5 | vec3 LightDirection; 6 | float padding0; 7 | vec3 CameraPosition; 8 | float padding1; 9 | }; 10 | 11 | layout(set = 1, binding = 0) uniform texture2D Tex; 12 | layout(set = 1, binding = 1) uniform sampler Samp; 13 | 14 | layout(location = 0) in vec3 fsin_Position_WorldSpace; 15 | layout(location = 1) in vec3 fsin_Normal; 16 | layout(location = 2) in vec2 fsin_TexCoord; 17 | 18 | layout(location = 0) out vec4 outputColor; 19 | 20 | void main() 21 | { 22 | vec4 texColor = texture(sampler2D(Tex, Samp), fsin_TexCoord); 23 | 24 | float diffuseIntensity = clamp(dot(fsin_Normal, -LightDirection), 0, 1); 25 | vec4 diffuseColor = texColor * diffuseIntensity; 26 | 27 | // Specular color 28 | vec4 specColor = vec4(0, 0, 0, 0); 29 | vec3 lightColor = vec3(1, 1, 1); 30 | float specPower = 5.0f; 31 | float specIntensity = 0.3f; 32 | vec3 vertexToEye = -normalize(fsin_Position_WorldSpace - CameraPosition); 33 | vec3 lightReflect = normalize(reflect(LightDirection, fsin_Normal)); 34 | float specularFactor = dot(vertexToEye, lightReflect); 35 | if (specularFactor > 0) 36 | { 37 | specularFactor = pow(abs(specularFactor), specPower); 38 | specColor = vec4(lightColor * specIntensity * specularFactor, 1.0f) * texColor; 39 | } 40 | 41 | outputColor = diffuseColor + specColor; 42 | } 43 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Shaders/Planet-vertex.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(set = 0, binding = 1) uniform ProjView 4 | { 5 | mat4 View; 6 | mat4 Proj; 7 | }; 8 | 9 | layout(location = 0) in vec3 Position; 10 | layout(location = 1) in vec3 Normal; 11 | layout(location = 2) in vec2 TexCoord; 12 | 13 | layout(location = 0) out vec3 fsin_Position_WorldSpace; 14 | layout(location = 1) out vec3 fsin_Normal; 15 | layout(location = 2) out vec2 fsin_TexCoord; 16 | 17 | void main() 18 | { 19 | fsin_Position_WorldSpace = Position; 20 | vec4 pos = vec4(Position, 1); 21 | gl_Position = Proj * View * pos; 22 | fsin_Normal = Normal; 23 | fsin_TexCoord = TexCoord * vec2(10, 6); 24 | } 25 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Shaders/Starfield-fragment.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | #define HASHSCALE3 vec3(443.897, 441.423, 437.195) 4 | #define STARFREQUENCY 0.01 5 | 6 | layout(set = 0, binding = 0) uniform InvCameraInfo 7 | { 8 | mat4 InvProj; 9 | mat4 InvView; 10 | }; 11 | 12 | layout(location = 0) in vec4 fsin_ClipPos; 13 | layout(location = 1) in vec3 fsin_TexCoord; 14 | 15 | layout(location = 0) out vec4 outputColor; 16 | 17 | // Hash function by Dave Hoskins (https://www.shadertoy.com/view/4djSRW) 18 | float hash33(vec3 p3) 19 | { 20 | p3 = fract(p3 * HASHSCALE3); 21 | p3 += dot(p3, p3.yxz + vec3(19.19, 19.19, 19.19)); 22 | return fract((p3.x + p3.y) * p3.z + (p3.x + p3.z) * p3.y + (p3.y + p3.z) * p3.x); 23 | } 24 | 25 | vec3 starField(vec3 pos) 26 | { 27 | vec3 color = vec3(0, 0, 0); 28 | float threshhold = (1.0 - STARFREQUENCY); 29 | float rnd = hash33(pos); 30 | if (rnd >= threshhold) 31 | { 32 | float starCol = pow(abs((rnd - threshhold) / (1.0 - threshhold)), 16.0); 33 | color += vec3(starCol, starCol, starCol); 34 | } 35 | return color; 36 | } 37 | 38 | void main() 39 | { 40 | // View Coordinates 41 | vec4 viewCoords = InvProj * fsin_ClipPos; 42 | viewCoords.z = -1.0f; 43 | viewCoords.w = 0.0f; 44 | 45 | vec3 worldDirection = (InvView * viewCoords).xyz; 46 | worldDirection = normalize(worldDirection); 47 | 48 | worldDirection = floor(worldDirection * 700) / 700; 49 | 50 | outputColor = vec4(starField(worldDirection), 1.0); 51 | } 52 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Instancing/Shaders/Starfield-vertex.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(location = 0) out vec4 fsin_ClipPos; 4 | layout(location = 1) out vec3 fsin_TexCoord; 5 | 6 | void main() 7 | { 8 | fsin_TexCoord = vec3((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2, gl_VertexIndex & 2); 9 | gl_Position = vec4(fsin_TexCoord.xy * 2.0f - 1.0f, 0.0f, 1.0f); 10 | fsin_ClipPos = gl_Position; 11 | } 12 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/Images/awesomeface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/Images/awesomeface.png -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/Images/container.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/Images/container.jpg -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/Images/wall.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/Images/wall.jpg -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/ProcessedImages/awesomeface.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/ProcessedImages/awesomeface.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/ProcessedImages/container.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/ProcessedImages/container.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/ProcessedImages/wall.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/Assets/ProcessedImages/wall.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/LearnOpenGL/BaseGpuDrawableExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Xml.Linq; 3 | using Veldrid.Maui.Controls.Base; 4 | 5 | namespace Veldrid.Maui.Samples.Core.LearnOpenGL 6 | { 7 | internal static class BaseGpuDrawableExtension 8 | { 9 | public static string ReadEmbedAssetPath(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 10 | { 11 | if (type == null) 12 | { 13 | Assembly assembly = Assembly.GetExecutingAssembly(); 14 | List resourceNames = new List(assembly.GetManifestResourceNames()); 15 | resourcePath = resourcePath.Replace(@"/", "."); 16 | resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath)); 17 | } 18 | else 19 | { 20 | List resourceNames = new List(type.Assembly.GetManifestResourceNames()); 21 | resourcePath = resourcePath.Replace(@"/", "."); 22 | resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath)); 23 | } 24 | 25 | if (resourcePath == null) 26 | throw new FileNotFoundException("Resource not found"); 27 | return resourcePath; 28 | } 29 | 30 | public static byte[] ReadEmbedAsset(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 31 | { 32 | resourcePath = ReadEmbedAssetPath(drawable, resourcePath); 33 | return drawable.ReadEmbeddedAssetBytes(resourcePath); 34 | } 35 | 36 | public static Stream ReadEmbedAssetStream(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 37 | { 38 | var bytes = ReadEmbedAsset(drawable, resourcePath); 39 | MemoryStream destination = new MemoryStream(bytes); 40 | return destination; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Offscreen/Assets/darkmetal_bc3_unorm.ktx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Offscreen/Assets/darkmetal_bc3_unorm.ktx -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Offscreen/Assets/plane2.dae: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Blender User 6 | Blender 2.76.0 commit date:2015-11-03, commit time:10:56, hash:f337fea 7 | 8 | 2017-03-26T22:57:56 9 | 2017-03-26T22:57:56 10 | 11 | Z_UP 12 | 13 | 14 | 15 | 16 | 17 | 18 | -10 0 5 -10 0 10 -5 0 5 -5 0 10 0 0 5 0 0 10 5 0 5 5 0 10 10 0 5 10 0 10 -10 0 0 -5 0 0 0 0 0 5 0 0 10 0 0 -10 0 -5 -5 0 -5 0 0 -5 5 0 -5 10 0 -5 -10 0 -10 -5 0 -10 0 0 -10 5 0 -10 10 0 -10 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 0 1 0 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 0 0.25 0 0 0.25 0.25 0.25 0 0.25 0.25 0 0 0.25 0.25 0.25 0 0.5 0.25 0.5 0 0.5 0.25 0.25 0 0.5 0.25 0.5 0 0.75 0.25 0.75 0 0.75 0.25 0.5 0 0.75 0.25 0.75 0 1 0.25 1 0 1 0.25 0.75 0 0 0.5 0 0.25 0.25 0.5 0.25 0.25 0.25 0.5 0 0.25 0.25 0.5 0.25 0.25 0.5 0.5 0.5 0.25 0.5 0.5 0.25 0.25 0.5 0.5 0.5 0.25 0.75 0.5 0.75 0.25 0.75 0.5 0.5 0.25 0.75 0.5 0.75 0.25 1 0.5 1 0.25 1 0.5 0.75 0.25 0 0.75 0 0.5 0.25 0.75 0.25 0.5 0.25 0.75 0 0.5 0.25 0.75 0.25 0.5 0.5 0.75 0.5 0.5 0.5 0.75 0.25 0.5 0.5 0.75 0.5 0.5 0.75 0.75 0.75 0.5 0.75 0.75 0.5 0.5 0.75 0.75 0.75 0.5 1 0.75 1 0.5 1 0.75 0.75 0.5 0 1 0 0.75 0.25 1 0.25 0.75 0.25 1 0 0.75 0.25 1 0.25 0.75 0.5 1 0.5 0.75 0.5 1 0.25 0.75 0.5 1 0.5 0.75 0.75 1 0.75 0.75 0.75 1 0.5 0.75 0.75 1 0.75 0.75 1 1 1 0.75 1 1 0.75 0.75 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 54 |

0 0 0 1 0 1 2 0 2 3 0 3 2 0 4 1 0 5 2 0 6 3 0 7 4 0 8 5 0 9 4 0 10 3 0 11 4 0 12 5 0 13 6 0 14 7 0 15 6 0 16 5 0 17 6 0 18 7 0 19 8 0 20 9 0 21 8 0 22 7 0 23 10 0 24 0 0 25 11 0 26 2 0 27 11 0 28 0 0 29 11 0 30 2 0 31 12 0 32 4 0 33 12 0 34 2 0 35 12 0 36 4 0 37 13 0 38 6 0 39 13 0 40 4 0 41 13 0 42 6 0 43 14 0 44 8 0 45 14 0 46 6 0 47 15 0 48 10 0 49 16 0 50 11 0 51 16 0 52 10 0 53 16 0 54 11 0 55 17 0 56 12 0 57 17 0 58 11 0 59 17 0 60 12 0 61 18 0 62 13 0 63 18 0 64 12 0 65 18 0 66 13 0 67 19 0 68 14 0 69 19 0 70 13 0 71 20 0 72 15 0 73 21 0 74 16 0 75 21 0 76 15 0 77 21 0 78 16 0 79 22 0 80 17 0 81 22 0 82 16 0 83 22 0 84 17 0 85 23 0 86 18 0 87 23 0 88 17 0 89 23 0 90 18 0 91 24 0 92 19 0 93 24 0 94 18 0 95

55 |
56 |
57 |
58 |
59 | 60 | 61 | 62 | 63 | 1 0 0 0 0 -1.62921e-7 -1 0 0 1 -1.62921e-7 0 0 0 0 1 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 |
-------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Offscreen/Shaders/Mirror-fragment.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(set = 0, binding = 1) uniform texture2D ReflectionMap; 4 | layout(set = 0, binding = 2) uniform sampler ReflectionMapSampler; 5 | layout(set = 0, binding = 3) uniform texture2D ColorMap; 6 | layout(set = 0, binding = 4) uniform sampler ColorMapSampler; 7 | 8 | layout(location = 0) in vec2 fsin_uv; 9 | layout(location = 1) in vec4 fsin_position; 10 | layout(location = 0) out vec4 fsout_color; 11 | 12 | void main() 13 | { 14 | vec4 outFragColor; 15 | vec2 projCoord = vec2((fsin_position.x / fsin_position.w) / 2 + 0.5, (fsin_position.y / fsin_position.w) / -2 + 0.5); 16 | float blurSize = 1.f / 512.f; 17 | vec4 color = texture(sampler2D(ColorMap, ColorMapSampler), fsin_uv); 18 | outFragColor = color * 0.25f; 19 | if (gl_FrontFacing) 20 | { 21 | vec4 reflection = vec4(0.0f, 0.0f, 0.0f, 0.0f); 22 | for (int x = -3; x <= 3; x++) 23 | { 24 | for (int y = -3; y <= 3; y++) 25 | { 26 | reflection += texture(sampler2D(ReflectionMap, ReflectionMapSampler), vec2(projCoord.x + x * blurSize, projCoord.y + y * blurSize)) / 49.0f; 27 | } 28 | } 29 | 30 | outFragColor += reflection * 1.5f * (color.x); 31 | } 32 | 33 | fsout_color = outFragColor; 34 | } 35 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Offscreen/Shaders/Mirror-vertex.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(set = 0, binding = 0) uniform UBO 4 | { 5 | mat4 Projection; 6 | mat4 View; 7 | mat4 Model; 8 | vec4 LightPos; 9 | }; 10 | 11 | layout(location = 0) in vec3 Position; 12 | layout(location = 1) in vec2 UV; 13 | layout(location = 2) in vec3 Color; 14 | layout(location = 3) in vec3 Normal; 15 | layout(location = 0) out vec2 fsin_uv; 16 | layout(location = 1) out vec4 fsin_position; 17 | 18 | void main() 19 | { 20 | fsin_uv = UV; 21 | fsin_position = Projection * View * Model * vec4(Position, 1.f); 22 | gl_Position = fsin_position; 23 | } 24 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Offscreen/Shaders/Phong-fragment.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(location = 0) in vec3 fsin_normal; 4 | layout(location = 1) in vec3 fsin_color; 5 | layout(location = 2) in vec3 fsin_eyePos; 6 | layout(location = 3) in vec3 fsin_lightVec; 7 | layout(location = 0) out vec4 fsout_color; 8 | 9 | void main() 10 | { 11 | vec3 Eye = normalize(-fsin_eyePos); 12 | vec3 Reflected = normalize(reflect(-fsin_lightVec, fsin_normal)); 13 | vec4 IAmbient = vec4(0.1f, 0.1f, 0.1f, 1.0f); 14 | float diff = clamp(dot(fsin_normal, fsin_lightVec), 0.f, 100000); 15 | vec4 IDiffuse = vec4(diff, diff, diff, diff); 16 | float specular = 0.75f; 17 | vec4 ISpecular = vec4(0.0f, 0.0f, 0.0f, 0.0f); 18 | if (dot(fsin_eyePos, fsin_normal) < 0.0) 19 | { 20 | ISpecular = (vec4(0.5f, 0.5f, 0.5f, 1.0f) * pow(clamp(dot(Reflected, Eye), 0.0f, 100000), 16.0f)) * specular; 21 | } 22 | 23 | fsout_color = (IAmbient + IDiffuse) * vec4(fsin_color, 1.0f) + ISpecular; 24 | } 25 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Offscreen/Shaders/Phong-vertex.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(set = 0, binding = 0) uniform UBO 4 | { 5 | mat4 Projection; 6 | mat4 View; 7 | mat4 Model; 8 | vec4 LightPos; 9 | }; 10 | 11 | layout(location = 0) in vec3 Position; 12 | layout(location = 1) in vec2 UV; 13 | layout(location = 2) in vec3 Color; 14 | layout(location = 3) in vec3 Normal; 15 | layout(location = 0) out vec3 fsin_normal; 16 | layout(location = 1) out vec3 fsin_color; 17 | layout(location = 2) out vec3 fsin_eyePos; 18 | layout(location = 3) out vec3 fsin_lightVec; 19 | 20 | void main() 21 | { 22 | vec4 v4Pos = vec4(Position, 1); 23 | fsin_normal = Normal; 24 | fsin_color = Color; 25 | gl_Position = Projection * View * (Model * v4Pos); 26 | vec4 eyePos = View * Model * v4Pos; 27 | fsin_eyePos = eyePos.xyz; 28 | vec4 eyeLightPos = View * LightPos; 29 | fsin_lightVec = normalize(LightPos.xyz - fsin_eyePos); 30 | } 31 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/RenderDocCapture.cs: -------------------------------------------------------------------------------- 1 | namespace Veldrid.Maui.Samples.Core 2 | { 3 | public class RenderDocCapture 4 | { 5 | static RenderDoc rd; 6 | public static void Init() 7 | { 8 | if (rd == null) 9 | { 10 | RenderDoc.Load(out RenderDoc Rd); // Load RenderDoc from the default locations. 11 | rd = Rd; 12 | var folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "renderdocResult"); 13 | if (!Directory.Exists(folder)) 14 | Directory.CreateDirectory(folder); 15 | rd.SetCaptureSavePath(folder); // Save captures into a particular folder. 16 | } 17 | } 18 | 19 | public static void StartCapture() 20 | { 21 | rd?.TriggerCapture(); // Capture the next frame. 22 | rd?.StartFrameCapture(); // Start capturing. 23 | } 24 | 25 | static bool haveLunchUI = false; 26 | public static void EndCapture() 27 | { 28 | rd?.EndFrameCapture(); // Stop capturing and save. 29 | if (haveLunchUI == false && rd != null) 30 | { 31 | rd?.LaunchReplayUI(); // Launch the replay UI, with previous captures already loaded in. 32 | haveLunchUI = true; 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/TexturedCube/Assets/Images/spnza_bricks_a_diff.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/TexturedCube/Assets/Images/spnza_bricks_a_diff.png -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/TexturedCube/Assets/ProcessedImages/spnza_bricks_a_diff.binary: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/TexturedCube/Assets/ProcessedImages/spnza_bricks_a_diff.binary -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/TexturedCube/Assets/Shaders/frag.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(location = 0) in vec2 fsin_texCoords; 4 | layout(location = 0) out vec4 fsout_color; 5 | 6 | layout(set = 1, binding = 1) uniform texture2D SurfaceTexture; 7 | layout(set = 1, binding = 2) uniform sampler SurfaceSampler; 8 | 9 | void main() 10 | { 11 | fsout_color = texture(sampler2D(SurfaceTexture, SurfaceSampler), fsin_texCoords); 12 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/TexturedCube/Assets/Shaders/vert.glsl: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(set = 0, binding = 0) uniform ProjectionBuffer 4 | { 5 | mat4 Projection; 6 | }; 7 | 8 | layout(set = 0, binding = 1) uniform ViewBuffer 9 | { 10 | mat4 View; 11 | }; 12 | 13 | layout(set = 1, binding = 0) uniform WorldBuffer 14 | { 15 | mat4 World; 16 | }; 17 | 18 | layout(location = 0) in vec3 Position; 19 | layout(location = 1) in vec2 TexCoords; 20 | layout(location = 0) out vec2 fsin_texCoords; 21 | 22 | void main() 23 | { 24 | vec4 worldPosition = World * vec4(Position, 1); 25 | vec4 viewPosition = View * worldPosition; 26 | vec4 clipPosition = Projection * viewPosition; 27 | gl_Position = clipPosition; 28 | fsin_texCoords = TexCoords; 29 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/TexturedCube/BaseGpuDrawableExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Xml.Linq; 3 | using Veldrid.Maui.Controls.Base; 4 | 5 | namespace Veldrid.Maui.Samples.Core.TexturedCube 6 | { 7 | internal static class BaseGpuDrawableExtension 8 | { 9 | public static string ReadEmbedAssetPath(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 10 | { 11 | if (type == null) 12 | { 13 | Assembly assembly = Assembly.GetExecutingAssembly(); 14 | List resourceNames = new List(assembly.GetManifestResourceNames()); 15 | resourcePath = resourcePath.Replace(@"/", "."); 16 | resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath)); 17 | } 18 | else 19 | { 20 | List resourceNames = new List(type.Assembly.GetManifestResourceNames()); 21 | resourcePath = resourcePath.Replace(@"/", "."); 22 | resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath)); 23 | } 24 | 25 | if (resourcePath == null) 26 | throw new FileNotFoundException("Resource not found"); 27 | return resourcePath; 28 | } 29 | 30 | public static byte[] ReadEmbedAsset(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 31 | { 32 | resourcePath = ReadEmbedAssetPath(drawable, resourcePath); 33 | return drawable.ReadEmbeddedAssetBytes(resourcePath); 34 | } 35 | 36 | public static Stream ReadEmbedAssetStream(this BaseGpuDrawable drawable, string resourcePath = "foler.fileName.extention", Type type = null) 37 | { 38 | var bytes = ReadEmbedAsset(drawable, resourcePath); 39 | MemoryStream destination = new MemoryStream(bytes); 40 | return destination; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples.Core/Veldrid.Maui.Samples.Core.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0;net7.0-ios;net7.0-maccatalyst 5 | $(TargetFrameworks);net7.0-android 6 | enable 7 | enable 8 | True 9 | 10 | 11 | 12 | 13 | %(FileName)%(Extension) 14 | 15 | 16 | 17 | 18 | 19 | %(FileName)%(Extension) 20 | 21 | 22 | %(FileName)%(Extension) 23 | 24 | 25 | 26 | 27 | 28 | %(FileName)%(Extension) 29 | 30 | 31 | %(FileName)%(Extension) 32 | 33 | 34 | %(FileName)%(Extension) 35 | 36 | 37 | 38 | 39 | 40 | %(FileName)%(Extension) 41 | 42 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/App.xaml: -------------------------------------------------------------------------------- 1 |  2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/App.xaml.cs: -------------------------------------------------------------------------------- 1 | namespace Veldrid.Maui.Samples 2 | { 3 | public partial class App : Application 4 | { 5 | public App() 6 | { 7 | InitializeComponent(); 8 | 9 | MainPage = new AppShell(); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/AppShell.xaml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/AppShell.xaml.cs: -------------------------------------------------------------------------------- 1 | namespace Veldrid.Maui.Samples 2 | { 3 | public partial class AppShell : Shell 4 | { 5 | public AppShell() 6 | { 7 | InitializeComponent(); 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/MainPage.xaml: -------------------------------------------------------------------------------- 1 |  2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 18 | 19 | 20 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/MauiProgram.cs: -------------------------------------------------------------------------------- 1 | using Veldrid.Maui.Controls.Hosts; 2 | 3 | namespace Veldrid.Maui.Samples 4 | { 5 | public static class MauiProgram 6 | { 7 | public static MauiApp CreateMauiApp() 8 | { 9 | var builder = MauiApp.CreateBuilder(); 10 | builder 11 | .UseMauiApp() 12 | .UseVeldridView() 13 | .ConfigureFonts(fonts => 14 | { 15 | fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); 16 | fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); 17 | }); 18 | 19 | return builder.Build(); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/Android/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/Android/MainActivity.cs: -------------------------------------------------------------------------------- 1 | using Android.App; 2 | using Android.Content.PM; 3 | using Android.OS; 4 | 5 | namespace Veldrid.Maui.Samples 6 | { 7 | [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)] 8 | public class MainActivity : MauiAppCompatActivity 9 | { 10 | } 11 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/Android/MainApplication.cs: -------------------------------------------------------------------------------- 1 | using Android.App; 2 | using Android.Runtime; 3 | 4 | namespace Veldrid.Maui.Samples 5 | { 6 | [Application] 7 | public class MainApplication : MauiApplication 8 | { 9 | public MainApplication(IntPtr handle, JniHandleOwnership ownership) 10 | : base(handle, ownership) 11 | { 12 | } 13 | 14 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); 15 | } 16 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/Android/Resources/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #512BD4 4 | #2B0B98 5 | #2B0B98 6 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/MacCatalyst/AppDelegate.cs: -------------------------------------------------------------------------------- 1 | using Foundation; 2 | 3 | namespace Veldrid.Maui.Samples 4 | { 5 | [Register("AppDelegate")] 6 | public class AppDelegate : MauiUIApplicationDelegate 7 | { 8 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); 9 | } 10 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/MacCatalyst/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | UIDeviceFamily 6 | 7 | 1 8 | 2 9 | 10 | UIRequiredDeviceCapabilities 11 | 12 | arm64 13 | 14 | UISupportedInterfaceOrientations 15 | 16 | UIInterfaceOrientationPortrait 17 | UIInterfaceOrientationLandscapeLeft 18 | UIInterfaceOrientationLandscapeRight 19 | 20 | UISupportedInterfaceOrientations~ipad 21 | 22 | UIInterfaceOrientationPortrait 23 | UIInterfaceOrientationPortraitUpsideDown 24 | UIInterfaceOrientationLandscapeLeft 25 | UIInterfaceOrientationLandscapeRight 26 | 27 | XSAppIconAssets 28 | Assets.xcassets/appicon.appiconset 29 | 30 | 31 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/MacCatalyst/Program.cs: -------------------------------------------------------------------------------- 1 | using ObjCRuntime; 2 | using UIKit; 3 | 4 | namespace Veldrid.Maui.Samples 5 | { 6 | public class Program 7 | { 8 | // This is the main entry point of the application. 9 | static void Main(string[] args) 10 | { 11 | // if you want to use a different Application Delegate class from "AppDelegate" 12 | // you can specify it here. 13 | UIApplication.Main(args, null, typeof(AppDelegate)); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/Tizen/Main.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Maui; 2 | using Microsoft.Maui.Hosting; 3 | using System; 4 | 5 | namespace Veldrid.Maui.Samples 6 | { 7 | internal class Program : MauiApplication 8 | { 9 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); 10 | 11 | static void Main(string[] args) 12 | { 13 | var app = new Program(); 14 | app.Run(args); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/Tizen/tizen-manifest.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | appicon.xhigh.png 7 | 8 | 9 | 10 | 11 | http://tizen.org/privilege/internet 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/Windows/App.xaml: -------------------------------------------------------------------------------- 1 |  7 | 8 | 9 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/Windows/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.UI.Xaml; 2 | 3 | // To learn more about WinUI, the WinUI project structure, 4 | // and more about our project templates, see: http://aka.ms/winui-project-info. 5 | 6 | namespace Veldrid.Maui.Samples.WinUI 7 | { 8 | /// 9 | /// Provides application-specific behavior to supplement the default Application class. 10 | /// 11 | public partial class App : MauiWinUIApplication 12 | { 13 | /// 14 | /// Initializes the singleton application object. This is the first line of authored code 15 | /// executed, and as such is the logical equivalent of main() or WinMain(). 16 | /// 17 | public App() 18 | { 19 | this.InitializeComponent(); 20 | } 21 | 22 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); 23 | } 24 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/Windows/Package.appxmanifest: -------------------------------------------------------------------------------- 1 |  2 | 7 | 8 | 9 | 10 | 11 | $placeholder$ 12 | User Name 13 | $placeholder$.png 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/Windows/app.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | true/PM 12 | PerMonitorV2, PerMonitor 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/iOS/AppDelegate.cs: -------------------------------------------------------------------------------- 1 | using Foundation; 2 | 3 | namespace Veldrid.Maui.Samples 4 | { 5 | [Register("AppDelegate")] 6 | public class AppDelegate : MauiUIApplicationDelegate 7 | { 8 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); 9 | } 10 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/iOS/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | LSRequiresIPhoneOS 6 | 7 | UIDeviceFamily 8 | 9 | 1 10 | 2 11 | 12 | UIRequiredDeviceCapabilities 13 | 14 | arm64 15 | 16 | UISupportedInterfaceOrientations 17 | 18 | UIInterfaceOrientationPortrait 19 | UIInterfaceOrientationLandscapeLeft 20 | UIInterfaceOrientationLandscapeRight 21 | 22 | UISupportedInterfaceOrientations~ipad 23 | 24 | UIInterfaceOrientationPortrait 25 | UIInterfaceOrientationPortraitUpsideDown 26 | UIInterfaceOrientationLandscapeLeft 27 | UIInterfaceOrientationLandscapeRight 28 | 29 | XSAppIconAssets 30 | Assets.xcassets/appicon.appiconset 31 | CFBundleIdentifier 32 | tempsample.com.test 33 | MinimumOSVersion 34 | 15.2 35 | CFBundleShortVersionString 36 | 1.0 37 | 38 | 39 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Platforms/iOS/Program.cs: -------------------------------------------------------------------------------- 1 | using ObjCRuntime; 2 | using UIKit; 3 | 4 | namespace Veldrid.Maui.Samples 5 | { 6 | public class Program 7 | { 8 | // This is the main entry point of the application. 9 | static void Main(string[] args) 10 | { 11 | // if you want to use a different Application Delegate class from "AppDelegate" 12 | // you can specify it here. 13 | UIApplication.Main(args, null, typeof(AppDelegate)); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Windows Machine": { 4 | "commandName": "MsixPackage", 5 | "nativeDebugging": false 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Resources/AppIcon/appicon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Resources/AppIcon/appiconfg.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Resources/Fonts/OpenSans-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples/Resources/Fonts/OpenSans-Regular.ttf -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Resources/Fonts/OpenSans-Semibold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.Maui.Samples/Veldrid.Maui.Samples/Resources/Fonts/OpenSans-Semibold.ttf -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Resources/Raw/AboutAssets.txt: -------------------------------------------------------------------------------- 1 | Any raw assets you want to be deployed with your application can be placed in 2 | this directory (and child directories). Deployment of the asset to your application 3 | is automatically handled by the following `MauiAsset` Build Action within your `.csproj`. 4 | 5 | 6 | 7 | These files will be deployed with you package and will be accessible using Essentials: 8 | 9 | async Task LoadMauiAsset() 10 | { 11 | using var stream = await FileSystem.OpenAppPackageFileAsync("AboutAssets.txt"); 12 | using var reader = new StreamReader(stream); 13 | 14 | var contents = reader.ReadToEnd(); 15 | } 16 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Resources/Splash/splash.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Resources/Styles/Colors.xaml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 6 | 7 | #512BD4 8 | #DFD8F7 9 | #2B0B98 10 | White 11 | Black 12 | #E1E1E1 13 | #C8C8C8 14 | #ACACAC 15 | #919191 16 | #6E6E6E 17 | #404040 18 | #212121 19 | #141414 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | #F7B548 35 | #FFD590 36 | #FFE5B9 37 | #28C2D1 38 | #7BDDEF 39 | #C3F2F4 40 | #3E8EED 41 | #72ACF1 42 | #A7CBF6 43 | 44 | -------------------------------------------------------------------------------- /Veldrid.Maui.Samples/Veldrid.Maui.Samples/Veldrid.Maui.Samples.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0-maccatalyst;net7.0-android;net7.0-ios 5 | $(TargetFrameworks);net7.0-windows10.0.19041.0 6 | 7 | 8 | Exe 9 | Veldrid.Maui.Samples 10 | true 11 | true 12 | enable 13 | 14 | 15 | Veldrid.Maui.Samples 16 | 17 | 18 | com.companyname.veldrid.maui.samples 19 | B718CF3F-632D-4CB3-BEE7-608D1CB5CCC7 20 | 21 | 22 | 1.0 23 | 1 24 | 25 | 15.2 26 | 14.0 27 | 21.0 28 | 10.0.17763.0 29 | 10.0.17763.0 30 | 6.5 31 | True 32 | 33 | 34 | 35 | 36 | 37 | SdkOnly 38 | 39 | 40 | 41 | SdkOnly 42 | 43 | 44 | 45 | manual 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /Veldrid.SDL.Samples/Base/VeldridPlatformInterface.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using Veldrid; 3 | using Veldrid.Maui.Controls.Base; 4 | using Veldrid.StartupUtilities; 5 | using Veldrid.Utilities; 6 | using Vulkan.Xlib; 7 | 8 | namespace Veldrid.SDL.Samples.Base 9 | { 10 | public sealed partial class VeldridPlatformInterface : 11 | BaseVeldridPlatformInterface 12 | { 13 | public VeldridPlatformWindow _view; 14 | GraphicsBackend _backend; 15 | 16 | public VeldridPlatformInterface(VeldridPlatformWindow view, GraphicsBackend backend = GraphicsBackend.Vulkan) 17 | { 18 | PlatformType = PlatformType.Desktop; 19 | 20 | _backend = backend; 21 | _view = view; 22 | _view.SizeChanged += OnViewSizeChanged; 23 | _view.Loaded += OnLoaded; 24 | _view.Unloaded += OnUnloaded; 25 | } 26 | 27 | public override uint Width => (uint)(_view.Width * 1); 28 | public override uint Height => (uint)(_view.Height * 1); 29 | 30 | public override bool AutoReDraw { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } 31 | 32 | private void OnUnloaded() 33 | { 34 | DestroyGraphicsDevice(); 35 | } 36 | 37 | private void OnLoaded() => CreateGraphicsDevice(); 38 | 39 | /// 40 | /// 设备的创建和销毁流程是一次性的, 而设置Drawable是可以多次的 41 | /// 42 | private void CreateGraphicsDevice() 43 | { 44 | GraphicsDeviceOptions options = new GraphicsDeviceOptions 45 | { 46 | PreferStandardClipSpaceYDirection = true, 47 | PreferDepthRangeZeroToOne = true, 48 | Debug = true, 49 | 50 | SwapchainDepthFormat = PixelFormat.R16_UNorm, 51 | SyncToVerticalBlank = true, 52 | ResourceBindingModel = ResourceBindingModel.Improved, 53 | }; 54 | 55 | _graphicsDevice = VeldridStartup.CreateGraphicsDevice(_view.Window, options, _backend); 56 | _swapChain = _graphicsDevice.MainSwapchain; 57 | _resources = new DisposeCollectorResourceFactory(_graphicsDevice.ResourceFactory); 58 | InvokeGraphicsDeviceCreated(); 59 | 60 | Run(); 61 | } 62 | 63 | #region Render 64 | bool _enableRun = false; 65 | private void Run() 66 | { 67 | _enableRun = true; 68 | Task.Factory.StartNew(() => Loop(), TaskCreationOptions.LongRunning); 69 | } 70 | 71 | int frameTime = 1000 / 60;//每秒60帧 72 | private void Loop() 73 | { 74 | while (_enableRun) 75 | { 76 | try 77 | { 78 | Thread.Sleep(frameTime); 79 | 80 | RenderLoop(); 81 | } 82 | catch (Exception e) 83 | { 84 | Debug.WriteLine("Encountered an error while rendering: " + e); 85 | //throw; 86 | } 87 | } 88 | } 89 | 90 | private void RenderLoop() 91 | { 92 | if (_graphicsDevice != null) 93 | { 94 | InvokeRendering(frameTime); 95 | } 96 | } 97 | #endregion 98 | 99 | /// 100 | /// 释放GraphicsDevice和ResourceFactory 101 | /// 102 | private void DestroyGraphicsDevice() 103 | { 104 | _enableRun = false; 105 | if (_graphicsDevice != null) 106 | { 107 | InvokeGraphicsDeviceDestroyed(); 108 | _graphicsDevice.WaitForIdle(); 109 | (_resources as DisposeCollectorResourceFactory)?.DisposeCollector.DisposeAll(); 110 | _graphicsDevice.Dispose(); 111 | _graphicsDevice = null; 112 | } 113 | } 114 | 115 | private void OnViewSizeChanged() 116 | { 117 | if (_graphicsDevice != null) 118 | { 119 | _swapChain.Resize(Width, Height); 120 | InvokeResized(); 121 | } 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /Veldrid.SDL.Samples/Base/VeldridPlatformWindow.cs: -------------------------------------------------------------------------------- 1 | using Veldrid.Sdl2; 2 | using Veldrid.StartupUtilities; 3 | 4 | namespace Veldrid.SDL.Samples.Base 5 | { 6 | public class VeldridPlatformWindow 7 | { 8 | public Sdl2Window Window; 9 | public int Width => Window.Width; 10 | public int Height => Window.Height; 11 | 12 | public Action SizeChanged; 13 | public Action Loaded; 14 | public Action Unloaded; 15 | 16 | public VeldridPlatformWindow(int x = 100, int y = 100, int w = 500, int h = 500) 17 | { 18 | WindowCreateInfo windowCI = new WindowCreateInfo() 19 | { 20 | X = x, 21 | Y = y, 22 | WindowWidth = w, 23 | WindowHeight = h, 24 | WindowTitle = "VeldridLearning" 25 | }; 26 | Window = VeldridStartup.CreateWindow(ref windowCI); 27 | Window.Shown += Window_Exposed; 28 | Window.Resized += Window_Resized; 29 | Window.Closing += Window_Closing; 30 | } 31 | 32 | private void Window_Closing() 33 | { 34 | Unloaded?.Invoke(); 35 | } 36 | 37 | private void Window_Exposed() 38 | { 39 | Loaded?.Invoke(); 40 | } 41 | 42 | private void Window_Resized() 43 | { 44 | SizeChanged?.Invoke(); 45 | } 46 | 47 | public double CompositionScaleX => 1; 48 | public double CompositionScaleY => 1; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Veldrid.SDL.Samples/Program.cs: -------------------------------------------------------------------------------- 1 | using Veldrid.SDL.Samples.Base; 2 | using Veldrid; 3 | using Veldrid.Maui.Samples.Core.LearnOpenGL; 4 | using Veldrid.Maui.Controls.Base; 5 | 6 | namespace Veldrid.SDL.Samples 7 | { 8 | class Program 9 | { 10 | static void Main(string[] args) 11 | { 12 | VeldridPlatformWindow window = new VeldridPlatformWindow(); 13 | var platformInterface = new VeldridPlatformInterface(window, GraphicsBackend.Vulkan); 14 | Maui.Samples.Core.RenderDocCapture.Init(); 15 | var camera = new SimpleCamera(); 16 | //platformInterface.Drawable = new Maui.Samples.Core.GettingStarted.GettingStartedDrawable(); 17 | //platformInterface.Drawable = new Maui.Samples.Core.ComputeTexture.ComputeTextureApplication(); 18 | //platformInterface.Drawable = new Maui.Samples.Core.AnimatedMesh.AnimatedMeshApplication(camera); 19 | //platformInterface.Drawable = new Maui.Samples.Core.ComputeParticles.ComputeParticlesApplication(); 20 | //platformInterface.Drawable = new Maui.Samples.Core.Instancing.InstancingApplication(camera); 21 | //platformInterface.Drawable = new Maui.Samples.Core.Offscreen.OffscreenApplication(camera); 22 | //platformInterface.Drawable = new Maui.Samples.Core.TexturedCube.TexturedCubeDrawable(); 23 | 24 | //platformInterface.Drawable = new HelloTriangle(); 25 | //platformInterface.Drawable = new HelloTriangle_ElementBufferObject(); 26 | //platformInterface.Drawable = new Shaders_InsAndOuts(); 27 | //platformInterface.Drawable = new Shaders_Uniform(); 28 | //platformInterface.Drawable = new Shaders_MoreAttributes(); 29 | //platformInterface.Drawable = new Textures(); 30 | //platformInterface.Drawable = new Textures_ApplyingTextures(); 31 | //platformInterface.Drawable = new Textures_TextureUnits(); 32 | //platformInterface.Drawable = new Transformations_InPractice(); 33 | //platformInterface.Drawable = new CoordinateSystems_Going3D(); 34 | //platformInterface.Drawable = new CoordinateSystems_More3D(); 35 | //platformInterface.Drawable = new CoordinateSystems_MoreCubes(); 36 | var head = new Maui.Samples.Core.Headless.HeadlessHelloTriangle(); 37 | if(platformInterface.Drawable != null) 38 | window.Window.Title = platformInterface.Drawable.GetType().Name; 39 | while (window.Window.Exists) 40 | { 41 | window.Window.PumpEvents(); 42 | } 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Veldrid.SDL.Samples/Veldrid.SDL.Samples.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net7.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Veldrid.Samples.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.33103.201 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Veldrid.macOS.Samples", "Veldrid.macOS.Samples\Veldrid.macOS.Samples\Veldrid.macOS.Samples.csproj", "{1EA8CF18-E122-40EA-B3BF-12ED321755AF}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Veldrid.Maui.Samples", "Veldrid.Maui.Samples", "{3831AFCB-6DBE-4643-880B-AAB6DE4B4403}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Veldrid.Maui.Controls", "Veldrid.Maui.Samples\Veldrid.Maui.Controls\Veldrid.Maui.Controls.csproj", "{7399DAC5-72C2-47CE-9037-17EA1AAAA90B}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Veldrid.Maui.Samples.Core", "Veldrid.Maui.Samples\Veldrid.Maui.Samples.Core\Veldrid.Maui.Samples.Core.csproj", "{733290E4-98A6-4D0D-901E-CC46CD3F4BC6}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Veldrid.Maui.Samples", "Veldrid.Maui.Samples\Veldrid.Maui.Samples\Veldrid.Maui.Samples.csproj", "{1425EA5B-6C92-41A4-B3C7-ED6B9F784DC0}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Veldrid.Wpf.Samples", "Veldrid.Wpf.Samples\Veldrid.Wpf.Samples.csproj", "{82978DDB-012F-4FCA-B43D-28DEFBE822AA}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Veldrid.SDL.Samples", "Veldrid.SDL.Samples\Veldrid.SDL.Samples.csproj", "{38DA08EA-4C77-4383-A561-EF2E0D5257BD}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OfficialVeldrid.SDL.Samples", "OfficialVeldrid.SDL.Samples\OfficialVeldrid.SDL.Samples.csproj", "{3CF68AE0-2FC6-40E3-9885-30DF795C8E5B}" 21 | EndProject 22 | Global 23 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 24 | Debug|Any CPU = Debug|Any CPU 25 | Release|Any CPU = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 28 | {1EA8CF18-E122-40EA-B3BF-12ED321755AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {1EA8CF18-E122-40EA-B3BF-12ED321755AF}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {1EA8CF18-E122-40EA-B3BF-12ED321755AF}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {1EA8CF18-E122-40EA-B3BF-12ED321755AF}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {7399DAC5-72C2-47CE-9037-17EA1AAAA90B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {7399DAC5-72C2-47CE-9037-17EA1AAAA90B}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {7399DAC5-72C2-47CE-9037-17EA1AAAA90B}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {7399DAC5-72C2-47CE-9037-17EA1AAAA90B}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {733290E4-98A6-4D0D-901E-CC46CD3F4BC6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {733290E4-98A6-4D0D-901E-CC46CD3F4BC6}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {733290E4-98A6-4D0D-901E-CC46CD3F4BC6}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {733290E4-98A6-4D0D-901E-CC46CD3F4BC6}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {1425EA5B-6C92-41A4-B3C7-ED6B9F784DC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {1425EA5B-6C92-41A4-B3C7-ED6B9F784DC0}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {1425EA5B-6C92-41A4-B3C7-ED6B9F784DC0}.Debug|Any CPU.Deploy.0 = Debug|Any CPU 43 | {1425EA5B-6C92-41A4-B3C7-ED6B9F784DC0}.Release|Any CPU.ActiveCfg = Release|Any CPU 44 | {1425EA5B-6C92-41A4-B3C7-ED6B9F784DC0}.Release|Any CPU.Build.0 = Release|Any CPU 45 | {1425EA5B-6C92-41A4-B3C7-ED6B9F784DC0}.Release|Any CPU.Deploy.0 = Release|Any CPU 46 | {82978DDB-012F-4FCA-B43D-28DEFBE822AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {82978DDB-012F-4FCA-B43D-28DEFBE822AA}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {82978DDB-012F-4FCA-B43D-28DEFBE822AA}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {82978DDB-012F-4FCA-B43D-28DEFBE822AA}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {38DA08EA-4C77-4383-A561-EF2E0D5257BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {38DA08EA-4C77-4383-A561-EF2E0D5257BD}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {38DA08EA-4C77-4383-A561-EF2E0D5257BD}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {38DA08EA-4C77-4383-A561-EF2E0D5257BD}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {3CF68AE0-2FC6-40E3-9885-30DF795C8E5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {3CF68AE0-2FC6-40E3-9885-30DF795C8E5B}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {3CF68AE0-2FC6-40E3-9885-30DF795C8E5B}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {3CF68AE0-2FC6-40E3-9885-30DF795C8E5B}.Release|Any CPU.Build.0 = Release|Any CPU 58 | EndGlobalSection 59 | GlobalSection(SolutionProperties) = preSolution 60 | HideSolutionNode = FALSE 61 | EndGlobalSection 62 | GlobalSection(NestedProjects) = preSolution 63 | {7399DAC5-72C2-47CE-9037-17EA1AAAA90B} = {3831AFCB-6DBE-4643-880B-AAB6DE4B4403} 64 | {733290E4-98A6-4D0D-901E-CC46CD3F4BC6} = {3831AFCB-6DBE-4643-880B-AAB6DE4B4403} 65 | {1425EA5B-6C92-41A4-B3C7-ED6B9F784DC0} = {3831AFCB-6DBE-4643-880B-AAB6DE4B4403} 66 | EndGlobalSection 67 | GlobalSection(ExtensibilityGlobals) = postSolution 68 | SolutionGuid = {EF4B1875-8ECC-4AC6-842C-E9A1EA95BFD2} 69 | EndGlobalSection 70 | EndGlobal 71 | -------------------------------------------------------------------------------- /Veldrid.Wpf.Samples/App.xaml: -------------------------------------------------------------------------------- 1 |  7 | 8 | 9 | -------------------------------------------------------------------------------- /Veldrid.Wpf.Samples/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Configuration; 4 | using System.Data; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using System.Windows; 8 | 9 | namespace Veldrid.Wpf.Samples 10 | { 11 | /// 12 | /// Interaction logic for App.xaml 13 | /// 14 | public partial class App : Application 15 | { 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Veldrid.Wpf.Samples/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | 3 | [assembly: ThemeInfo( 4 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located 5 | //(used if a resource is not found in the page, 6 | // or application resource dictionaries) 7 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located 8 | //(used if a resource is not found in the page, 9 | // app, or any theme specific resource dictionaries) 10 | )] 11 | -------------------------------------------------------------------------------- /Veldrid.Wpf.Samples/MainWindow.xaml: -------------------------------------------------------------------------------- 1 |  12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Veldrid.Wpf.Samples/Veldrid.Wpf.Samples.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | WinExe 5 | net7.0-windows 6 | enable 7 | true 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | true 18 | 19 | 20 | true 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Veldrid.Wpf.Samples/VeldridComponent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Runtime.InteropServices; 4 | using System.Windows; 5 | using System.Windows.Media; 6 | //Copy form https://gist.github.com/mellinoe/2ba885476f51ef867715e5aa64b390de 7 | namespace Veldrid.Wpf.Samples 8 | { 9 | // This extends from the "Win32HwndControl" from the SharpDX example code. 10 | public class VeldridComponent : Win32HwndControl 11 | { 12 | private Swapchain _sc; 13 | private CommandList _cl; 14 | private GraphicsDevice _gd; 15 | 16 | public bool Rendering { get; private set; } 17 | 18 | protected override sealed void Initialize() 19 | { 20 | _gd = GraphicsDevice.CreateD3D11(new GraphicsDeviceOptions()); 21 | _cl = _gd.ResourceFactory.CreateCommandList(); 22 | CreateSwapchain(); 23 | 24 | Rendering = true; 25 | CompositionTarget.Rendering += OnCompositionTargetRendering; 26 | } 27 | 28 | protected override sealed void Uninitialize() 29 | { 30 | Rendering = false; 31 | CompositionTarget.Rendering -= OnCompositionTargetRendering; 32 | 33 | DestroySwapchain(); 34 | } 35 | 36 | protected sealed override void Resized() 37 | { 38 | ResizeSwapchain(); 39 | } 40 | 41 | private void OnCompositionTargetRendering(object sender, EventArgs eventArgs) 42 | { 43 | if (!Rendering) 44 | return; 45 | 46 | Render(); 47 | } 48 | 49 | private double GetDpiScale() 50 | { 51 | PresentationSource source = PresentationSource.FromVisual(this); 52 | 53 | return source.CompositionTarget.TransformToDevice.M11; 54 | } 55 | 56 | protected virtual void CreateSwapchain() 57 | { 58 | double dpiScale = GetDpiScale(); 59 | uint width = (uint)(ActualWidth < 0 ? 0 : Math.Ceiling(ActualWidth * dpiScale)); 60 | uint height = (uint)(ActualHeight < 0 ? 0 : Math.Ceiling(ActualHeight * dpiScale)); 61 | 62 | Module mainModule = typeof(VeldridComponent).Module; 63 | IntPtr hinstance = Marshal.GetHINSTANCE(mainModule); 64 | SwapchainSource win32Source = SwapchainSource.CreateWin32(Hwnd, hinstance); 65 | SwapchainDescription scDesc = new SwapchainDescription(win32Source, width, height, PixelFormat.R32_Float, true); 66 | 67 | _sc = _gd.ResourceFactory.CreateSwapchain(scDesc); 68 | } 69 | 70 | protected virtual void DestroySwapchain() 71 | { 72 | _sc.Dispose(); 73 | } 74 | 75 | private void ResizeSwapchain() 76 | { 77 | double dpiScale = GetDpiScale(); 78 | uint width = (uint)(ActualWidth < 0 ? 0 : Math.Ceiling(ActualWidth * dpiScale)); 79 | uint height = (uint)(ActualHeight < 0 ? 0 : Math.Ceiling(ActualHeight * dpiScale)); 80 | _sc.Resize(width, height); 81 | } 82 | 83 | protected virtual void Render() 84 | { 85 | _cl.Begin(); 86 | _cl.SetFramebuffer(_sc.Framebuffer); 87 | Random r = new Random(); 88 | _cl.ClearColorTarget( 89 | 0, 90 | new RgbaFloat((float)r.NextDouble(), 0, 0, 1)); 91 | _cl.ClearDepthStencil(1); 92 | 93 | // Do your rendering here (or call a subclass, etc.) 94 | 95 | _cl.End(); 96 | _gd.SubmitCommands(_cl); 97 | _gd.SwapBuffers(_sc); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /Veldrid.Wpf.Samples/VeldridPlatformInterface.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Runtime.InteropServices; 4 | using System.Windows.Media; 5 | using Veldrid.Maui.Controls.Base; 6 | using Veldrid.Utilities; 7 | 8 | namespace Veldrid.Wpf.Samples 9 | { 10 | public sealed partial class VeldridPlatformInterface : 11 | BaseVeldridPlatformInterface 12 | { 13 | public VeldridPlatformView _view; 14 | 15 | private readonly GraphicsBackend _backend; 16 | 17 | public VeldridPlatformInterface(VeldridPlatformView view, GraphicsBackend backend = GraphicsBackend.Direct3D11) 18 | { 19 | PlatformType = PlatformType.Desktop; 20 | 21 | if (!(backend == GraphicsBackend.Direct3D11 || backend == GraphicsBackend.Vulkan)) 22 | throw new NotSupportedException($"Not support {backend} backend."); 23 | _backend = backend; 24 | 25 | _view = view; 26 | _view.SizeChanged += OnViewSizeChanged; 27 | _view.Loaded += OnLoaded; 28 | _view.Unloaded += OnUnloaded; 29 | } 30 | 31 | public override uint Width => (uint)(_view.RenderSize.Width * _view.CompositionScaleX); 32 | public override uint Height => (uint)(_view.RenderSize.Height * _view.CompositionScaleY); 33 | public override bool AutoReDraw { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } 34 | 35 | private void OnUnloaded() 36 | { 37 | CompositionTarget.Rendering -= RenderLoop; 38 | DestroyGraphicsDevice(); 39 | } 40 | 41 | public void OnLoaded() => CreateGraphicsDevice(); 42 | 43 | /// 44 | /// 设备的创建和销毁流程是一次性的, 而设置Drawable是可以多次的 45 | /// 46 | private void CreateGraphicsDevice() 47 | { 48 | double dpiScale = _view.CompositionScaleX; 49 | uint width = (uint)(_view.ActualWidth < 0 ? 0 : Math.Ceiling(_view.ActualWidth * dpiScale)); 50 | uint height = (uint)(_view.ActualHeight < 0 ? 0 : Math.Ceiling(_view.ActualHeight * dpiScale)); 51 | 52 | Module mainModule = typeof(VeldridPlatformView).Module; 53 | IntPtr hinstance = Marshal.GetHINSTANCE(mainModule); 54 | SwapchainSource win32Source = SwapchainSource.CreateWin32(_view.NativeHwnd, hinstance); 55 | SwapchainDescription scDesc = new SwapchainDescription(win32Source, width, height, PixelFormat.R32_Float, true); 56 | 57 | var Options = new GraphicsDeviceOptions(false, null, false, ResourceBindingModel.Improved, true, true); 58 | if (_backend == GraphicsBackend.Direct3D11) 59 | _graphicsDevice = GraphicsDevice.CreateD3D11(Options, scDesc); 60 | else if (_backend == GraphicsBackend.Vulkan) 61 | _graphicsDevice = GraphicsDevice.CreateVulkan(Options, scDesc); 62 | //_swapChain = _graphicsDevice.ResourceFactory.CreateSwapchain(scDesc); 63 | _swapChain = _graphicsDevice.MainSwapchain; 64 | 65 | CompositionTarget.Rendering += RenderLoop; 66 | 67 | _resources = new DisposeCollectorResourceFactory(_graphicsDevice.ResourceFactory); 68 | InvokeGraphicsDeviceCreated(); 69 | } 70 | 71 | /// 72 | /// 释放GraphicsDevice和ResourceFactory 73 | /// 74 | private void DestroyGraphicsDevice() 75 | { 76 | if (_graphicsDevice != null) 77 | { 78 | InvokeGraphicsDeviceDestroyed(); 79 | _graphicsDevice.WaitForIdle(); 80 | (_resources as DisposeCollectorResourceFactory)?.DisposeCollector.DisposeAll(); 81 | _graphicsDevice.Dispose(); 82 | _graphicsDevice = null; 83 | } 84 | } 85 | 86 | /// 87 | /// View will still run it. 88 | /// 89 | /// 90 | /// 91 | private void RenderLoop(object? sender, EventArgs eventArgs) 92 | { 93 | if (_graphicsDevice != null) InvokeRendering(16); 94 | } 95 | 96 | private void OnViewSizeChanged() 97 | { 98 | if (_graphicsDevice != null) 99 | { 100 | double dpiScale = _view.CompositionScaleX; 101 | uint width = (uint)(_view.ActualWidth < 0 ? 0 : Math.Ceiling(_view.ActualWidth * dpiScale)); 102 | uint height = (uint)(_view.ActualHeight < 0 ? 0 : Math.Ceiling(_view.ActualHeight * dpiScale)); 103 | _swapChain.Resize(width, height); 104 | InvokeResized(); 105 | } 106 | } 107 | 108 | public override void Dispose() 109 | { 110 | _view = null; 111 | base.Dispose(); 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /Veldrid.Wpf.Samples/VeldridPlatformView.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Windows; 7 | 8 | namespace Veldrid.Wpf.Samples 9 | { 10 | public class VeldridPlatformView : Win32HwndControl 11 | { 12 | public IntPtr NativeHwnd => this.Hwnd; 13 | public Action SizeChanged; 14 | public Action Loaded; 15 | public Action Unloaded; 16 | public VeldridPlatformView() 17 | { 18 | } 19 | 20 | protected override void Initialize() 21 | { 22 | Loaded?.Invoke(); 23 | } 24 | 25 | protected override void Resized() 26 | { 27 | SizeChanged?.Invoke(); 28 | } 29 | 30 | protected override void Uninitialize() 31 | { 32 | Unloaded?.Invoke(); 33 | } 34 | 35 | public double CompositionScaleX =>GetDpiScale(); 36 | public double CompositionScaleY =>GetDpiScale(); 37 | private double GetDpiScale() 38 | { 39 | PresentationSource source = PresentationSource.FromVisual(this); 40 | if(source != null ) 41 | return source.CompositionTarget.TransformToDevice.M11; 42 | else 43 | return 1; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.33103.201 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Veldrid.macOS.Samples", "Veldrid.macOS.Samples\Veldrid.macOS.Samples.csproj", "{1EA8CF18-E122-40EA-B3BF-12ED321755AF}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {1EA8CF18-E122-40EA-B3BF-12ED321755AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {1EA8CF18-E122-40EA-B3BF-12ED321755AF}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {1EA8CF18-E122-40EA-B3BF-12ED321755AF}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {1EA8CF18-E122-40EA-B3BF-12ED321755AF}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {EF4B1875-8ECC-4AC6-842C-E9A1EA95BFD2} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/AppDelegate.cs: -------------------------------------------------------------------------------- 1 | namespace Veldrid.macOS.Samples 2 | { 3 | [Register("AppDelegate")] 4 | public class AppDelegate : NSApplicationDelegate 5 | { 6 | public override void DidFinishLaunching(NSNotification notification) 7 | { 8 | // Insert code here to initialize your application 9 | } 10 | 11 | public override void WillTerminate(NSNotification notification) 12 | { 13 | // Insert code here to tear down your application 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/AppGlobals.cs: -------------------------------------------------------------------------------- 1 | using Veldrid; 2 | 3 | namespace Veldrid.macOS.Samples 4 | { 5 | // Using Veldrid, only a single GraphicsDevice needs to be created, 6 | // even when rendering to many Swapchains in an application. 7 | // A Veldrid GraphicsDevice is responsible for creating all useful graphics 8 | // resources, including Swapchains. The GraphicsDevice in this class is used 9 | // to create a Swapchain in ViewController.ViewDidLoad. 10 | public static class AppGlobals 11 | { 12 | public static GraphicsDevice Device { get; private set; } 13 | 14 | public static void InitDevice() 15 | { 16 | GraphicsDeviceOptions options = new GraphicsDeviceOptions( 17 | debug: false, 18 | swapchainDepthFormat: null, 19 | syncToVerticalBlank: false, 20 | resourceBindingModel: ResourceBindingModel.Improved, 21 | preferDepthRangeZeroToOne: true, 22 | preferStandardClipSpaceYDirection: true); 23 | 24 | Device = GraphicsDevice.CreateMetal(options); 25 | } 26 | 27 | internal static void DisposeDevice() 28 | { 29 | Device.Dispose(); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images": [ 3 | { 4 | "idiom" : "mac", 5 | "scale" : "1x", 6 | "size" : "16x16", 7 | "filename": "Icon16.png" 8 | }, 9 | { 10 | "idiom" : "mac", 11 | "scale" : "2x", 12 | "size" : "16x16", 13 | "filename": "Icon32.png" 14 | }, 15 | { 16 | "idiom" : "mac", 17 | "scale" : "1x", 18 | "size" : "32x32", 19 | "filename": "Icon32.png" 20 | }, 21 | { 22 | "idiom" : "mac", 23 | "scale" : "2x", 24 | "size" : "32x32", 25 | "filename": "Icon64.png" 26 | }, 27 | { 28 | "idiom" : "mac", 29 | "scale" : "1x", 30 | "size" : "128x128", 31 | "filename": "Icon128.png" 32 | }, 33 | { 34 | "idiom" : "mac", 35 | "scale" : "2x", 36 | "size" : "128x128", 37 | "filename": "Icon256.png" 38 | }, 39 | { 40 | "idiom" : "mac", 41 | "scale" : "1x", 42 | "size" : "256x256", 43 | "filename": "Icon256.png" 44 | }, 45 | { 46 | "idiom" : "mac", 47 | "scale" : "2x", 48 | "size" : "256x256", 49 | "filename": "Icon512.png" 50 | }, 51 | { 52 | "idiom" : "mac", 53 | "scale" : "1x", 54 | "size" : "512x512", 55 | "filename": "Icon512.png" 56 | }, 57 | { 58 | "idiom" : "mac", 59 | "scale" : "2x", 60 | "size" : "512x512", 61 | "filename": "Icon1024.png" 62 | } 63 | ], 64 | "info": { 65 | "version": 1, 66 | "author": "xcode" 67 | }, 68 | } 69 | -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon1024.png -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon128.png -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon16.png -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon256.png -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon32.png -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon512.png -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xtuzy/Veldrid.Samples/394a586def1feb14e3789fc437fd9af5e89b5f7c/Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/AppIcon.appiconset/Icon64.png -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Entitlements.plist: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Info.plist: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | CFBundleName 6 | Veldrid.macOS.Samples 7 | CFBundleIdentifier 8 | com.companyname.veldrid.macOSApp 9 | CFBundleShortVersionString 10 | 1.0 11 | CFBundleVersion 12 | 1 13 | CFBundleDevelopmentRegion 14 | en 15 | CFBundleInfoDictionaryVersion 16 | 6.0 17 | CFBundlePackageType 18 | APPL 19 | CFBundleSignature 20 | ???? 21 | NSHumanReadableCopyright 22 | ${AuthorCopyright:HtmlEncode} 23 | NSPrincipalClass 24 | NSApplication 25 | NSMainStoryboardFile 26 | Main 27 | XSAppIconAssets 28 | Assets.xcassets/AppIcon.appiconset 29 | 30 | 31 | -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Main.cs: -------------------------------------------------------------------------------- 1 | using Veldrid.macOS.Samples; 2 | 3 | // This is the main entry point of the application. 4 | NSApplication.Init(); 5 | //AppGlobals.InitDevice(); 6 | NSApplication.Main(args); 7 | //AppGlobals.DisposeDevice(); 8 | -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/Veldrid.macOS.Samples.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | net7.0-macos 4 | Exe 5 | enable 6 | true 7 | 10.14 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | true 17 | 18 | 19 | true 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/VeldridPlatformInterface.cs: -------------------------------------------------------------------------------- 1 | using CoreVideo; 2 | using System.Diagnostics; 3 | using Veldrid.Maui.Controls.Base; 4 | using Veldrid.Utilities; 5 | 6 | namespace Veldrid.macOS.Samples 7 | { 8 | public class VeldridPlatformInterface : //UIViewController, 9 | BaseVeldridPlatformInterface 10 | { 11 | private VeldridPlatformView _view; 12 | 13 | private readonly GraphicsDeviceOptions _options; 14 | private readonly GraphicsBackend _backend; 15 | private CVDisplayLink _timer; 16 | 17 | public override uint Width => (uint)(_view.CorrectedFrame.Width * NSScreen.MainScreen.BackingScaleFactor); 18 | public override uint Height => (uint)(_view.CorrectedFrame.Height * NSScreen.MainScreen.BackingScaleFactor); 19 | 20 | public override bool AutoReDraw { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } 21 | 22 | public VeldridPlatformInterface(VeldridPlatformView view, GraphicsBackend backend = GraphicsBackend.Metal) 23 | { 24 | PlatformType = PlatformType.Desktop; 25 | 26 | if (!(backend == GraphicsBackend.Metal || backend == GraphicsBackend.Vulkan)) 27 | throw new NotSupportedException($"Not support {backend} backend on Mac."); 28 | _backend = backend; 29 | 30 | _options = new GraphicsDeviceOptions(false, null, false, ResourceBindingModel.Improved, true, true); 31 | 32 | _view = view; 33 | _view.ViewLoaded += CreateGraphicsDevice; 34 | _view.SizeChanged += OnViewSizeChanged; 35 | _view.ViewRemoved += DestroyGraphicsDevice; 36 | } 37 | 38 | /// 39 | /// 在后自动执行, 开使渲染循环. 40 | /// 41 | public void Run() 42 | { 43 | // To render at a steady rate, we create a display link which will invoke our Render function. 44 | _timer = new CVDisplayLink(); 45 | _timer.SetOutputCallback(RenderLoop); 46 | /* 47 | if (DeviceInfo.Current.Version < new Version(10, 0)) 48 | { 49 | _timer.FrameInterval = 1; 50 | } 51 | else if (DeviceInfo.Current.Version < new Version(15, 0)) 52 | { 53 | _timer.PreferredFramesPerSecond = 60; 54 | } 55 | else 56 | { 57 | _timer.PreferredFrameRateRange = CAFrameRateRange.Default; 58 | }*/ 59 | _timer.Start(); 60 | } 61 | 62 | private CVReturn RenderLoop( 63 | CVDisplayLink displayLink, 64 | ref CVTimeStamp inNow, 65 | ref CVTimeStamp inOutputTime, 66 | CVOptionFlags flagsIn, 67 | ref CVOptionFlags flagsOut) 68 | { 69 | float elapsed = 16; 70 | if (_graphicsDevice != null) 71 | { 72 | try 73 | { 74 | InvokeRendering(elapsed); 75 | } 76 | catch (Exception e) 77 | { 78 | Debug.WriteLine("Encountered an error while rendering: " + e); 79 | //throw; 80 | } 81 | } 82 | return CVReturn.Success; 83 | } 84 | 85 | private void DestroyGraphicsDevice() 86 | { 87 | if (_graphicsDevice != null) 88 | { 89 | var tempDevice = _graphicsDevice; 90 | _graphicsDevice = null;//先设置null阻止渲染循环 91 | 92 | InvokeGraphicsDeviceDestroyed(); 93 | tempDevice.WaitForIdle(); 94 | (_resources as DisposeCollectorResourceFactory)?.DisposeCollector.DisposeAll(); 95 | tempDevice.Dispose(); 96 | } 97 | } 98 | 99 | private void CreateGraphicsDevice() 100 | { 101 | SwapchainSource ss = SwapchainSource.CreateNSView(_view.Handle); 102 | //MTLSwapchain内部自动转换成Pixel 103 | SwapchainDescription scd = new SwapchainDescription(ss,(uint)_view.CorrectedFrame.Width,(uint)_view.CorrectedFrame.Height, PixelFormat.R32_Float,false);//参考Veldrid.Samples的iOS 104 | //SwapchainDescription scd = new SwapchainDescription(ss, (uint)_view.CorrectedFrame.Width, (uint)_view.CorrectedFrame.Height, null, true, true);//参考VeldridNSViewExample 105 | if (_backend == GraphicsBackend.Metal) 106 | { 107 | //_graphicsDevice = GraphicsDevice.CreateMetal(_options); 108 | //_swapChain = _graphicsDevice.ResourceFactory.CreateSwapchain(ref scd); 109 | _graphicsDevice = GraphicsDevice.CreateMetal(_options, scd); 110 | _swapChain = _graphicsDevice.MainSwapchain; 111 | } 112 | else if (_backend == GraphicsBackend.OpenGL) 113 | { 114 | throw new NotImplementedException("Current not support OpenGL on Mac"); 115 | } 116 | else if (_backend == GraphicsBackend.Vulkan) 117 | { 118 | //need use MoltenVK 119 | _graphicsDevice = GraphicsDevice.CreateVulkan(_options, scd); 120 | _swapChain = _graphicsDevice.MainSwapchain; 121 | //throw new NotImplementedException("Current not support Vulkan on Mac"); 122 | } 123 | _resources = new DisposeCollectorResourceFactory(_graphicsDevice.ResourceFactory); 124 | InvokeGraphicsDeviceCreated(); 125 | 126 | Run(); 127 | } 128 | 129 | private void OnViewSizeChanged() 130 | { 131 | if (_graphicsDevice != null) 132 | { 133 | //MTLSwapchain内部自动转换成Pixel 134 | _swapChain.Resize((uint)_view.CorrectedFrame.Width, (uint)_view.CorrectedFrame.Height); 135 | InvokeResized(); 136 | } 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/VeldridPlatformView.cs: -------------------------------------------------------------------------------- 1 | using CoreAnimation; 2 | using CoreGraphics; 3 | namespace Veldrid.macOS.Samples 4 | { 5 | public class VeldridPlatformView : NSView 6 | { 7 | public VeldridPlatformView() 8 | { 9 | //this.Layer.MasksToBounds = true; // IMPORTANT 10 | 11 | this.PostsFrameChangedNotifications = true; 12 | NSNotificationCenter.DefaultCenter.AddObserver(NSView.FrameChangedNotification, FrameChanged); 13 | } 14 | 15 | /// 16 | /// 遇到了NSView的Frame只能在UI线程调用的Exception, 因此自定义一个 17 | /// 18 | internal CGSize CorrectedFrame = CGSize.Empty; 19 | /// 20 | /// 构建GraphicsDevice时大小不能为0, Maui会调用此方法计算UIView的大小,因此在该方法中判断何时大小不为0 21 | /// 22 | /// 23 | /// 24 | public void FrameChanged(NSNotification notification) 25 | { 26 | var result = this.Frame.Size; 27 | if (this.firstTimeLoad && result.Width > 0 && result.Height > 0)//初次有大小 28 | { 29 | CorrectedFrame = result; 30 | ViewLoaded?.Invoke(); 31 | firstTimeLoad = false; 32 | } 33 | else if (result != CorrectedFrame)//大小更新 34 | { 35 | CorrectedFrame = result; 36 | SizeChanged?.Invoke(); 37 | } 38 | } 39 | 40 | public Action SizeChanged; 41 | public Action ViewLoaded; 42 | public Action ViewRemoved; 43 | bool firstTimeLoad = true; 44 | public override void ViewDidMoveToWindow() 45 | { 46 | base.ViewDidMoveToWindow(); 47 | /*if (firstTimeLoad) 48 | { 49 | ViewLoaded?.Invoke(); 50 | firstTimeLoad = false; 51 | } 52 | else*/ 53 | if (!firstTimeLoad) 54 | { 55 | ViewRemoved?.Invoke(); 56 | firstTimeLoad = true; 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/ViewController.designer.cs: -------------------------------------------------------------------------------- 1 | // WARNING 2 | // 3 | // This file has been generated automatically by Visual Studio to store outlets and 4 | // actions made in the UI designer. If it is removed, they will be lost. 5 | // Manual changes to this file may not be handled correctly. 6 | // 7 | 8 | namespace Veldrid.macOS.Samples 9 | { 10 | [Register("ViewController")] 11 | partial class ViewController 12 | { 13 | void ReleaseDesignerOutlets() 14 | { 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/ViewController.old.cs: -------------------------------------------------------------------------------- 1 | using CoreVideo; 2 | using ObjCRuntime; 3 | 4 | namespace Veldrid.macOS.Samples 5 | { 6 | public partial class __ViewController : NSViewController 7 | { 8 | private readonly GraphicsDevice _gd; 9 | private Swapchain _sc; 10 | private CommandList _cl; 11 | private int _frameIndex = 0; 12 | private RgbaFloat[] _clearColors = 13 | { 14 | RgbaFloat.Red, 15 | RgbaFloat.Orange, 16 | RgbaFloat.Yellow, 17 | RgbaFloat.Green, 18 | RgbaFloat.Blue, 19 | new RgbaFloat(0.8f, 0.1f, 0.3f, 1f), 20 | new RgbaFloat(0.8f, 0.1f, 0.9f, 1f), 21 | }; 22 | private bool _resized; 23 | private (uint Width, uint Height) _size; 24 | 25 | protected __ViewController(NativeHandle handle) : base(handle) 26 | { 27 | // This constructor is required if the view controller is loaded from a xib or a storyboard. 28 | // Do not put any initialization here, use ViewDidLoad instead. 29 | 30 | _gd = AppGlobals.Device; 31 | } 32 | 33 | public override void ViewDidLoad() 34 | { 35 | base.ViewDidLoad(); 36 | 37 | // Do any additional setup after loading the view. 38 | 39 | var ss = SwapchainSource.CreateNSView(View.Handle); 40 | SwapchainDescription scDesc = new SwapchainDescription( 41 | ss, (uint)View.Frame.Width, (uint)View.Frame.Height, null, true, true); 42 | _sc = AppGlobals.Device.ResourceFactory.CreateSwapchain(scDesc); 43 | _cl = AppGlobals.Device.ResourceFactory.CreateCommandList(); 44 | 45 | // To render at a steady rate, we create a display link which will invoke our Render function. 46 | CVDisplayLink displayLink = new CVDisplayLink(); 47 | displayLink.SetOutputCallback(HandleDisplayLinkOutputCallback); 48 | displayLink.Start(); 49 | } 50 | 51 | private void Render() 52 | { 53 | // If we've detected a resize event, we handle it now. 54 | if (_resized) 55 | { 56 | _resized = false; 57 | _sc.Resize(_size.Width, _size.Height); 58 | } 59 | 60 | try 61 | { 62 | // Each frame, we clear the Swapchain's color target. 63 | // Several different colors are cycled. 64 | _cl.Begin(); 65 | _cl.SetFramebuffer(_sc.Framebuffer); 66 | _cl.ClearColorTarget(0, _clearColors[_frameIndex]); 67 | _cl.End(); 68 | _gd.SubmitCommands(_cl); 69 | _gd.SwapBuffers(_sc); 70 | 71 | // Do some math to loop our color picker index. 72 | if (_frameIndex == _clearColors.Length - 1) _frameIndex = 0; 73 | else _frameIndex++; 74 | }catch(Exception ex) 75 | { 76 | 77 | } 78 | } 79 | 80 | private CVReturn HandleDisplayLinkOutputCallback( 81 | CVDisplayLink displayLink, 82 | ref CVTimeStamp inNow, 83 | ref CVTimeStamp inOutputTime, 84 | CVOptionFlags flagsIn, 85 | ref CVOptionFlags flagsOut) 86 | { 87 | Render(); 88 | return CVReturn.Success; 89 | } 90 | 91 | 92 | public override void ViewDidLayout() 93 | { 94 | base.ViewDidLayout(); 95 | _resized = true; 96 | _size = ((uint)View.Frame.Width, (uint)View.Frame.Height); 97 | } 98 | 99 | public override NSObject RepresentedObject 100 | { 101 | get => base.RepresentedObject; 102 | set 103 | { 104 | base.RepresentedObject = value; 105 | 106 | // Update the view, if already loaded. 107 | } 108 | } 109 | 110 | 111 | } 112 | } -------------------------------------------------------------------------------- /Veldrid.macOS.Samples/Veldrid.macOS.Samples/ViewController.old.designer.cs: -------------------------------------------------------------------------------- 1 | // WARNING 2 | // 3 | // This file has been generated automatically by Visual Studio to store outlets and 4 | // actions made in the UI designer. If it is removed, they will be lost. 5 | // Manual changes to this file may not be handled correctly. 6 | // 7 | 8 | namespace Veldrid.macOS.Samples 9 | { 10 | [Register("__ViewController")] 11 | partial class __ViewController 12 | { 13 | void ReleaseDesignerOutlets() 14 | { 15 | } 16 | } 17 | } --------------------------------------------------------------------------------