### StereoKit Hello World Example Source: https://github.com/stereokit/stereokit/blob/master/README.md This is the minimal code required to initialize StereoKit, load a model, and run a basic application. It demonstrates the ease of getting started with StereoKit for mixed reality development. ```CSharp using StereoKit; SK.Initialize(); Model helmet = Model.FromFile("DamagedHelmet.gltf"); SK.Run(() => { helmet.Draw(Matrix.TS(Vec3.Zero, 0.1f)); }); ``` -------------------------------- ### Install Linux Build Prerequisites Source: https://github.com/stereokit/stereokit/blob/master/BUILDING.md Installs necessary packages for building StereoKit on Linux using apt-get. ```shell # here's the commands for installing Linux build pre-reqs: sudo apt-get update sudo apt-get install cmake ninja-build clang lld libx11-dev libxfixes-dev libegl-dev libgbm-dev libfontconfig-dev ``` -------------------------------- ### SK Initialization and Main Loop Source: https://context7.com/stereokit/stereokit/llms.txt Demonstrates how to initialize StereoKit with custom settings and run the main application loop using SK.Run. This is the standard way to start and manage an application's lifecycle. ```APIDOC ## SK — Initialization and Main Loop `SK` is the entry point for every StereoKit application. `SK.Initialize` boots the native layer and OpenXR runtime; `SK.Run` drives the per-frame loop and cleans up on exit. ```csharp using StereoKit; // Full-featured initialization with explicit settings SKSettings settings = new SKSettings { appName = "MyMRApp", assetsFolder = "Assets", mode = AppMode.XR, // fall back to Simulator if XR unavailable blendPreference = DisplayBlend.AnyTransparent, logFilter = LogLevel.Diagnostic, flatscreenWidth = 1280, flatscreenHeight = 720, }; if (!SK.Initialize(settings)) { Console.Error.WriteLine("StereoKit initialization failed!"); return; } Console.WriteLine($"Version: {SK.VersionName}"); Console.WriteLine($"Display mode: {SK.ActiveDisplayMode}"); Console.WriteLine($"Eye tracking: {SK.System.eyeTrackingPresent}"); Model helmet = Model.FromFile("DamagedHelmet.glb"); Pose windowPose = new Pose(0, 0, -0.5f, Quat.Identity); // SK.Run loops until SK.Quit() is called or the platform requests exit; // it automatically calls SK.Shutdown() when done. SK.Run(() => { // Draw model 10 cm in front of origin helmet?.Draw(Matrix.TS(Vec3.Zero, 0.1f)); // Minimal UI window UI.WindowBegin("Controls", ref windowPose); if (UI.Button("Quit")) SK.Quit(); UI.WindowEnd(); }, onShutdown: () => { Console.WriteLine("Shutting down cleanly."); }); ``` ``` -------------------------------- ### SK Initialization and Main Loop Source: https://context7.com/stereokit/stereokit/llms.txt Initializes StereoKit with explicit settings and runs the main application loop. Handles cleanup automatically on exit. Use SK.Initialize for full-featured setup and SK.Run for the standard application lifecycle. ```csharp using StereoKit; // Full-featured initialization with explicit settings SKSettings settings = new SKSettings { appName = "MyMRApp", assetsFolder = "Assets", mode = AppMode.XR, // fall back to Simulator if XR unavailable blendPreference = DisplayBlend.AnyTransparent, logFilter = LogLevel.Diagnostic, flatscreenWidth = 1280, flatscreenHeight = 720, }; if (!SK.Initialize(settings)) { Console.Error.WriteLine("StereoKit initialization failed!"); return; } Console.WriteLine($"Version: {SK.VersionName}"); Console.WriteLine($"Display mode: {SK.ActiveDisplayMode}"); Console.WriteLine($"Eye tracking: {SK.System.eyeTrackingPresent}"); Model helmet = Model.FromFile("DamagedHelmet.glb"); Pose windowPose = new Pose(0, 0, -0.5f, Quat.Identity); // SK.Run loops until SK.Quit() is called or the platform requests exit; // it automatically calls SK.Shutdown() when done. SK.Run(() => { // Draw model 10 cm in front of origin helmet?.Draw(Matrix.TS(Vec3.Zero, 0.1f)); // Minimal UI window UI.WindowBegin("Controls", ref windowPose); if (UI.Button("Quit")) SK.Quit(); UI.WindowEnd(); }, onShutdown: () => { Console.WriteLine("Shutting down cleanly."); }); ``` -------------------------------- ### Run C# Test App (Linux) Source: https://github.com/stereokit/stereokit/blob/master/BUILDING.md Runs the C# StereoKit test application using the .NET CLI. Requires the .NET SDK to be installed. ```shell # To run the C# test app, you will need the .NET SDK installed dotnet run --configuration Release --project Examples/StereoKitTest/StereoKitTest.csproj ``` -------------------------------- ### Tab and Space Usage Example Source: https://github.com/stereokit/stereokit/blob/master/CONTRIBUTING.md Demonstrates StereoKit's formatting convention: tabs for indentation and spaces for alignment. This aims to improve accessibility by allowing users to set their preferred tab width while maintaining code alignment. ```text -> -> function(arg1, -> -> .........arg2, -> -> .........arg3); ``` -------------------------------- ### Set Include Directories for StereoKitC Source: https://github.com/stereokit/stereokit/blob/master/CMakeLists.txt Configures public and private include directories for the StereoKitC target. This ensures that headers are accessible during compilation and installation. ```cmake target_include_directories(StereoKitC PUBLIC $ $ PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/StereoKitC/ ${LINUX_INCLUDES} ) if (basis_universal_ADDED) target_include_directories(StereoKitC PRIVATE ${basis_universal_SOURCE_DIR}/transcoder) endif() ``` -------------------------------- ### Generated R Class for Android Resources Source: https://github.com/stereokit/stereokit/blob/master/Examples/StereoKitTest/StereoKitTest_Xamarin/Resources/AboutResources.txt Shows an example of the 'R' class generated by the Android build system. This class contains constants that serve as IDs for your application's resources. ```csharp public class R { public class drawable { public const int icon = 0x123; } public class layout { public const int main = 0x456; } public class strings { public const int first_string = 0xabc; public const int second_string = 0xbcd; } } ``` -------------------------------- ### Generated Resource Class Structure Source: https://github.com/stereokit/stereokit/blob/master/Examples/StereoKitTest/StereoKitTest_NetAndroid/Resources/AboutResources.txt This is an example of the 'Resource' class generated by the Android build system. It contains nested classes for different resource types (Drawable, Layout, Strings) with constant integer IDs for each resource. ```csharp public class Resource { public class Drawable { public const int icon = 0x123; } public class Layout { public const int main = 0x456; } public class Strings { public const int first_string = 0xabc; public const int second_string = 0xbcd; } } ``` -------------------------------- ### Immediate Mode UI with StereoKit Source: https://context7.com/stereokit/stereokit/llms.txt Demonstrates creating a floating window with various UI elements like labels, sliders, toggles, and input fields. Use this for dynamic in-app menus and controls. ```csharp using StereoKit; Pose panelPose = new Pose(0, 0, -0.4f, Quat.LookDir(0, 0, 1)); bool wireframe = false; float brightness = 0.5f; string inputText = "hello"; Model target = Model.FromFile("Helmet.glb"); SK.Run(() => { // Draw the 3D object we're tweaking target?.Draw(Matrix.TS(new Vec3(0.4f, 0, -0.5f), 0.12f)); // A floating window containing controls UI.WindowBegin("Settings", ref panelPose, new Vec2(0.24f, 0)); UI.Label("Brightness"); if (UI.HSlider("brightness", ref brightness, 0f, 1f, 0.01f, 0.22f)) Console.WriteLine($"Brightness → {brightness:F2}"); UI.Toggle("Wireframe", ref wireframe); UI.Label("Notes"); UI.Input("notes", ref inputText, new Vec2(0.22f, UI.LineHeight * 2)); if (UI.Button("Reset")) { brightness = 0.5f; wireframe = false; inputText = "hello"; } // Separator between sections UI.HSeparator(); UI.Label($"Layout remaining: {UI.LayoutRemaining.x * 100:F0} cm"); UI.WindowEnd(); }); ``` -------------------------------- ### Texture Loading and Generation Source: https://context7.com/stereokit/stereokit/llms.txt Details how to load textures from files asynchronously, create textures from pixel data, and generate procedural cubemaps for environment lighting. Shows how to apply textures to materials. ```APIDOC ## Tex — Textures and Cubemaps `Tex` encapsulates 2D textures, texture arrays, cubemaps, and render targets. It can load standard image formats and generate procedural cubemaps for environment lighting. ```csharp // Load from file (asynchronous) Tex albedo = Tex.FromFile("Metal_Albedo.png", sRGBData: true); Tex normal = Tex.FromFile("Metal_Normal.png", sRGBData: false); Tex metalRough = Tex.FromFile("Metal_MRAO.png", sRGBData: false); // Subscribe to async load completion albedo.OnLoaded += tex => Console.WriteLine($"Loaded {tex.Width}x{tex.Height}"); // Create texture procedurally from Color32 array int w = 64, h = 64; Color32[] pixels = new Color32[w * h]; for (int i = 0; i < pixels.Length; i++) pixels[i] = (i / w + i % w) % 2 == 0 ? Color32.White : Color32.Black; Tex checkerboard = Tex.FromColors(pixels, w, h); // Generate a gradient-based cubemap for the sky and scene lighting Gradient gradient = new Gradient( new GradientKey(new Color(0.1f, 0.1f, 0.3f), 0.0f), new GradientKey(new Color(0.8f, 0.8f, 1.0f), 0.5f), new GradientKey(new Color(1.0f, 0.9f, 0.6f), 1.0f)); SphericalHarmonics lighting; Tex sky = Tex.GenCubemap(gradient, out lighting, Vec3.Up, resolution: 128); Renderer.SkyTex = sky; Renderer.SkyLight = lighting; // Apply to a material Material mat = Material.PBR.Copy(); mat[MatParamName.DiffuseTex] = albedo; mat[MatParamName.NormalTex] = normal; mat[MatParamName.MetalTex] = metalRough; SK.Run(() => { Mesh.GenerateSphere(0.15f).Draw(mat, Matrix.T(0, 0, -0.5f)); }); ``` ``` -------------------------------- ### Add Code Sample for Documentation Source: https://github.com/stereokit/stereokit/blob/master/CONTRIBUTING.md Use ':CodeSample:' tags to include C# code snippets in documentation. Specify the class, method, or property to associate the sample with. Ensure code adheres to the 80-character line limit. ```csharp /// :CodeSample: Vec3 Vec3.Distance /// ### Distance between two points /// /// Distance does use a Sqrt call, so only use it if you definitely /// need the actual distance. Otherwise, consider DistanceSq. Vec3 pointA = new Vec3(3,2,5); Vec3 pointB = new Vec3(3,2,8); float distance = Vec3.Distance(pointA, pointB); /// :End: ``` -------------------------------- ### Generate Primitive and Custom Meshes Source: https://context7.com/stereokit/stereokit/llms.txt Demonstrates generating common primitive shapes like planes, cubes, spheres, and cylinders using built-in functions. Also shows how to create a custom mesh from raw vertex and index data. ```csharp // Built-in primitive generators Mesh plane = Mesh.GeneratePlane(new Vec2(1f, 1f), subdivisions: 2); Mesh cube = Mesh.GenerateCube(new Vec3(0.2f, 0.2f, 0.2f)); Mesh rounded = Mesh.GenerateRoundedCube(Vec3.One * 0.2f, edgeRadius: 0.02f); Mesh sphere = Mesh.GenerateSphere(0.15f, subdivisions: 6); Mesh cylinder = Mesh.GenerateCylinder(diameter: 0.1f, depth: 0.2f, direction: Vec3.Up); Mesh circle = Mesh.GenerateCircle(0.1f, spokes: 32); // Custom mesh with raw vertex data Vertex[] verts = new Vertex[] { new Vertex(new Vec3(-0.1f, 0f, 0f), Vec3.Up, new Vec2(0, 0), Color32.White), new Vertex(new Vec3( 0.1f, 0f, 0f), Vec3.Up, new Vec2(1, 0), Color32.White), new Vertex(new Vec3( 0f, 0.2f, 0f), Vec3.Up, new Vec2(0.5f, 1), Color32.White), }; uint[] inds = new uint[] { 0, 1, 2 }; Mesh triangle = new Mesh(); triangle.SetVerts(verts); triangle.SetInds(inds); Material mat = Material.Unlit.Copy(); mat[MatParamName.ColorTint] = new Color(0, 1, 0); SK.Run(() => { sphere.Draw(mat, Matrix.T(0, 0, -0.5f)); cylinder.Draw(Material.PBR, Matrix.T(0.3f, 0, -0.5f)); triangle.Draw(mat, Matrix.T(-0.3f, 0, -0.5f)); }); ``` -------------------------------- ### Implement and Register IStepper for FPS Overlay Source: https://context7.com/stereokit/stereokit/llms.txt Implement the IStepper interface to create a background system like an FPS counter. Register it with SK.AddStepper() to have it automatically initialized, stepped, and shut down. ```csharp using StereoKit; using StereoKit.Framework; // A stepper that displays a persistent FPS counter window class FpsOverlay : IStepper { public bool Enabled => true; Pose _pose = new Pose(-0.3f, 0.1f, -0.4f, Quat.Identity); double _fps = 0; int _frames = 0; double _elapsed = 0; public bool Initialize() { Log.Info("FpsOverlay ready."); return true; } public void Step() { _frames++; _elapsed += Time.Stepf; if (_elapsed >= 1.0) { _fps = _frames / _elapsed; _frames = 0; _elapsed = 0; } UI.WindowBegin("FPS", ref _pose, UIWin.Body); UI.Label($"{_fps:F0} fps | {Time.Stepf * 1000:F1} ms"); UI.WindowEnd(); } public void Shutdown() { Log.Info("FpsOverlay shutdown."); } } // Register before or after SK.Initialize SK.AddStepper(); if (!SK.Initialize("StepperDemo")) return; SK.Run(() => { // Main app code here; FpsOverlay runs automatically every frame Mesh.GenerateSphere(0.05f).Draw(Material.PBR, Matrix.T(0, 0, -0.5f)); }); ``` -------------------------------- ### Play Spatial Audio with StereoKit Sound API Source: https://context7.com/stereokit/stereokit/llms.txt Shows how to load and play sounds from files, generate procedural tones, and play them at specific world-space positions with volume control. Also includes a visual marker for the audio source. Ensure StereoKit is initialized. ```csharp Sound blip = Sound.FromFile("Blip.wav"); Sound ambient = Sound.FromFile("Ambient.mp3"); // Procedural tone: 0.5 s of 440 Hz sine at 48 000 samples/sec float sampleRate = 48000f; float[] samples = new float[(int)(sampleRate * 0.5f)]; for (int i = 0; i < samples.Length; i++) samples[i] = MathF.Sin(i / sampleRate * 440f * MathF.PI * 2f) * 0.5f; Sound tone = Sound.FromSamples(samples); Vec3 audioSource = new Vec3(0.3f, 0, -0.5f); SK.Run(() => { // One-shot positional sound on pinch Hand hand = Input.Hand(Handed.Right); if (hand.IsJustPinched) { // Play at pinch point, full volume SoundInst inst = blip.Play(hand.pinchPt, volume: 1.0f); } // Looping ambient sound from a fixed world position if (!ambient.IsPlaying) ambient.Play(audioSource, volume: 0.3f); // Visual marker for audio source Lines.AddAxis(new Pose(audioSource, Quat.Identity), 0.02f); }); ``` -------------------------------- ### Mesh Generation and Usage Source: https://context7.com/stereokit/stereokit/llms.txt Demonstrates how to generate various primitive meshes like planes, cubes, spheres, and cylinders, as well as how to create custom meshes from raw vertex and index data. It also shows how to draw these meshes with materials. ```APIDOC ## Mesh — Procedural Geometry `Mesh` stores vertex and index data for triangle-based geometry. StereoKit ships built-in generators for common primitives and lets you supply raw vertex arrays. ```csharp // Built-in primitive generators Mesh plane = Mesh.GeneratePlane(new Vec2(1f, 1f), subdivisions: 2); Mesh cube = Mesh.GenerateCube(new Vec3(0.2f, 0.2f, 0.2f)); Mesh rounded = Mesh.GenerateRoundedCube(Vec3.One * 0.2f, edgeRadius: 0.02f); Mesh sphere = Mesh.GenerateSphere(0.15f, subdivisions: 6); Mesh cylinder = Mesh.GenerateCylinder(diameter: 0.1f, depth: 0.2f, direction: Vec3.Up); Mesh circle = Mesh.GenerateCircle(0.1f, spokes: 32); // Custom mesh with raw vertex data Vertex[] verts = new Vertex[] { new Vertex(new Vec3(-0.1f, 0f, 0f), Vec3.Up, new Vec2(0, 0), Color32.White), new Vertex(new Vec3( 0.1f, 0f, 0f), Vec3.Up, new Vec2(1, 0), Color32.White), new Vertex(new Vec3( 0f, 0.2f, 0f), Vec3.Up, new Vec2(0.5f, 1), Color32.White), }; uint[] inds = new uint[] { 0, 1, 2 }; Mesh triangle = new Mesh(); triangle.SetVerts(verts); triangle.SetInds(inds); Material mat = Material.Unlit.Copy(); mat[MatParamName.ColorTint] = new Color(0, 1, 0); SK.Run(() => { sphere.Draw(mat, Matrix.T(0, 0, -0.5f)); cylinder.Draw(Material.PBR, Matrix.T(0.3f, 0, -0.5f)); triangle.Draw(mat, Matrix.T(-0.3f, 0, -0.5f)); }); ``` ``` -------------------------------- ### Set NDK Environment Variable (Windows Command Line) Source: https://github.com/stereokit/stereokit/blob/master/BUILDING.md Configure the NDK path for Windows command line builds. Replace '[user]' with your actual username. ```shell # For Windows GUI, see: `Edit the system environment variables` in the Control # Panel. # Windows Command Line set NDK C:\Users\[user]\AppData\Local\Android\Sdk\ndk\25.2.9519653 ``` -------------------------------- ### Load and Generate Textures Source: https://context7.com/stereokit/stereokit/llms.txt Covers loading textures from image files asynchronously and creating textures procedurally from color arrays. Also demonstrates generating a cubemap for environment lighting. ```csharp // Load from file (asynchronous) Tex albedo = Tex.FromFile("Metal_Albedo.png", sRGBData: true); Tex normal = Tex.FromFile("Metal_Normal.png", sRGBData: false); Tex metalRough = Tex.FromFile("Metal_MRAO.png", sRGBData: false); // Subscribe to async load completion albedo.OnLoaded += tex => Console.WriteLine($"Loaded {tex.Width}x{tex.Height}"); // Create texture procedurally from Color32 array int w = 64, h = 64; Color32[] pixels = new Color32[w * h]; for (int i = 0; i < pixels.Length; i++) pixels[i] = (i / w + i % w) % 2 == 0 ? Color32.White : Color32.Black; Tex checkerboard = Tex.FromColors(pixels, w, h); // Generate a gradient-based cubemap for the sky and scene lighting Gradient gradient = new Gradient( new GradientKey(new Color(0.1f, 0.1f, 0.3f), 0.0f), new GradientKey(new Color(0.8f, 0.8f, 1.0f), 0.5f), new GradientKey(new Color(1.0f, 0.9f, 0.6f), 1.0f)); SphericalHarmonics lighting; Tex sky = Tex.GenCubemap(gradient, out lighting, Vec3.Up, resolution: 128); Renderer.SkyTex = sky; Renderer.SkyLight = lighting; // Apply to a material Material mat = Material.PBR.Copy(); mat[MatParamName.DiffuseTex] = albedo; mat[MatParamName.NormalTex] = normal; mat[MatParamName.MetalTex] = metalRough; SK.Run(() => { Mesh.GenerateSphere(0.15f).Draw(mat, Matrix.T(0, 0, -0.5f)); }); ``` -------------------------------- ### Material Customization and Usage Source: https://context7.com/stereokit/stereokit/llms.txt Explains how to create, copy, and modify materials. Covers setting shader parameters, transparency, face culling, and wireframe properties, as well as creating materials from custom shaders. ```APIDOC ## Material — Shading and Render State `Material` pairs a `Shader` with its parameter values and controls render state (transparency, face culling, wireframe, depth testing). The library provides built-in PBR, Unlit, and clip variants. ```csharp // Copy a built-in material to get a modifiable instance Material pbr = Material.PBR.Copy(); pbr[MatParamName.ColorTint] = new Color(0.8f, 0.3f, 0.1f); pbr[MatParamName.MetallicAmount] = 0.8f; pbr[MatParamName.RoughnessAmount] = 0.2f; pbr[MatParamName.NormalTex] = Tex.FromFile("BrickNormal.png"); // Transparent material Material glass = Material.PBR.Copy(); glass.Transparency = Transparency.Blend; glass.FaceCull = Cull.None; // double-sided // Unlit material for UI elements / debug Material unlit = Material.Unlit.Copy(); unlit[MatParamName.DiffuseTex] = Tex.FromFile("Icon.png"); unlit.Wireframe = false; // Create material from a custom HLSL shader Shader customShader = Shader.FromFile("MyShader.hlsl"); Material customMat = new Material(customShader); customMat["_MyColor"] = new Color(1, 0.5f, 0, 1); customMat["_Scale"] = 2.0f; SK.Run(() => { Mesh.GenerateSphere(0.1f).Draw(pbr, Matrix.T(-0.3f, 0, -0.6f)); Mesh.GenerateSphere(0.1f).Draw(glass, Matrix.T(0, 0, -0.6f)); Mesh.GenerateSphere(0.1f).Draw(unlit, Matrix.T( 0.3f, 0, -0.6f)); }); ``` ``` -------------------------------- ### Initialize and Resize Canvas for StereoKit Web Demo Source: https://github.com/stereokit/stereokit/blob/master/tools/web_build/index.htm Sets up the canvas element for the StereoKit WebGL/WASM demo and handles window resize events to maintain correct canvas dimensions and trigger StereoKit's resize callback. ```javascript var resize_time; function canvas_resize(){ clearTimeout(resize_time); resize_time = setTimeout(function() { var canv = document.getElementById('canvas'); canv.width = canv.offsetWidth; canv.height = canv.offsetHeight; _sk_web_canvas_resize(canv.width, canv.height); }, 200); } var canv = document.getElementById('canvas'); canv.width = canv.offsetWidth; canv.height = canv.offsetHeight; var Module = { canvas: canv }; window.addEventListener('resize', canvas_resize, false); ``` -------------------------------- ### Run Native Test App (Linux) Source: https://github.com/stereokit/stereokit/blob/master/BUILDING.md Executes the native StereoKit test application after building with CMake. ```shell # Run the native test app ./bin/intermediate/cmake/Linux_x64_Release/StereoKitCTest ``` -------------------------------- ### Customize Materials for Shading Source: https://context7.com/stereokit/stereokit/llms.txt Shows how to modify built-in materials like PBR and Unlit, and create custom materials from HLSL shaders. Useful for controlling appearance, transparency, and render states. ```csharp // Copy a built-in material to get a modifiable instance Material pbr = Material.PBR.Copy(); pbr[MatParamName.ColorTint] = new Color(0.8f, 0.3f, 0.1f); pbr[MatParamName.MetallicAmount] = 0.8f; pbr[MatParamName.RoughnessAmount] = 0.2f; pbr[MatParamName.NormalTex] = Tex.FromFile("BrickNormal.png"); // Transparent material Material glass = Material.PBR.Copy(); glass.Transparency = Transparency.Blend; glass.FaceCull = Cull.None; // double-sided // Unlit material for UI elements / debug Material unlit = Material.Unlit.Copy(); unlit[MatParamName.DiffuseTex] = Tex.FromFile("Icon.png"); unlit.Wireframe = false; // Create material from a custom HLSL shader Shader customShader = Shader.FromFile("MyShader.hlsl"); Material customMat = new Material(customShader); customMat["_MyColor"] = new Color(1, 0.5f, 0, 1); customMat["_Scale"] = 2.0f; SK.Run(() => { Mesh.GenerateSphere(0.1f).Draw(pbr, Matrix.T(-0.3f, 0, -0.6f)); Mesh.GenerateSphere(0.1f).Draw(glass, Matrix.T(0, 0, -0.6f)); Mesh.GenerateSphere(0.1f).Draw(unlit, Matrix.T( 0.3f, 0, -0.6f)); }); ``` -------------------------------- ### Create and Manipulate Poses in StereoKit Source: https://context7.com/stereokit/stereokit/llms.txt Demonstrates the creation of various Pose objects, including identity, origin, and poses with specific positions and orientations. Shows how to extract direction vectors and convert poses to matrices. Useful for defining object transformations and tracking spatial relationships. ```csharp // Create poses Pose identity = Pose.Identity; // origin, facing +Z Pose atOrigin = new Pose(Vec3.Zero, Quat.Identity); Pose inFront = new Pose(new Vec3(0, 0, -0.5f), Quat.LookDir(0, 0, 1)); Pose tilted = new Pose(0, 0.5f, -1f, Quat.FromAngles(30, 0, 0)); // Direction vectors derived from orientation Vec3 fwd = inFront.Forward; // -Z direction of the pose Vec3 right = inFront.Right; Vec3 up = inFront.Up; Ray ray = inFront.Ray; // Ray from position in Forward direction // Convert pose to Matrix Matrix m = inFront.ToMatrix(); Matrix s = inFront.ToMatrix(scale: 0.1f); // Use head pose for positioning UI relative to the user Pose menuPose = Input.Head; menuPose.position += menuPose.Forward * 0.4f; // place 40 cm in front SK.Run(() => { // Visualize tracking poses Lines.AddAxis(Input.Head, size: 0.05f); Lines.AddAxis(Input.Hand(Handed.Left).wrist, size: 0.03f); Lines.AddAxis(Input.Hand(Handed.Right).palm, size: 0.03f); // Window anchored in front of the user at startup UI.WindowBegin("Info", ref menuPose); UI.Label($"Head: {Input.Head.position}"); UI.WindowEnd(); }); ``` -------------------------------- ### Set NDK Environment Variable (Linux) Source: https://github.com/stereokit/stereokit/blob/master/BUILDING.md Configure the NDK path for Linux systems by adding it to the user's profile. Replace '[user]' with your actual username. ```shell # Linux sudo echo "NDK=~/Android/Sdk/ndk/25.2.9519653" >> ~/.profile ``` -------------------------------- ### Build StereoKit with CMake (Linux) Source: https://github.com/stereokit/stereokit/blob/master/BUILDING.md Builds StereoKit using CMake presets for the Linux x64 Release configuration. ```shell ### From StereoKit's root directory ### # Build using the presets cmake --preset Linux_x64_Release cmake --build --preset Linux_x64_Release ``` -------------------------------- ### Generate Screenshot for Documentation Source: https://github.com/stereokit/stereokit/blob/master/CONTRIBUTING.md Use Tests.Screenshot to capture images for documentation. Specify the filename, dimensions, and optional pose. Ensure the markdown reference correctly points to the generated image URL. ```csharp Tests.Screenshot("Drawing_MeshLooksLike.jpg", 600, 400, V.XYZ(0, 0, 0.12f), Vec3.Zero); ``` ```markdown ![Meshes are made from triangles!]({{site.screen_url}}/Drawing_MeshLooksLike.jpg) ``` -------------------------------- ### Control Scene Rendering and Capture Screenshots with StereoKit Renderer Source: https://context7.com/stereokit/stereokit/llms.txt Configures scene appearance using environment maps and spherical harmonics, and demonstrates rendering meshes directly and capturing screenshots from a custom viewpoint. Requires StereoKit initialization. ```csharp // Configure scene appearance at startup Tex envMap = Tex.FromFile("outdoor.hdr"); SphericalHarmonics sh = SphericalHarmonics.FromLights(new LightSource[] { new LightSource { directionTo = Vec3.Up, color = new Color(1, 0.9f, 0.8f) } }); Renderer.SkyTex = envMap; Renderer.SkyLight = sh; Renderer.EnableSky = true; Renderer.Scaling = 1.5f; // 150% of the runtime's recommended resolution // Draw a mesh directly via Renderer (bypass model transform overhead) Mesh mesh = Mesh.GenerateCube(Vec3.One * 0.1f); Material mat = Material.PBR.Copy(); SK.Run(() => { // Add to render queue with full control over layer and tint Renderer.Add(mesh, mat, Matrix.T(0, 0, -0.5f), Color.White, RenderLayer.Layer1); // Screenshot to disk from a custom viewpoint if (Input.Key(Key.F12) == BtnState.JustActive) { Renderer.Screenshot( "screenshot.png", from: new Vec3(0, 0.3f, 0.3f), at: Vec3.Zero, width: 1920, height: 1080, fieldOfViewDegrees: 60); } }); ``` -------------------------------- ### Include Raw Assets in MAUI Project Source: https://github.com/stereokit/stereokit/blob/master/tools/VSTemplates/SKTemplate_Maui/Assets/AboutAssets.txt Add this entry to your project file to include raw assets. Ensure the Build Action is set to 'MauiAsset'. ```xml ``` -------------------------------- ### Load MAUI Asset at Runtime Source: https://github.com/stereokit/stereokit/blob/master/tools/VSTemplates/SKTemplate_Maui/Assets/AboutAssets.txt Use `FileSystem.OpenAppPackageFileAsync` to load raw assets deployed with your MAUI application. The file name must match the asset name included in the project file. ```csharp async Task LoadMauiAsset() { using var stream = await FileSystem.OpenAppPackageFileAsync("AboutAssets.txt"); using var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); } ``` -------------------------------- ### Input Handling with StereoKit Source: https://context7.com/stereokit/stereokit/llms.txt Captures and visualizes input data from hands, motion controllers, head pose, and eye tracking. Requires device support and permissions for eye tracking. ```csharp SK.Run(() => { // --- Hand input --- Hand right = Input.Hand(Handed.Right); if (right.IsTracked) { // Visualize the index fingertip HandJoint tip = right[FingerId.Index, JointId.Tip]; Lines.AddAxis(tip.Pose, 0.01f); if (right.IsJustPinched) Log.Info("Right hand pinched!"); if (right.IsJustGripped) Log.Info("Right hand gripped! Activation: {0:F2}", right.gripActivation); } // --- Controller input --- Controller ctrl = Input.Controller(Handed.Right); if (ctrl.IsTracked) { // Aim ray for far interactions Lines.Add(ctrl.aim.Ray, 0.5f, new Color32(0, 200, 255, 200), 0.002f); if (ctrl.IsX1JustPressed) Log.Info("A / X button pressed"); if (ctrl.trigger > 0.9f) Log.Info($"Trigger: {ctrl.trigger:F2}"); Vec2 stick = ctrl.stick; if (stick.Magnitude > 0.2f) Log.Info($"Stick: ({stick.x:F2}, {stick.y:F2})"); } // --- Head pose --- Pose head = Input.Head; Lines.AddAxis(head, 0.05f); // --- Eye tracking (requires device support + permission) --- if (SK.System.eyeTrackingPresent && Input.EyesTracked.IsActive()) { Pose eyes = Input.Eyes; Lines.Add(eyes.Ray, 1.0f, new Color32(255, 220, 0, 180), 0.001f); } }); ``` -------------------------------- ### Post-Build Command to Copy Binaries and Headers Source: https://github.com/stereokit/stereokit/blob/master/CMakeLists.txt Defines a custom post-build command for the StereoKitC target to create distribution directories and copy the built binary and header files. It organizes files by OS, architecture, and build configuration. ```cmake set(SK_DISTRIBUTE_FOLDER "bin/distribute") add_custom_command(TARGET StereoKitC POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory "${CMAKE_CURRENT_SOURCE_DIR}/${SK_DISTRIBUTE_FOLDER}/bin/${SK_BIN_OS}/${SK_ARCH}/$" COMMAND ${CMAKE_COMMAND} -E copy_if_different "$" "${CMAKE_CURRENT_SOURCE_DIR}/${SK_DISTRIBUTE_FOLDER}/bin/${SK_BIN_OS}/${SK_ARCH}/$/$" COMMAND ${CMAKE_COMMAND} -E make_directory "${CMAKE_CURRENT_SOURCE_DIR}/${SK_DISTRIBUTE_FOLDER}/include" COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/StereoKitC/stereokit.h" "${CMAKE_CURRENT_SOURCE_DIR}/StereoKitC/stereokit_ui.h" "${CMAKE_CURRENT_SOURCE_DIR}/${SK_DISTRIBUTE_FOLDER}/include/" ) ``` -------------------------------- ### Android Resource Directory Structure Source: https://github.com/stereokit/stereokit/blob/master/Examples/StereoKitTest/StereoKitTest_Xamarin/Resources/AboutResources.txt Illustrates the typical directory structure for Android resources within an application. Ensure your resource files are placed in the appropriate subdirectories. ```text Resources/ drawable/ icon.png layout/ main.xml values/ strings.xml ``` -------------------------------- ### Add Standalone Document Page Source: https://github.com/stereokit/stereokit/blob/master/CONTRIBUTING.md Use ':CodeDoc:' tags to create standalone documentation pages. Specify a category, sort index, and name for the document. This is useful for tutorials and concept explanations. ```csharp /// :CodeDoc: Guides 5 Drawing /// # Drawing content with StereoKit /// /// ... using StereoKit; /// /// :End: // doesn't include this in the document namespace Guides { /// :CodeDoc: Guides Drawing /// ... /// :End: ``` -------------------------------- ### Draw Various Line Types with StereoKit Lines API Source: https://context7.com/stereokit/stereokit/llms.txt Demonstrates drawing simple colored lines, gradient lines, ray visualizations, multi-point polylines, and axis widgets. Ensure StereoKit is initialized before use. ```csharp SK.Run(() => { // Simple colored line segment Lines.Add( new Vec3(-0.2f, 0, -0.5f), new Vec3( 0.2f, 0, -0.5f), new Color32(255, 80, 80, 255), thickness: 0.003f); // Gradient line (different start/end colors) Lines.Add( new Vec3(0, -0.1f, -0.5f), new Vec3(0, 0.1f, -0.5f), new Color32(0, 0, 255, 255), new Color32(0, 255, 0, 255), thickness: 0.004f); // Ray visualization Ray pointerRay = new Ray(Input.Head.position, Input.Head.Forward); Lines.Add(pointerRay, length: 0.5f, new Color32(255, 255, 0, 180), 0.002f); // Multi-point polyline LinePoint[] path = new LinePoint[] { new LinePoint(new Vec3(-0.1f, 0, -0.6f), new Color32(255,0,0,255), 0.004f), new LinePoint(new Vec3( 0, 0.1f, -0.6f), new Color32(0,255,0,255), 0.004f), new LinePoint(new Vec3( 0.1f, 0, -0.6f), new Color32(0,0,255,255), 0.004f), new LinePoint(new Vec3( 0, -0.1f, -0.6f), new Color32(255,255,0,255), 0.004f), }; Lines.Add(path); // Axis widget at hand wrist Hand hand = Input.Hand(Handed.Right); if (hand.IsTracked) Lines.AddAxis(hand.wrist, size: 0.03f); }); ``` -------------------------------- ### Model - 3D Asset Loading and Drawing Source: https://context7.com/stereokit/stereokit/llms.txt Loads and draws 3D models from various file formats or builds them programmatically. Supports skeletal animation playback and inspecting model bounds. Use Model.FromFile for common formats, Model.FromMemory for embedded data, and Model.FromMesh for procedural generation. ```csharp // Load from file (async, returns immediately with a placeholder) Model robot = Model.FromFile("Robot.glb"); // Load from raw bytes (useful for embedded resources) byte[] data = File.ReadAllBytes("Widget.glb"); Model widget = Model.FromMemory("Widget.glb", data); // Build programmatically from mesh + material Mesh sphere = Mesh.GenerateSphere(0.1f); Material mat = Material.PBR.Copy(); mat[MatParamName.ColorTint] = new Color(1f, 0.2f, 0.2f); Model redBall = Model.FromMesh(sphere, mat); // Skeletal animation playback Model character = Model.FromFile("Character.glb"); character.PlayAnim("Walk", AnimMode.Loop); Pose animPose = new Pose(0.5f, 0, -1f, Quat.Identity); SK.Run(() => { // Draw at a specific transform; Matrix.TRS = Translation * Rotation * Scale robot?.Draw(Matrix.TRS( new Vec3(0, 0, -1f), Quat.FromAngles(0, Time.Totalf * 20f, 0), Vec3.One)); // Inspect model bounds for interaction / clipping if (robot != null) Lines.Add(robot.Bounds.Center, robot.Bounds.Center + Vec3.Up * 0.01f, new Color32(255, 255, 0, 255), 0.002f); }); ``` -------------------------------- ### Post-Build Command to Copy Tools Source: https://github.com/stereokit/stereokit/blob/master/CMakeLists.txt Adds a custom post-build command to copy the 'tools' directory to 'tools/skshaderc' relative to the current source directory. ```cmake add_custom_command(TARGET StereoKitC POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory "${sk_gpu_SOURCE_DIR}/tools" "${CMAKE_CURRENT_SOURCE_DIR}/tools/skshaderc" ) ``` -------------------------------- ### SK.Step — Manual Frame Loop Source: https://context7.com/stereokit/stereokit/llms.txt Provides an alternative to SK.Run for scenarios where manual control over the frame loop is required, such as integration with game engines. SK.Step advances StereoKit by one frame and returns false when the application should exit. ```APIDOC ## SK.Step — Manual Frame Loop `SK.Step` advances StereoKit by one frame and returns `false` when the application should exit. Use this when you need to manage the loop yourself (e.g., game engine integration). ```csharp if (!SK.Initialize("ManualLoopApp")) return; Model cube = Model.FromMesh( Mesh.GenerateCube(Vec3.One * 0.2f), Material.PBR.Copy()); while (SK.Step(() => { cube.Draw(Matrix.TR(new Vec3(0, 0, -0.5f), Quat.FromAngles(0, Time.Totalf * 30f, 0))); })) { /* outer loop for platform tasks if needed */ } SK.Shutdown(); ``` ``` -------------------------------- ### Accessing Raw Assets in Android Source: https://github.com/stereokit/stereokit/blob/master/Examples/StereoKitTest/StereoKitTest_Xamarin/Assets/AboutAssets.txt Place raw assets in the 'Assets' directory with a 'AndroidAsset' build action. Access them using Android's AssetManager. ```csharp public class ReadAsset : Activity { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); InputStream input = Assets.Open ("my_asset.txt"); } } ``` -------------------------------- ### Apply Compile and Link Options to openxr_loader Source: https://github.com/stereokit/stereokit/blob/master/CMakeLists.txt Applies warning flags and release-specific compile/link options to the 'openxr_loader' target if SK_BUILD_OPENXR_LOADER is enabled. ```cmake if (SK_BUILD_OPENXR_LOADER) target_compile_options(openxr_loader PRIVATE ${SK_WARNING_FLAG}) target_compile_options(openxr_loader PRIVATE "$<$:${SK_RELEASE_COMPILE}>") target_link_options (openxr_loader PRIVATE ${SK_LINKER_FLAGS} "$<$:${SK_RELEASE_LINK}>") endif() ``` -------------------------------- ### StereoKit Diagnostic Logging Source: https://context7.com/stereokit/stereokit/llms.txt Configures and utilizes StereoKit's logging system for diagnostic messages. Shows how to set the log filter level and subscribe to log events for custom handling, such as writing to a file. Essential for debugging and monitoring application state. ```csharp // Set filter before SK.Initialize to capture init messages Log.Filter = LogLevel.Diagnostic; // Register a custom callback (e.g., to write to a file) Log.Subscribe((LogLevel level, string text) => { File.AppendAllText("app.log", $ ``` ```csharp [{level}] {text} ``` ```csharp }); if (!SK.Initialize("LogDemo")) return; Log.Info("App started. Version: {0}", SK.VersionName); Log.Warn("This is a <~YLW>warning<~clr> message."); Log.Err ("This is an <~RED>error<~clr> message."); Log.Diag("Diagnostic: eye tracking = {0}", SK.System.eyeTrackingPresent); int frame = 0; SK.Run(() => { frame++; if (frame % 600 == 0) Log.Info("Frame {0} — {1:F1} ms/frame", frame, Time.Stepf * 1000); }); ``` -------------------------------- ### SK.Step - Manual Frame Loop Source: https://context7.com/stereokit/stereokit/llms.txt Advances StereoKit by one frame, returning false when the application should exit. This is useful for integrating StereoKit into existing game engines or custom loop structures. Ensure SK.Shutdown() is called after the loop. ```csharp if (!SK.Initialize("ManualLoopApp")) return; Model cube = Model.FromMesh( Mesh.GenerateCube(Vec3.One * 0.2f), Material.PBR.Copy()); while (SK.Step(() => { cube.Draw(Matrix.TR(new Vec3(0, 0, -0.5f), Quat.FromAngles(0, Time.Totalf * 30f, 0))); })) { /* outer loop for platform tasks if needed */ } SK.Shutdown(); ``` -------------------------------- ### Early Return for Simplicity Source: https://github.com/stereokit/stereokit/blob/master/CONTRIBUTING.md Utilize early returns to avoid deep indentation and improve code readability. This pattern simplifies control flow. ```cpp void function() { if (!condition) return; // Do stuff } ``` ```cpp void function() { if (condition) { // Do stuff } } ``` -------------------------------- ### Post-Build Command for Dynamic OpenXR Loader Source: https://github.com/stereokit/stereokit/blob/master/CMakeLists.txt Conditionally adds a post-build command to copy the 'openxr_loader' target if SK_DYNAMIC_OPENXR is enabled, placing it in a 'standard' subdirectory within the distribution path. ```cmake if (SK_DYNAMIC_OPENXR) add_custom_command(TARGET StereoKitC POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory "${CMAKE_CURRENT_SOURCE_DIR}/${SK_DISTRIBUTE_FOLDER}/bin/${SK_BIN_OS}/${SK_ARCH}/$/standard" COMMAND ${CMAKE_COMMAND} -E copy_if_different "$" "${CMAKE_CURRENT_SOURCE_DIR}/${SK_DISTRIBUTE_FOLDER}/bin/${SK_BIN_OS}/${SK_ARCH}/$/standard/$" ) endif() ``` -------------------------------- ### Apply Compile and Link Options to reactphysics3d Source: https://github.com/stereokit/stereokit/blob/master/CMakeLists.txt Applies warning flags and release-specific compile/link options to the 'reactphysics3d' target if SK_PHYSICS is enabled. ```cmake if (SK_PHYSICS) target_compile_options(reactphysics3d PRIVATE ${SK_WARNING_FLAG}) target_compile_options(reactphysics3d PRIVATE "$<$:${SK_RELEASE_COMPILE}>") target_link_options (reactphysics3d PRIVATE "$<$:${SK_RELEASE_LINK}>") endif() ```