{"TotalCount":11,"Files":[{"Ident":"alex.rsm","Path":"Code/RetroPostProcess.cs","FileName":"RetroPostProcess.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":449511,"IsPrivate":false,"Code":"using Sandbox;\nusing Sandbox.Rendering;\n\n/// \u003Csummary\u003E\n/// Camera looks inspired by different eras of 3D rendering.\n/// \u003C/summary\u003E\npublic enum RetroCameraPreset\n{\n\tCustom,\n\t[Title( \u0022PSX\u0022 )] PSX,\n\t[Title( \u0022Half-Life 1\u0022 )] HalfLife1,\n\t[Title( \u0022Half-Life 2\u0022 )] HalfLife2\n}\n\n/// \u003Csummary\u003E\n/// Color precision applied after rendering.\n/// \u003C/summary\u003E\npublic enum RetroColorDepth\n{\n\t[Title( \u0022Legacy (Dither Only)\u0022 )] Legacy,\n\t[Title( \u0022Full Color (No Reduction)\u0022 )] FullColor,\n\t[Title( \u00228-bit (RGB 3:3:2)\u0022 )] Rgb332,\n\t[Title( \u002215-bit (RGB 5:5:5)\u0022 )] Rgb555,\n\t[Title( \u002216-bit (RGB 5:6:5)\u0022 )] Rgb565,\n\t[Title( \u002224-bit (RGB 8:8:8)\u0022 )] Rgb888,\n\t[Title( \u0022Custom Bits per Channel\u0022 )] CustomBits,\n\t[Title( \u0022Custom Levels per Channel\u0022 )] CustomLevels\n}\n\n/// \u003Csummary\u003E\n/// Texture filtering override for compatible retro materials.\n/// \u003C/summary\u003E\npublic enum RetroTextureFiltering\n{\n\t[Title( \u0022Material Default\u0022 )] MaterialDefault = 0,\n\tPoint = 1,\n\tBilinear = 2,\n\tTrilinear = 3\n}\n\n/// \u003Csummary\u003E\n/// Controls retro material detail and applies pixelation, ordered dithering and aspect-ratio bars.\n/// \u003C/summary\u003E\n[Title( \u0022Retro Camera Controls\u0022 )]\n[Category( \u0022Post Processing\u0022 )]\n[Icon( \u0022filter_vintage\u0022 )]\npublic sealed class RetroPostProcess : BasePostProcess\u003CRetroPostProcess\u003E\n{\n\t/// \u003Csummary\u003E\n\t/// Select a look, or choose Custom to use the settings below.\n\t/// Custom settings are preserved when switching between presets.\n\t/// Presets affect post-processing and retro detail textures, not material filtering or lighting.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Presets\u0022, Order = -1 )] public RetroCameraPreset Preset { get; set; } = RetroCameraPreset.Custom;\n\n\t/// \u003Csummary\u003E\n\t/// Controls the color precision of the final image. Legacy reduces colors only when dithering is enabled.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public RetroColorDepth ColorDepth { get; set; } = RetroColorDepth.Legacy;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowColorBits ), true ), Range( 1, 8 )] public int RedBits { get; set; } = 5;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowColorBits ), true ), Range( 1, 8 )] public int GreenBits { get; set; } = 5;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowColorBits ), true ), Range( 1, 8 )] public int BlueBits { get; set; } = 5;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowColorLevels ), true ), Range( 2, 256 )] public float ColorLevels { get; set; } = 32;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowDither ), true )] public bool Dither { get; set; } = true;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowDitherStrength ), true ), Range( 0, 1 )] public float DitherStrength { get; set; } = 0.5f;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public bool Downscale { get; set; } = true;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public bool Crop { get; set; } = true;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public Vector2 TargetResolution { get; set; } = new( 320, 240 );\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public Vector2 TargetAspect { get; set; } = new( 4, 3 );\n\n\tprivate bool ShowColorBits =\u003E Preset == RetroCameraPreset.Custom \u0026\u0026 ColorDepth == RetroColorDepth.CustomBits;\n\tprivate bool ShowColorLevels =\u003E Preset == RetroCameraPreset.Custom \u0026\u0026 ColorDepth is RetroColorDepth.Legacy or RetroColorDepth.CustomLevels;\n\tprivate bool ShowDither =\u003E Preset == RetroCameraPreset.Custom \u0026\u0026 ColorDepth != RetroColorDepth.FullColor;\n\tprivate bool ShowDitherStrength =\u003E ShowDither \u0026\u0026 Dither;\n\n\t/// \u003Csummary\u003E\n\t/// Enables detail textures on retro materials visible to this camera.\n\t/// Each material must also have its detail texture feature enabled.\n\t/// Camera post-processing must be enabled for this setting to apply.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Rendering\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public bool UseDetailTextures { get; set; } = true;\n\n\t/// \u003Csummary\u003E\n\t/// Overrides texture filtering only on compatible retro materials.\n\t/// Camera post-processing must be enabled for this setting to apply.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Rendering\u0022 )] public RetroTextureFiltering TextureFiltering { get; set; } = RetroTextureFiltering.MaterialDefault;\n\n\t/// \u003Csummary\u003E\n\t/// Applies Gouraud shading to directional diffuse lighting only on compatible retro materials.\n\t/// Point and spot lights remain per pixel. Camera post-processing must be enabled for this setting to apply.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Rendering\u0022 ), Title( \u0022Gouraud Shading (Sun Diffuse)\u0022 )] public bool GouraudSunDiffuse { get; set; } = false;\n\n\t/// \u003Csummary\u003E\n\t/// Uses a texel-aligned approximation of lighting and shadows only on compatible retro materials.\n\t/// Camera post-processing must be enabled for this setting to apply.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Rendering\u0022 ), Title( \u0022Texel Lighting and Shadows\u0022 )] public bool TexelLighting { get; set; } = false;\n\n\tinternal readonly record struct CameraSettings(\n\t\tbool Dither, bool Downscale, bool Crop, Vector2 TargetResolution, Vector2 TargetAspect,\n\t\tfloat ColorLevels, float DitherStrength, bool UseDetailTextures, RetroColorDepth ColorDepth,\n\t\tint RedBits, int GreenBits, int BlueBits )\n\t{\n\t\tpublic bool ApplyReduction =\u003E ColorDepth switch\n\t\t{\n\t\t\tRetroColorDepth.FullColor =\u003E false,\n\t\t\tRetroColorDepth.Legacy =\u003E Dither,\n\t\t\t_ =\u003E true\n\t\t};\n\n\t\tpublic bool ApplyDither =\u003E Dither \u0026\u0026 ColorDepth != RetroColorDepth.FullColor;\n\n\t\tpublic Vector3 ChannelLevels =\u003E ColorDepth switch\n\t\t{\n\t\t\tRetroColorDepth.Rgb332 =\u003E new( 8, 8, 4 ),\n\t\t\tRetroColorDepth.Rgb555 =\u003E new( 32, 32, 32 ),\n\t\t\tRetroColorDepth.Rgb565 =\u003E new( 32, 64, 32 ),\n\t\t\tRetroColorDepth.Rgb888 =\u003E new( 256, 256, 256 ),\n\t\t\tRetroColorDepth.CustomBits =\u003E new(\n\t\t\t\t1 \u003C\u003C System.Math.Clamp( RedBits, 1, 8 ),\n\t\t\t\t1 \u003C\u003C System.Math.Clamp( GreenBits, 1, 8 ),\n\t\t\t\t1 \u003C\u003C System.Math.Clamp( BlueBits, 1, 8 ) ),\n\t\t\t_ =\u003E new( ColorLevels, ColorLevels, ColorLevels )\n\t\t};\n\t}\n\n\tinternal CameraSettings EffectiveSettings =\u003E Preset switch\n\t{\n\t\tRetroCameraPreset.PSX =\u003E new( true, true, true, new( 320, 240 ), new( 4, 3 ), 32, 1, false, RetroColorDepth.Rgb555, 5, 5, 5 ),\n\t\tRetroCameraPreset.HalfLife1 =\u003E new( false, true, true, new( 640, 480 ), new( 4, 3 ), 256, 0, false, RetroColorDepth.FullColor, 5, 6, 5 ),\n\t\tRetroCameraPreset.HalfLife2 =\u003E new( false, true, true, new( 1024, 768 ), new( 4, 3 ), 256, 0, true, RetroColorDepth.FullColor, 8, 8, 8 ),\n\t\t_ =\u003E new( Dither, Downscale, Crop, TargetResolution, TargetAspect, ColorLevels, DitherStrength, UseDetailTextures, ColorDepth, RedBits, GreenBits, BlueBits )\n\t};\n\n\t/// \u003Csummary\u003E\n\t/// Copies the selected preset to Custom so its settings can be adjusted.\n\t/// \u003C/summary\u003E\n\t[Button( \u0022Edit Preset\u0022 ), Group( \u0022Presets\u0022, Order = -1 ), HideIf( nameof( Preset ), RetroCameraPreset.Custom )]\n\tpublic void EditPreset()\n\t{\n\t\tvar settings = EffectiveSettings;\n\t\tusing var undo = Scene.Editor?.UndoScope( \u0022Edit Retro Preset\u0022 ).WithComponentChanges( this ).Push();\n\t\tDither = settings.Dither;\n\t\tDownscale = settings.Downscale;\n\t\tCrop = settings.Crop;\n\t\tTargetResolution = settings.TargetResolution;\n\t\tTargetAspect = settings.TargetAspect;\n\t\tColorDepth = settings.ColorDepth;\n\t\tRedBits = settings.RedBits;\n\t\tGreenBits = settings.GreenBits;\n\t\tBlueBits = settings.BlueBits;\n\t\tColorLevels = settings.ColorLevels;\n\t\tDitherStrength = settings.DitherStrength;\n\t\tUseDetailTextures = settings.UseDetailTextures;\n\t\tPreset = RetroCameraPreset.Custom;\n\t}\n\n\tprivate RetroDetailCameraEffect detailEffect;\n\n\tprotected override void OnEnabled()\n\t{\n\t\t// Scene attributes are merged into each camera before camera effects are applied.\n\t\tScene.RenderAttributes.Set( \u0022RetroDetailTexturesDisabled\u0022, 0.0f );\n\t\tScene.RenderAttributes.Set( \u0022RetroTextureFiltering\u0022, 0.0f );\n\t\tScene.RenderAttributes.Set( \u0022RetroGouraudSunDiffuse\u0022, 0.0f );\n\t\tScene.RenderAttributes.Set( \u0022RetroTexelLighting\u0022, 0.0f );\n\t\tdetailEffect = GameObject.Components.Create\u003CRetroDetailCameraEffect\u003E( false );\n\t\tdetailEffect.Flags = ComponentFlags.Hidden | ComponentFlags.NotSaved | ComponentFlags.NotCloned | ComponentFlags.NotNetworked;\n\t\tdetailEffect.Controls = this;\n\t\tdetailEffect.Enabled = true;\n\t}\n\n\tprotected override void OnDisabled()\n\t{\n\t\tdetailEffect?.Destroy();\n\t\tdetailEffect = null;\n\t}\n\n\tprivate static readonly Material Shader = Material.FromShader( \u0022shaders/retro_postprocess.shader\u0022 );\n\n\tpublic override void Render()\n\t{\n\t\tvar reduction = GetWeighted( x =\u003E x.EffectiveSettings.ApplyReduction ? 1.0f : 0.0f );\n\t\tvar dither = GetWeighted( x =\u003E x.EffectiveSettings.ApplyDither ? 1.0f : 0.0f );\n\t\tvar downscale = GetWeighted( x =\u003E x.EffectiveSettings.Downscale ? 1.0f : 0.0f );\n\t\tvar crop = GetWeighted( x =\u003E x.EffectiveSettings.Crop ? 1.0f : 0.0f );\n\t\tif ( reduction \u003C= 0 \u0026\u0026 downscale \u003C= 0 \u0026\u0026 crop \u003C= 0 ) return;\n\n\t\tAttributes.Set( \u0022ColorReduction\u0022, reduction );\n\t\tAttributes.Set( \u0022Dither\u0022, dither );\n\t\tAttributes.Set( \u0022Downscale\u0022, downscale );\n\t\tAttributes.Set( \u0022Crop\u0022, crop );\n\t\tAttributes.Set( \u0022TargetResolution\u0022, GetWeighted( x =\u003E x.EffectiveSettings.TargetResolution, new Vector2( 320, 240 ) ) );\n\t\tAttributes.Set( \u0022TargetAspect\u0022, GetWeighted( x =\u003E x.EffectiveSettings.TargetAspect, new Vector2( 4, 3 ) ) );\n\t\tAttributes.Set( \u0022ColorLevels\u0022, GetWeighted( x =\u003E x.EffectiveSettings.ChannelLevels, new Vector3( 256, 256, 256 ) ) );\n\t\tAttributes.Set( \u0022DitherStrength\u0022, GetWeighted( x =\u003E x.EffectiveSettings.DitherStrength ) );\n\n\t\tBlit( BlitMode.WithBackbuffer( Shader, Stage.AfterPostProcess, 10000 ), \u0022Retro Post Process\u0022 );\n\t}\n}\n"},{"Ident":"alex.rsm","Path":"UnitTests/UnitTest.cs","FileName":"UnitTest.cs","PackageType":"library","CodeKind":"UnitTest","AssetVersionId":449511,"IsPrivate":false,"Code":"global using Microsoft.VisualStudio.TestTools.UnitTesting;\r\n\r\n[TestClass]\r\npublic class TestInit\r\n{\r\n\tpublic static Sandbox.TestAppSystem AppSystem;\r\n\r\n\t[AssemblyInitialize]\r\n\tpublic static void AssemblyInitialize( TestContext context )\r\n\t{\r\n\t\tAppSystem = new Sandbox.TestAppSystem();\r\n\t\tAppSystem.Init();\r\n\t}\r\n\r\n\t[AssemblyCleanup]\r\n\tpublic static void AssemblyCleanup()\r\n\t{\r\n\t\tAppSystem.Shutdown();\r\n\t}\r\n}\r\n"},{"Ident":"alex.rsm","Path":".obj/__compiler_extra.cs","FileName":"__compiler_extra.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":449511,"IsPrivate":false,"Code":"global using static Sandbox.Internal.GlobalGameNamespace;\nglobal using Microsoft.AspNetCore.Components;\nglobal using Microsoft.AspNetCore.Components.Rendering;\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonTitle\u0022, \u0022Retro Shading Model\u0022 )]\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonIdent\u0022, \u0022rsm\u0022 )]\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022OrgIdent\u0022, \u0022alex\u0022 )]\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022Ident\u0022, \u0022alex.rsm\u0022 )]\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineVersion\u0022, \u002233\u0022 )]\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineMinorVersion\u0022, \u00221\u0022 )]\n\n[assembly: System.Runtime.Versioning.TargetFramework( \u0022.NETCoreApp,Version=v9.0\u0022, FrameworkDisplayName = \u0022.NET 9.0\u0022 )]"},{"Ident":"alex.rsm","Path":"ShowcaseSpin.cs","FileName":"ShowcaseSpin.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":449511,"IsPrivate":false,"Code":"using Sandbox;\n\n[Title( \u0022Showcase Spin\u0022 )]\npublic sealed class ShowcaseSpin : Component\n{\n\t[Property] public float DegreesPerSecond { get; set; } = 30.0f;\n\n\tprotected override void OnUpdate()\n\t{\n\t\tLocalRotation *= Rotation.FromYaw( DegreesPerSecond * Time.Delta );\n\t}\n}\n"},{"Ident":"alex.rsm","Path":"Editor/RetroTextureTool.cs","FileName":"RetroTextureTool.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449511,"IsPrivate":false,"Code":"using System;\r\nusing System.IO;\r\nusing System.Threading.Tasks;\r\nusing Editor;\r\nusing Sandbox;\r\n\r\npublic static class RetroTextureProcessor\r\n{\r\n\t/// \u003Csummary\u003EDownscales an encoded image and returns a quantized PNG. Alpha is not quantized.\u003C/summary\u003E\r\n\tpublic static byte[] Process( byte[] imageData, int maxSize, int colorLevels, bool dither )\r\n\t{\r\n\t\treturn Process( imageData, maxSize, colorLevels, dither, true );\r\n\t}\r\n\r\n\tinternal static byte[] Process( byte[] imageData, int maxSize, int colorLevels, bool dither, bool smooth )\r\n\t{\r\n\t\tArgumentNullException.ThrowIfNull( imageData );\r\n\t\tusing var source = Bitmap.CreateFromBytes( imageData ) ?? throw new InvalidDataException( \u0022The image could not be decoded.\u0022 );\r\n\t\treturn Process( source, maxSize, colorLevels, dither, smooth );\r\n\t}\r\n\r\n\tinternal static byte[] Process( Bitmap source, int maxSize, int colorLevels, bool dither, bool smooth )\r\n\t{\r\n\t\tmaxSize = Math.Clamp( maxSize, 1, 4096 );\r\n\t\tcolorLevels = Math.Clamp( colorLevels, 2, 256 );\r\n\r\n\t\tvar scale = Math.Min( 1.0, (double)maxSize / Math.Max( source.Width, source.Height ) );\r\n\t\tvar width = Math.Max( 1, (int)Math.Round( source.Width * scale ) );\r\n\t\tvar height = Math.Max( 1, (int)Math.Round( source.Height * scale ) );\r\n\t\tusing var resized = source.Resize( width, height, smooth );\r\n\t\tvar pixels = resized.GetPixels();\r\n\t\tint[] bayer = { 0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5 };\r\n\t\tvar steps = colorLevels - 1;\r\n\t\tfor ( var y = 0; y \u003C height; y\u002B\u002B )\r\n\t\t{\r\n\t\t\tfor ( var x = 0; x \u003C width; x\u002B\u002B )\r\n\t\t\t{\r\n\t\t\t\tvar index = y * width \u002B x;\r\n\t\t\t\tvar color = pixels[index];\r\n\t\t\t\tvar offset = dither ? ( ( bayer[( y % 4 ) * 4 \u002B x % 4] \u002B 0.5f ) / 16f - 0.5f ) : 0f;\r\n\t\t\t\tcolor.r = Quantize( color.r, steps, offset );\r\n\t\t\t\tcolor.g = Quantize( color.g, steps, offset );\r\n\t\t\t\tcolor.b = Quantize( color.b, steps, offset );\r\n\t\t\t\tpixels[index] = color;\r\n\t\t\t}\r\n\t\t}\r\n\t\tresized.SetPixels( pixels );\r\n\t\treturn resized.ToPng();\r\n\t}\r\n\r\n\tstatic float Quantize( float value, int steps, float offset )\r\n\t{\r\n\t\treturn Math.Clamp( MathF.Floor( value * steps \u002B offset \u002B 0.5f ), 0, steps ) / steps;\r\n\t}\r\n}\r\n\r\n[EditorApp( \u0022Retro Texture\u0022, \u0022texture\u0022, \u0022Downscale and dither an image\u0022 )]\r\npublic sealed class RetroTextureTool : BaseWindow\r\n{\r\n\treadonly ComboBox size;\r\n\treadonly ComboBox colors;\r\n\treadonly ComboBox dithering;\r\n\treadonly ComboBox sampling;\r\n\treadonly Label inputLabel;\r\n\treadonly Label originalInfo;\r\n\treadonly Label resultInfo;\r\n\treadonly Label status;\r\n\treadonly Button saveButton;\r\n\treadonly RetroTexturePreview originalPreview;\r\n\treadonly RetroTexturePreview resultPreview;\r\n\tstring inputPath;\r\n\tbyte[] inputData;\r\n\tbyte[] resultData;\r\n\tint revision;\r\n\tbool processing;\r\n\r\n\tpublic RetroTextureTool()\r\n\t{\r\n\t\tWindowTitle = \u0022Retro Texture\u0022;\r\n\t\tMinimumSize = new Vector2( 680, 480 );\r\n\t\tSize = new Vector2( 900, 620 );\r\n\t\tLayout = Layout.Column();\r\n\t\tLayout.Margin = 16;\r\n\t\tLayout.Spacing = 10;\r\n\r\n\t\tvar inputRow = Layout.AddRow();\r\n\t\tinputRow.Spacing = 10;\r\n\t\tinputRow.Add( new Button( \u0022Choose Image\u2026\u0022 ) { Clicked = ChooseInput } );\r\n\t\tinputLabel = inputRow.Add( new Label( \u0022No image selected\u0022 ) { WordWrap = true }, 1 );\r\n\r\n\t\tvar previews = Layout.AddRow( 1 );\r\n\t\tpreviews.Spacing = 10;\r\n\t\tvar original = previews.AddColumn( 1 );\r\n\t\toriginalInfo = original.Add( new Label( \u0022Original\u0022 ) );\r\n\t\toriginalPreview = original.Add( new RetroTexturePreview( true ), 1 );\r\n\t\tvar result = previews.AddColumn( 1 );\r\n\t\tresultInfo = result.Add( new Label( \u0022Result\u0022 ) );\r\n\t\tresultPreview = result.Add( new RetroTexturePreview( false ), 1 );\r\n\r\n\t\tvar controls = Layout.AddRow();\r\n\t\tcontrols.Spacing = 10;\r\n\t\tvar sizeColumn = controls.AddColumn( 1 );\r\n\t\tsizeColumn.Add( new Label( \u0022Maximum dimension\u0022 ) );\r\n\t\tsize = sizeColumn.Add( new ComboBox() );\r\n\t\tforeach ( var value in new[] { \u002264\u0022, \u0022128\u0022, \u0022256\u0022, \u0022512\u0022, \u00221024\u0022, \u00222048\u0022, \u00224096\u0022 } ) size.AddItem( value );\r\n\t\tsize.CurrentIndex = 2;\r\n\t\tvar colorsColumn = controls.AddColumn( 1 );\r\n\t\tcolorsColumn.Add( new Label( \u0022Levels per channel\u0022 ) );\r\n\t\tcolors = colorsColumn.Add( new ComboBox() );\r\n\t\tforeach ( var value in new[] { \u00224\u0022, \u00228\u0022, \u002216\u0022, \u002232\u0022, \u002264\u0022, \u0022256\u0022 } ) colors.AddItem( value );\r\n\t\tcolors.CurrentIndex = 2;\r\n\t\tvar ditherColumn = controls.AddColumn( 1 );\r\n\t\tditherColumn.Add( new Label( \u0022Dithering\u0022 ) );\r\n\t\tdithering = ditherColumn.Add( new ComboBox() );\r\n\t\tdithering.AddItem( \u0022Ordered\u0022 );\r\n\t\tdithering.AddItem( \u0022None\u0022 );\r\n\t\tvar samplingColumn = controls.AddColumn( 1 );\r\n\t\tsamplingColumn.Add( new Label( \u0022Resize filter\u0022 ) );\r\n\t\tsampling = samplingColumn.Add( new ComboBox() );\r\n\t\tsampling.AddItem( \u0022Smooth\u0022 );\r\n\t\tsampling.AddItem( \u0022Nearest\u0022 );\r\n\r\n\t\tsize.ItemChanged \u002B= RequestPreview;\r\n\t\tcolors.ItemChanged \u002B= RequestPreview;\r\n\t\tdithering.ItemChanged \u002B= RequestPreview;\r\n\t\tsampling.ItemChanged \u002B= RequestPreview;\r\n\r\n\t\tvar footer = Layout.AddRow();\r\n\t\tfooter.Spacing = 10;\r\n\t\tstatus = footer.Add( new Label( \u0022Choose an image to begin.\u0022 ) { WordWrap = true }, 1 );\r\n\t\tsaveButton = footer.Add( new Button.Primary( \u0022Save PNG\u2026\u0022 ) { Clicked = Save, Enabled = false } );\r\n\t}\r\n\r\n\tvoid ChooseInput()\r\n\t{\r\n\t\tvar dialog = new FileDialog( this ) { Title = \u0022Choose Image\u0022 };\r\n\t\tdialog.SetModeOpen();\r\n\t\tdialog.SetFindExistingFile();\r\n\t\tdialog.SetNameFilter( \u0022Images (*.png *.jpg *.jpeg *.webp *.bmp *.tga *.tif *.tiff *.psd);;All files (*)\u0022 );\r\n\t\tif ( !dialog.Execute() ) return;\r\n\t\tinputPath = dialog.SelectedFile;\r\n\t\tinputData = null;\r\n\t\tinputLabel.Text = Path.GetFileName( inputPath );\r\n\t\toriginalInfo.Text = \u0022Original\u0022;\r\n\t\toriginalPreview.SetImage( null );\r\n\t\tRequestPreview();\r\n\t}\r\n\r\n\tvoid RequestPreview()\r\n\t{\r\n\t\tif ( string.IsNullOrEmpty( inputPath ) ) return;\r\n\t\trevision\u002B\u002B;\r\n\t\tresultData = null;\r\n\t\tsaveButton.Enabled = false;\r\n\t\tresultInfo.Text = \u0022Result\u0022;\r\n\t\tresultPreview.SetImage( null );\r\n\t\tstatus.Text = \u0022Updating preview\u2026\u0022;\r\n\t\tif ( !processing ) UpdatePreview();\r\n\t}\r\n\r\n\tasync void UpdatePreview()\r\n\t{\r\n\t\tprocessing = true;\r\n\t\twhile ( IsValid )\r\n\t\t{\r\n\t\t\tvar currentRevision = revision;\r\n\t\t\tvar path = inputPath;\r\n\t\t\tvar data = inputData;\r\n\t\t\tvar maxSize = int.Parse( size.CurrentText );\r\n\t\t\tvar levels = int.Parse( colors.CurrentText );\r\n\t\t\tvar dither = dithering.CurrentIndex == 0;\r\n\t\t\tvar smooth = sampling.CurrentIndex == 0;\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tvar preview = await Task.Run( () =\u003E CreatePreview( path, data, maxSize, levels, dither, smooth ) );\r\n\t\t\t\tawait MainThread.Wait();\r\n\t\t\t\tif ( !IsValid ) return;\r\n\t\t\t\tif ( currentRevision != revision ) continue;\r\n\t\t\t\tinputData = preview.Input;\r\n\t\t\t\tresultData = preview.Result;\r\n\t\t\t\toriginalPreview.SetImage( preview.OriginalThumbnail );\r\n\t\t\t\tresultPreview.SetImage( preview.ResultThumbnail );\r\n\t\t\t\toriginalInfo.Text = $\u0022Original  \u00B7  {preview.OriginalWidth} \u00D7 {preview.OriginalHeight}\u0022;\r\n\t\t\t\tresultInfo.Text = $\u0022Result  \u00B7  {preview.ResultWidth} \u00D7 {preview.ResultHeight}\u0022;\r\n\t\t\t\tstatus.Text = \u0022Ready to save.\u0022;\r\n\t\t\t\tsaveButton.Enabled = true;\r\n\t\t\t}\r\n\t\t\tcatch ( Exception e )\r\n\t\t\t{\r\n\t\t\t\tawait MainThread.Wait();\r\n\t\t\t\tif ( !IsValid ) return;\r\n\t\t\t\tif ( currentRevision != revision ) continue;\r\n\t\t\t\tstatus.Text = $\u0022Could not process image: {e.Message}\u0022;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tprocessing = false;\r\n\t}\r\n\r\n\tstatic PreviewData CreatePreview( string path, byte[] input, int maxSize, int levels, bool dither, bool smooth )\r\n\t{\r\n\t\tinput ??= File.ReadAllBytes( path );\r\n\t\tusing var original = Bitmap.CreateFromBytes( input ) ?? throw new InvalidDataException( \u0022The image could not be decoded.\u0022 );\r\n\t\tvar result = RetroTextureProcessor.Process( original, maxSize, levels, dither, smooth );\r\n\t\tusing var processed = Bitmap.CreateFromBytes( result ) ?? throw new InvalidDataException( \u0022The result could not be decoded.\u0022 );\r\n\t\treturn new PreviewData( input, result, Thumbnail( original, true ), Thumbnail( processed, false ), original.Width, original.Height, processed.Width, processed.Height );\r\n\t}\r\n\r\n\tstatic byte[] Thumbnail( Bitmap bitmap, bool smooth )\r\n\t{\r\n\t\tvar scale = Math.Min( 1.0, 512.0 / Math.Max( bitmap.Width, bitmap.Height ) );\r\n\t\tusing var thumbnail = bitmap.Resize( Math.Max( 1, (int)Math.Round( bitmap.Width * scale ) ), Math.Max( 1, (int)Math.Round( bitmap.Height * scale ) ), smooth );\r\n\t\treturn thumbnail.ToPng();\r\n\t}\r\n\r\n\tsealed record PreviewData( byte[] Input, byte[] Result, byte[] OriginalThumbnail, byte[] ResultThumbnail, int OriginalWidth, int OriginalHeight, int ResultWidth, int ResultHeight );\r\n\r\n\tasync void Save()\r\n\t{\r\n\t\tif ( resultData == null ) return;\r\n\t\tvar dialog = new FileDialog( this ) { Title = \u0022Save Retro Texture\u0022, DefaultSuffix = \u0022png\u0022 };\r\n\t\tdialog.SetModeSave();\r\n\t\tdialog.SetNameFilter( \u0022PNG image (*.png)\u0022 );\r\n\t\tdialog.SelectFile( Path.Combine( Path.GetDirectoryName( inputPath ), Path.GetFileNameWithoutExtension( inputPath ) \u002B \u0022_retro.png\u0022 ) );\r\n\t\tif ( !dialog.Execute() ) return;\r\n\t\tvar output = dialog.SelectedFile;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif ( !string.Equals( Path.GetExtension( output ), \u0022.png\u0022, StringComparison.OrdinalIgnoreCase ) )\r\n\t\t\t\tthrow new InvalidOperationException( \u0022Choose a PNG filename.\u0022 );\r\n\t\t\tif ( string.Equals( Path.GetFullPath( inputPath ), Path.GetFullPath( output ), StringComparison.OrdinalIgnoreCase ) )\r\n\t\t\t\tthrow new InvalidOperationException( \u0022Choose a different file to preserve the original.\u0022 );\r\n\t\t\tvar data = resultData;\r\n\t\t\tawait Task.Run( () =\u003E File.WriteAllBytes( output, data ) );\r\n\t\t\tawait MainThread.Wait();\r\n\t\t\tif ( IsValid ) status.Text = $\u0022Saved {output}\u0022;\r\n\t\t}\r\n\t\tcatch ( Exception e )\r\n\t\t{\r\n\t\t\tawait MainThread.Wait();\r\n\t\t\tif ( IsValid ) status.Text = $\u0022Could not save image: {e.Message}\u0022;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nsealed class RetroTexturePreview : Widget\r\n{\r\n\tPixmap image;\r\n\treadonly bool smooth;\r\n\r\n\tpublic RetroTexturePreview( bool smooth )\r\n\t{\r\n\t\tthis.smooth = smooth;\r\n\t\tMinimumSize = new Vector2( 200, 180 );\r\n\t}\r\n\r\n\tpublic void SetImage( byte[] data )\r\n\t{\r\n\t\timage = null;\r\n\t\tif ( data != null )\r\n\t\t{\r\n\t\t\tusing var bitmap = Bitmap.CreateFromBytes( data );\r\n\t\t\tif ( bitmap != null ) image = Pixmap.FromBitmap( bitmap );\r\n\t\t}\r\n\t\tUpdate();\r\n\t}\r\n\r\n\tprotected override void OnPaint()\r\n\t{\r\n\t\tPaint.ClearPen();\r\n\t\tconst int tile = 16;\r\n\t\tfor ( var y = 0; y \u003C Height; y \u002B= tile )\r\n\t\t{\r\n\t\t\tfor ( var x = 0; x \u003C Width; x \u002B= tile )\r\n\t\t\t{\r\n\t\t\t\tPaint.SetBrush( ( ( x / tile \u002B y / tile ) % 2 == 0 ) ? Theme.WidgetBackground : Theme.SurfaceBackground );\r\n\t\t\t\tPaint.DrawRect( new Rect( x, y, Math.Min( tile, Width - x ), Math.Min( tile, Height - y ) ) );\r\n\t\t\t}\r\n\t\t}\r\n\t\tif ( image == null ) return;\r\n\t\tvar scale = Math.Min( Width / (float)image.Width, Height / (float)image.Height );\r\n\t\tvar width = image.Width * scale;\r\n\t\tvar height = image.Height * scale;\r\n\t\tPaint.BilinearFiltering = smooth;\r\n\t\tPaint.Draw( new Rect( ( Width - width ) / 2, ( Height - height ) / 2, width, height ), image );\r\n\t}\r\n}\r\n"},{"Ident":"alex.rsm","Path":"Editor/RetroAmbientMaterial.cs","FileName":"RetroAmbientMaterial.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449511,"IsPrivate":false,"Code":"using System;\nusing System.Buffers.Binary;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.IO.Compression;\nusing System.Net;\nusing System.Net.Http;\nusing System.Text;\nusing System.Text.Json;\nusing System.Threading;\nusing System.Text.RegularExpressions;\nusing System.Threading.Tasks;\nusing Sandbox;\n\nnamespace Editor;\n\n/// \u003Csummary\u003EImports a 1K ambientCG material into the current project\u0027s assets.\u003C/summary\u003E\n[EditorApp( \u0022Import ambientCG Material\u0022, \u0022download\u0022, \u0022Download and create a retro material from ambientCG\u0022 )]\npublic class RetroAmbientMaterial : Dialog\n{\n\tconst int MaxDownloadBytes = 32 * 1024 * 1024;\n\tconst int MaxMapBytes = 16 * 1024 * 1024;\n\tstatic readonly HttpClient Client = new( new HttpClientHandler { AllowAutoRedirect = false } ) { Timeout = TimeSpan.FromMinutes( 2 ) };\n\tconst int SearchPageSize = 20;\n\treadonly LineEdit search;\n\treadonly ComboBox results;\n\treadonly Label searchStatus;\n\treadonly Label details;\n\treadonly Button previous;\n\treadonly Button next;\n\treadonly List\u003C(string Id, string Description, string PreviewUrl)\u003E searchResults = new();\n\treadonly PreviewWidget preview;\n\tint previewVersion;\n\tCancellationTokenSource previewRequest;\n\tstring searchQuery = \u0022\u0022;\n\tint searchOffset;\n\tint searchTotal;\n\tint searchVersion;\n\treadonly LineEdit assetId;\n\treadonly LineEdit size;\n\treadonly LineEdit levels;\n\treadonly Label status;\n\treadonly Button create;\n\treadonly Checkbox retroShader;\n\n\tpublic static void Open() =\u003E new RetroAmbientMaterial().Show();\n\n\tpublic RetroAmbientMaterial()\n\t{\n\t\tDeleteOnClose = true;\n\t\tWindow.WindowTitle = \u0022Import ambientCG Material\u0022;\n\t\tWindow.Size = new( 520, 590 );\n\t\tLayout = Layout.Column();\n\t\tLayout.Margin = 16;\n\t\tLayout.Spacing = 8;\n\n\t\tLayout.Add( new Label( this ) { Text = \u0022Find a material\u0022 } );\n\t\tvar searchRow = Layout.AddRow();\n\t\tsearch = searchRow.Add( new LineEdit( this ) { PlaceholderText = \u0022Search ambientCG\u0022 }, 1 );\n\t\tsearchRow.Add( new Button( \u0022Search\u0022, \u0022search\u0022 ) { Clicked = () =\u003E StartSearch( search.Text?.Trim() ?? \u0022\u0022, 0 ) } );\n\t\tresults = Layout.Add( new ComboBox( this ) );\n\t\tresults.ItemChanged \u002B= SelectResult;\n\t\tvar previewRow = Layout.AddRow();\n\t\tpreview = previewRow.Add( new PreviewWidget( this ) );\n\t\tdetails = previewRow.Add( new Label( this ) { Text = \u0022Search for materials or enter an ID below.\u0022, WordWrap = true }, 1 );\n\t\tvar pageRow = Layout.AddRow();\n\t\tprevious = pageRow.Add( new Button( \u0022Previous\u0022 ) { Enabled = false, Clicked = () =\u003E StartSearch( searchQuery, searchOffset - SearchPageSize ) } );\n\t\tnext = pageRow.Add( new Button( \u0022Next\u0022 ) { Enabled = false, Clicked = () =\u003E StartSearch( searchQuery, searchOffset \u002B SearchPageSize ) } );\n\t\tsearchStatus = Layout.Add( new Label( this ) { Text = \u0022Search shows up to 20 results per page.\u0022, WordWrap = true } );\n\t\tsearch.ReturnPressed \u002B= () =\u003E StartSearch( search.Text?.Trim() ?? \u0022\u0022, 0 );\n\t\tsearch.TextEdited \u002B= _ =\u003E\n\t\t{\n\t\t\tsearchVersion\u002B\u002B;\n\t\t\tCancelPreview();\n\t\t\tsearchResults.Clear();\n\t\t\tresults.Clear();\n\t\t\tpreview.SetImage( null );\n\t\t\tdetails.Text = \u0022Search to update results.\u0022;\n\t\t\tprevious.Enabled = next.Enabled = false;\n\t\t\tsearchStatus.Text = \u0022Search to update results.\u0022;\n\t\t};\n\n\t\tLayout.Add( new Label( this ) { Text = \u0022Material ID\u0022 } );\n\t\tassetId = Layout.Add( new LineEdit( this ) { PlaceholderText = \u0022e.g. Bricks001\u0022 } );\n\t\tassetId.TextEdited \u002B= _ =\u003E\n\t\t{\n\t\t\tCancelPreview();\n\t\t\tpreview.SetImage( null );\n\t\t\tdetails.Text = \u0022Enter an ID or select a search result.\u0022;\n\t\t};\n\t\tvar options = Layout.AddRow();\n\t\toptions.Add( new Label( this ) { Text = \u0022Maximum size\u0022 } );\n\t\tsize = options.Add( new LineEdit( this ) { Text = \u0022256\u0022 } );\n\t\toptions.Add( new Label( this ) { Text = \u0022Color levels\u0022 } );\n\t\tlevels = options.Add( new LineEdit( this ) { Text = \u002232\u0022 } );\n\t\tretroShader = Layout.Add( new Checkbox( \u0022Use retro shader (uncheck for standard PBR)\u0022, this ) { Value = true } );\n\t\tLayout.Add( new Label( this ) { Text = \u0022Both use available color, normal and roughness maps. Metalness is used by standard PBR.\u0022, WordWrap = true } );\n\t\tstatus = Layout.Add( new Label( this ) { Text = \u0022Imports the 1K JPG maps. Existing materials are never replaced.\u0022, WordWrap = true } );\n\t\tcreate = Layout.Add( new Button.Primary( \u0022Import Material\u0022, \u0022download\u0022 ) { Clicked = () =\u003E _ = Import() } );\n\t}\n\n\tvoid SelectResult()\n\t{\n\t\tCancelPreview();\n\t\tvar version = previewVersion;\n\t\tpreview.SetImage( null );\n\t\tvar index = results.CurrentIndex - 1;\n\t\tif ( index \u003C 0 || index \u003E= searchResults.Count ) return;\n\t\tvar result = searchResults[index];\n\t\tassetId.Text = result.Id;\n\t\tdetails.Text = result.Description \u002B \u0022\\nLoading preview\u2026\u0022;\n\t\tpreviewRequest = new CancellationTokenSource();\n\t\t_ = LoadPreview( result.Id, result.PreviewUrl, result.Description, version, previewRequest.Token );\n\t}\n\n\tvoid StartSearch( string query, int offset )\n\t{\n\t\tif ( query.Length \u003E 128 )\n\t\t{\n\t\t\tsearchStatus.Text = \u0022Search text must be 128 characters or less.\u0022;\n\t\t\treturn;\n\t\t}\n\t\tsearchQuery = query;\n\t\tsearchOffset = Math.Max( 0, offset );\n\t\tvar version = \u002B\u002BsearchVersion;\n\t\tCancelPreview();\n\t\tpreview.SetImage( null );\n\t\tsearchResults.Clear();\n\t\tresults.Clear();\n\t\tdetails.Text = \u0022Searching for materials\u2026\u0022;\n\t\tprevious.Enabled = next.Enabled = false;\n\t\tsearchStatus.Text = \u0022Searching ambientCG\u2026\u0022;\n\t\t_ = Search( query, searchOffset, version );\n\t}\n\n\tasync Task Search( string query, int offset, int version )\n\t{\n\t\ttry\n\t\t{\n\t\t\tvar url = new Uri( $\u0022https://ambientcg.com/api/v2/full_json?type=Material\u0026limit={SearchPageSize}\u0026offset={offset}\u0026q={Uri.EscapeDataString( query )}\u0026include=labelData,technicalData,previewData\u0022 );\n\t\t\tusing var json = JsonDocument.Parse( await Download( url, 2 * 1024 * 1024 ) );\n\t\t\tvar found = new List\u003C(string Id, string Description, string PreviewUrl)\u003E();\n\t\t\tforeach ( var item in json.RootElement.GetProperty( \u0022foundAssets\u0022 ).EnumerateArray() )\n\t\t\t{\n\t\t\t\tvar id = item.GetProperty( \u0022assetId\u0022 ).GetString();\n\t\t\t\tif ( id == null || !Regex.IsMatch( id, @\u0022\\A[A-Za-z0-9]{1,64}\\z\u0022 ) ) continue;\n\t\t\t\tvar name = item.TryGetProperty( \u0022displayName\u0022, out var n ) ? n.GetString() : null;\n\t\t\t\tvar category = item.TryGetProperty( \u0022displayCategory\u0022, out var c ) ? c.GetString() : null;\n\t\t\t\tvar maps = item.TryGetProperty( \u0022maps\u0022, out var m ) \u0026\u0026 m.ValueKind == JsonValueKind.Array\n\t\t\t\t\t? string.Join( \u0022, \u0022, m.EnumerateArray().Select( x =\u003E x.GetString() ) ) : \u0022\u0022;\n\t\t\t\tvar previewUrl = item.TryGetProperty( \u0022previewImage\u0022, out var images ) \u0026\u0026 images.ValueKind == JsonValueKind.Object\n\t\t\t\t\t\u0026\u0026 images.TryGetProperty( \u0022256-PNG\u0022, out var image ) \u0026\u0026 image.ValueKind == JsonValueKind.String ? image.GetString() : null;\n\t\t\t\tfound.Add( (id, $\u0022{name ?? id}  \u00B7  {category ?? \u0022Material\u0022}\u0022 \u002B (maps.Length \u003E 0 ? $\u0022\\nMaps: {maps}\u0022 : \u0022\u0022) \u002B \u0022\\nSource: ambientCG (CC0)\u0022, previewUrl) );\n\t\t\t}\n\t\t\tvar total = json.RootElement.GetProperty( \u0022numberOfResults\u0022 ).GetInt32();\n\t\t\tawait MainThread.Wait();\n\t\t\tif ( !this.IsValid() || version != searchVersion ) return;\n\t\t\tresults.Clear();\n\t\t\tsearchResults.Clear();\n\t\t\tsearchResults.AddRange( found );\n\t\t\tresults.AddItem( \u0022Select a material\u2026\u0022 );\n\t\t\tforeach ( var item in found ) results.AddItem( item.Id );\n\t\t\tsearchTotal = total;\n\t\t\tprevious.Enabled = offset \u003E 0;\n\t\t\tnext.Enabled = offset \u002B SearchPageSize \u003C searchTotal;\n\t\t\tsearchStatus.Text = found.Count == 0 ? \u0022No materials found.\u0022 : $\u0022Showing {offset \u002B 1}\u2013{offset \u002B found.Count} of {searchTotal}.\u0022;\n\t\t\tdetails.Text = found.Count \u003E 0 ? \u0022Select a material to see its details.\u0022 : \u0022Try another search or enter a material ID below.\u0022;\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tawait MainThread.Wait();\n\t\t\tif ( this.IsValid() \u0026\u0026 version == searchVersion ) searchStatus.Text = $\u0022Search failed: {e.Message}\u0022;\n\t\t}\n\t}\n\n\tvoid CancelPreview()\n\t{\n\t\tpreviewVersion\u002B\u002B;\n\t\tpreviewRequest?.Cancel();\n\t\tpreviewRequest?.Dispose();\n\t\tpreviewRequest = null;\n\t}\n\n\tpublic override void OnDestroyed()\n\t{\n\t\tCancelPreview();\n\t\tbase.OnDestroyed();\n\t}\n\n\tasync Task LoadPreview( string id, string url, string description, int version, CancellationToken cancellation )\n\t{\n\t\ttry\n\t\t{\n\t\t\tif ( !Uri.TryCreate( url, UriKind.Absolute, out var uri ) )\n\t\t\t\tthrow new InvalidDataException( \u0022No preview is available.\u0022 );\n\t\t\tvar path = $\u0022/file/ambientCG-Web/media/thumbnail/256-PNG/{id}.png\u0022;\n\t\t\tvar bytes = await Download( uri, 1024 * 1024, path, cancellation );\n\t\t\tif ( bytes.Length \u003C 24 || !bytes.AsSpan( 0, 8 ).SequenceEqual( new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 } )\n\t\t\t\t|| BinaryPrimitives.ReadUInt32BigEndian( bytes.AsSpan( 8, 4 ) ) != 13\n\t\t\t\t|| !bytes.AsSpan( 12, 4 ).SequenceEqual( new byte[] { 73, 72, 68, 82 } )\n\t\t\t\t|| BinaryPrimitives.ReadUInt32BigEndian( bytes.AsSpan( 16, 4 ) ) != 256\n\t\t\t\t|| BinaryPrimitives.ReadUInt32BigEndian( bytes.AsSpan( 20, 4 ) ) != 256 )\n\t\t\t\tthrow new InvalidDataException( \u0022Invalid preview image.\u0022 );\n\t\t\tawait MainThread.Wait();\n\t\t\tif ( !this.IsValid() || version != previewVersion ) return;\n\t\t\tusing var bitmap = Bitmap.CreateFromBytes( bytes ) ?? throw new InvalidDataException( \u0022Invalid preview image.\u0022 );\n\t\t\tpreview.SetImage( Pixmap.FromBitmap( bitmap ) );\n\t\t\tdetails.Text = description;\n\t\t}\n\t\tcatch ( Exception )\n\t\t{\n\t\t\tawait MainThread.Wait();\n\t\t\tif ( this.IsValid() \u0026\u0026 version == previewVersion ) details.Text = description \u002B \u0022\\nPreview unavailable.\u0022;\n\t\t}\n\t}\n\n\tsealed class PreviewWidget : Widget\n\t{\n\t\tPixmap image;\n\n\t\tpublic PreviewWidget( Widget parent ) : base( parent )\n\t\t{\n\t\t\tFixedSize = new Vector2( 112, 112 );\n\t\t}\n\n\t\tpublic void SetImage( Pixmap value )\n\t\t{\n\t\t\timage = value;\n\t\t\tUpdate();\n\t\t}\n\n\t\tprotected override void OnPaint()\n\t\t{\n\t\t\tif ( image != null ) Paint.Draw( LocalRect, image );\n\t\t}\n\t}\n\n\tasync Task Import()\n\t{\n\t\tvar id = assetId.Text?.Trim() ?? \u0022\u0022;\n\t\tif ( !Regex.IsMatch( id, @\u0022\\A[A-Za-z0-9]{1,64}\\z\u0022 ) || !int.TryParse( size.Text, out var maxSize ) || maxSize \u003C 1 || maxSize \u003E 1024 || !int.TryParse( levels.Text, out var colorLevels ) || colorLevels \u003C 2 || colorLevels \u003E 256 )\n\t\t{\n\t\t\tstatus.Text = \u0022Enter an asset ID, size from 1\u20131024 and color levels from 2\u2013256.\u0022;\n\t\t\treturn;\n\t\t}\n\t\tvar useRetroShader = retroShader.Value;\n\n\t\tcreate.Enabled = false;\n\t\tstatus.Text = \u0022Checking material availability\u2026\u0022;\n\t\ttry\n\t\t{\n\t\t\tvar assetsPath = Sandbox.Project.Current?.GetAssetsPath() ?? throw new InvalidOperationException( \u0022No project is open.\u0022 );\n\t\t\tvar relativeDirectory = $\u0022materials/ambientcg/{id.ToLowerInvariant()}\u0022;\n\t\t\tvar destination = Path.Combine( assetsPath, \u0022materials\u0022, \u0022ambientcg\u0022, id.ToLowerInvariant() );\n\t\t\tif ( Directory.Exists( destination ) || File.Exists( destination ) )\n\t\t\t\tthrow new IOException( \u0022The destination already exists; nothing was overwritten.\u0022 );\n\n\t\t\tvar metadataUrl = new Uri( $\u0022https://ambientcg.com/api/v2/full_json?id={id}\u0026include=downloadData\u0022 );\n\t\t\tusing var metadata = JsonDocument.Parse( await Download( metadataUrl, 2 * 1024 * 1024 ) );\n\t\t\tstring canonicalId = null;\n\t\t\tstring filename = null;\n\t\t\tforeach ( var asset in metadata.RootElement.GetProperty( \u0022foundAssets\u0022 ).EnumerateArray() )\n\t\t\t{\n\t\t\t\tvar candidate = asset.GetProperty( \u0022assetId\u0022 ).GetString();\n\t\t\t\tif ( !string.Equals( candidate, id, StringComparison.OrdinalIgnoreCase ) || asset.GetProperty( \u0022dataType\u0022 ).GetString() != \u0022Material\u0022 ) continue;\n\t\t\t\tcanonicalId = candidate;\n\t\t\t\tvar downloads = asset.GetProperty( \u0022downloadFolders\u0022 ).GetProperty( \u0022default\u0022 ).GetProperty( \u0022downloadFiletypeCategories\u0022 ).GetProperty( \u0022zip\u0022 ).GetProperty( \u0022downloads\u0022 );\n\t\t\t\tforeach ( var download in downloads.EnumerateArray() )\n\t\t\t\t{\n\t\t\t\t\tif ( download.GetProperty( \u0022attribute\u0022 ).GetString() == \u00221K-JPG\u0022 \u0026\u0026 download.GetProperty( \u0022fileName\u0022 ).GetString() == $\u0022{canonicalId}_1K-JPG.zip\u0022 )\n\t\t\t\t\t\tfilename = download.GetProperty( \u0022fileName\u0022 ).GetString();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( filename == null ) throw new InvalidOperationException( \u0022No 1K JPG material download was found for that ID.\u0022 );\n\t\t\tawait MainThread.Wait();\n\t\t\tif ( !this.IsValid() ) return;\n\t\t\tstatus.Text = \u0022Downloading 1K JPG maps\u2026\u0022;\n\t\t\tvar zipBytes = await Download( new Uri( $\u0022https://ambientcg.com/get?file={Uri.EscapeDataString( filename )}\u0022 ), MaxDownloadBytes );\n\t\t\tawait MainThread.Wait();\n\t\t\tif ( !this.IsValid() ) return;\n\t\t\tif ( !string.Equals( Sandbox.Project.Current?.GetAssetsPath(), assetsPath, StringComparison.OrdinalIgnoreCase ) )\n\t\t\t\tthrow new InvalidOperationException( \u0022The open project changed during import.\u0022 );\n\t\t\tstatus.Text = \u0022Processing maps\u2026\u0022;\n\t\t\tvar maps = await Task.Run( () =\u003E ReadMaps( zipBytes, canonicalId, maxSize, colorLevels ) );\n\t\t\tawait MainThread.Wait();\n\t\t\tif ( !this.IsValid() ) return;\n\t\t\tif ( !string.Equals( Sandbox.Project.Current?.GetAssetsPath(), assetsPath, StringComparison.OrdinalIgnoreCase ) )\n\t\t\t\tthrow new InvalidOperationException( \u0022The open project changed during import.\u0022 );\n\t\t\tif ( !maps.ContainsKey( \u0022Color\u0022 ) ) throw new InvalidOperationException( \u0022The download has no Color map.\u0022 );\n\n\t\t\tvar parent = Path.GetDirectoryName( destination );\n\t\t\tDirectory.CreateDirectory( parent );\n\t\t\tvar staging = Path.Combine( parent, \u0022.ambientcg-\u0022 \u002B Guid.NewGuid().ToString( \u0022N\u0022 ) );\n\t\t\tDirectory.CreateDirectory( staging );\n\t\t\ttry\n\t\t\t{\n\t\t\t\tforeach ( var map in maps )\n\t\t\t\t\tFile.WriteAllBytes( Path.Combine( staging, map.Key.ToLowerInvariant() \u002B \u0022.png\u0022 ), map.Value );\n\t\t\t\tFile.WriteAllText( Path.Combine( staging, id.ToLowerInvariant() \u002B \u0022.vmat\u0022 ), BuildMaterialSource( relativeDirectory, maps.Keys, useRetroShader ) );\n\t\t\t\tDirectory.Move( staging, destination );\n\t\t\t\tforeach ( var map in maps )\n\t\t\t\t\tAssetSystem.RegisterFile( Path.Combine( destination, map.Key.ToLowerInvariant() \u002B \u0022.png\u0022 ) );\n\t\t\t\tAssetSystem.RegisterFile( Path.Combine( destination, id.ToLowerInvariant() \u002B \u0022.vmat\u0022 ) );\n\t\t\t}\n\t\t\tfinally\n\t\t\t{\n\t\t\t\tif ( Directory.Exists( staging ) ) Directory.Delete( staging, true );\n\t\t\t}\n\t\t\tstatus.Text = $\u0022Created {relativeDirectory}/{id.ToLowerInvariant()}.vmat\u0022;\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tawait MainThread.Wait();\n\t\t\tif ( this.IsValid() ) status.Text = $\u0022Import failed: {e.Message}\u0022;\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tawait MainThread.Wait();\n\t\t\tif ( this.IsValid() ) create.Enabled = true;\n\t\t}\n\t}\n\n\tstatic string BuildMaterialSource( string relativeDirectory, IEnumerable\u003Cstring\u003E maps, bool useRetroShader )\n\t{\n\t\tvar shader = useRetroShader ? \u0022shaders/retro_material.shader\u0022 : \u0022shaders/complex.shader\u0022;\n\t\tvar material = new StringBuilder( $\u0022Layer0\\n{{\\n\\tshader \\\u0022{shader}\\\u0022\\n\u0022 );\n\t\tif ( useRetroShader \u0026\u0026 maps.Contains( \u0022Roughness\u0022 ) ) material.AppendLine( \u0022\\tF_ROUGHNESS_TEXTURE 1\u0022 );\n\t\tif ( !useRetroShader \u0026\u0026 maps.Contains( \u0022Metalness\u0022 ) ) material.AppendLine( \u0022\\tF_METALNESS_TEXTURE 1\u0022 );\n\t\tforeach ( var map in maps )\n\t\t{\n\t\t\tif ( !useRetroShader || map != \u0022Metalness\u0022 )\n\t\t\t\tmaterial.AppendLine( $\u0022\\tTexture{map} \\\u0022{relativeDirectory}/{map.ToLowerInvariant()}.png\\\u0022\u0022 );\n\t\t}\n\t\tmaterial.AppendLine( \u0022}\u0022 );\n\t\treturn material.ToString();\n\t}\n\n\tstatic Dictionary\u003Cstring, byte[]\u003E ReadMaps( byte[] zipBytes, string id, int maxSize, int colorLevels )\n\t{\n\t\tvar names = new Dictionary\u003Cstring, string\u003E( StringComparer.OrdinalIgnoreCase )\n\t\t{\n\t\t\t[\u0022Color\u0022] = \u0022Color\u0022, [\u0022NormalDX\u0022] = \u0022Normal\u0022, [\u0022Roughness\u0022] = \u0022Roughness\u0022,\n\t\t\t[\u0022Metalness\u0022] = \u0022Metalness\u0022, [\u0022AmbientOcclusion\u0022] = \u0022AmbientOcclusion\u0022\n\t\t};\n\t\tvar maps = new Dictionary\u003Cstring, byte[]\u003E();\n\t\tusing var archive = new ZipArchive( new MemoryStream( zipBytes ), ZipArchiveMode.Read );\n\t\tforeach ( var entry in archive.Entries )\n\t\t{\n\t\t\tforeach ( var name in names )\n\t\t\t{\n\t\t\t\tif ( !string.Equals( entry.FullName, $\u0022{id}_1K-JPG_{name.Key}.jpg\u0022, StringComparison.OrdinalIgnoreCase ) ) continue;\n\t\t\t\tif ( entry.Length \u003E MaxMapBytes || maps.ContainsKey( name.Value ) ) throw new InvalidDataException( \u0022Invalid or duplicate texture map.\u0022 );\n\t\t\t\tusing var stream = entry.Open();\n\t\t\t\tvar bytes = ReadLimited( stream, MaxMapBytes );\n\t\t\t\tmaps.Add( name.Value, RetroTextureProcessor.Process( bytes, maxSize, name.Key == \u0022Color\u0022 ? colorLevels : 256, name.Key == \u0022Color\u0022 ) );\n\t\t\t}\n\t\t}\n\t\treturn maps;\n\t}\n\n\tstatic async Task\u003Cbyte[]\u003E Download( Uri url, int limit, string thumbnailPath = null, CancellationToken cancellation = default )\n\t{\n\t\tusing var timeout = CancellationTokenSource.CreateLinkedTokenSource( cancellation );\n\t\ttimeout.CancelAfter( TimeSpan.FromMinutes( 2 ) );\n\t\tfor ( var redirects = 0; redirects \u003C 4; redirects\u002B\u002B )\n\t\t{\n\t\t\tvar validHost = thumbnailPath == null\n\t\t\t\t? url.Host == \u0022ambientcg.com\u0022 || url.Host == \u0022acg-download.struffelproductions.com\u0022\n\t\t\t\t: url.Host == \u0022acg-media.struffelproductions.com\u0022 \u0026\u0026 url.AbsolutePath == thumbnailPath \u0026\u0026 url.Query.Length == 0 \u0026\u0026 url.Fragment.Length == 0;\n\t\t\tif ( url.Scheme != Uri.UriSchemeHttps || !url.IsDefaultPort || url.UserInfo.Length != 0 || !validHost )\n\t\t\t\tthrow new InvalidOperationException( \u0022Unexpected ambientCG download address.\u0022 );\n\t\t\tusing var response = await Client.GetAsync( url, HttpCompletionOption.ResponseHeadersRead, timeout.Token );\n\t\t\tif ( (int)response.StatusCode \u003E= 300 \u0026\u0026 (int)response.StatusCode \u003C 400 )\n\t\t\t{\n\t\t\t\turl = new Uri( url, response.Headers.Location ?? throw new InvalidDataException( \u0022Missing redirect location.\u0022 ) );\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tresponse.EnsureSuccessStatusCode();\n\t\t\tif ( response.Content.Headers.ContentLength \u003E limit ) throw new InvalidDataException( \u0022Download exceeds the size limit.\u0022 );\n\t\t\tusing var stream = await response.Content.ReadAsStreamAsync( timeout.Token );\n\t\t\tusing var output = new MemoryStream();\n\t\t\tvar buffer = new byte[8192];\n\t\t\tint read;\n\t\t\twhile ( (read = await stream.ReadAsync( buffer.AsMemory(), timeout.Token )) != 0 )\n\t\t\t{\n\t\t\t\tif ( output.Length \u002B read \u003E limit ) throw new InvalidDataException( \u0022Download exceeds the size limit.\u0022 );\n\t\t\t\toutput.Write( buffer, 0, read );\n\t\t\t}\n\t\t\treturn output.ToArray();\n\t\t}\n\t\tthrow new InvalidDataException( \u0022Too many redirects.\u0022 );\n\t}\n\n\tstatic byte[] ReadLimited( Stream stream, int limit )\n\t{\n\t\tusing var output = new MemoryStream();\n\t\tvar buffer = new byte[8192];\n\t\tint read;\n\t\twhile ( (read = stream.Read( buffer, 0, buffer.Length )) != 0 )\n\t\t{\n\t\t\tif ( output.Length \u002B read \u003E limit ) throw new InvalidDataException( \u0022Data exceeds the size limit.\u0022 );\n\t\t\toutput.Write( buffer, 0, read );\n\t\t}\n\t\treturn output.ToArray();\n\t}\n}\n"},{"Ident":"alex.rsm","Path":"Code/RetroDetailCameraEffect.cs","FileName":"RetroDetailCameraEffect.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":449511,"IsPrivate":false,"Code":"using Sandbox;\n\n/// \u003Csummary\u003E\n/// Applies retro material settings to the view before scene materials are drawn.\n/// \u003C/summary\u003E\n[Hide]\npublic sealed class RetroDetailCameraEffect : BasePostProcess\u003CRetroDetailCameraEffect\u003E\n{\n\tinternal RetroPostProcess Controls { get; set; }\n\n\tpublic override bool IsCameraEffect =\u003E true;\n\n\tpublic override void Render()\n\t{\n\t\tvar disabled = GetWeighted( x =\u003E x.Controls.EffectiveSettings.UseDetailTextures ? 0.0f : 1.0f );\n\t\tTargetCamera.Attributes.Set( \u0022RetroDetailTexturesDisabled\u0022, disabled );\n\n\t\tvar point = GetWeighted( x =\u003E x.Controls.TextureFiltering == RetroTextureFiltering.Point ? 1.0f : 0.0f );\n\t\tvar bilinear = GetWeighted( x =\u003E x.Controls.TextureFiltering == RetroTextureFiltering.Bilinear ? 1.0f : 0.0f );\n\t\tvar trilinear = GetWeighted( x =\u003E x.Controls.TextureFiltering == RetroTextureFiltering.Trilinear ? 1.0f : 0.0f );\n\t\tvar filtering = point \u003E= 0.5f \u0026\u0026 point \u003E= bilinear \u0026\u0026 point \u003E= trilinear ? RetroTextureFiltering.Point\n\t\t\t: bilinear \u003E= 0.5f \u0026\u0026 bilinear \u003E= trilinear ? RetroTextureFiltering.Bilinear\n\t\t\t: trilinear \u003E= 0.5f ? RetroTextureFiltering.Trilinear\n\t\t\t: RetroTextureFiltering.MaterialDefault;\n\t\tTargetCamera.Attributes.Set( \u0022RetroTextureFiltering\u0022, (float)filtering );\n\t\tTargetCamera.Attributes.Set( \u0022RetroGouraudSunDiffuse\u0022, GetWeighted( x =\u003E x.Controls.GouraudSunDiffuse ? 1.0f : 0.0f ) );\n\t\tTargetCamera.Attributes.Set( \u0022RetroTexelLighting\u0022, GetWeighted( x =\u003E x.Controls.TexelLighting ? 1.0f : 0.0f ) );\n\t}\n}\n"},{"Ident":"alex.rsm","Path":"RetroPostProcess.cs","FileName":"RetroPostProcess.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":449511,"IsPrivate":false,"Code":"using Sandbox;\nusing Sandbox.Rendering;\n\n/// \u003Csummary\u003E\n/// Camera looks inspired by different eras of 3D rendering.\n/// \u003C/summary\u003E\npublic enum RetroCameraPreset\n{\n\tCustom,\n\t[Title( \u0022PSX\u0022 )] PSX,\n\t[Title( \u0022Half-Life 1\u0022 )] HalfLife1,\n\t[Title( \u0022Half-Life 2\u0022 )] HalfLife2\n}\n\n/// \u003Csummary\u003E\n/// Color precision applied after rendering.\n/// \u003C/summary\u003E\npublic enum RetroColorDepth\n{\n\t[Title( \u0022Legacy (Dither Only)\u0022 )] Legacy,\n\t[Title( \u0022Full Color (No Reduction)\u0022 )] FullColor,\n\t[Title( \u00228-bit (RGB 3:3:2)\u0022 )] Rgb332,\n\t[Title( \u002215-bit (RGB 5:5:5)\u0022 )] Rgb555,\n\t[Title( \u002216-bit (RGB 5:6:5)\u0022 )] Rgb565,\n\t[Title( \u002224-bit (RGB 8:8:8)\u0022 )] Rgb888,\n\t[Title( \u0022Custom Bits per Channel\u0022 )] CustomBits,\n\t[Title( \u0022Custom Levels per Channel\u0022 )] CustomLevels\n}\n\n/// \u003Csummary\u003E\n/// Texture filtering override for compatible retro materials.\n/// \u003C/summary\u003E\npublic enum RetroTextureFiltering\n{\n\t[Title( \u0022Material Default\u0022 )] MaterialDefault = 0,\n\tPoint = 1,\n\tBilinear = 2,\n\tTrilinear = 3\n}\n\n/// \u003Csummary\u003E\n/// Controls retro material detail and applies pixelation, ordered dithering and aspect-ratio bars.\n/// \u003C/summary\u003E\n[Title( \u0022Retro Camera Controls\u0022 )]\n[Category( \u0022Post Processing\u0022 )]\n[Icon( \u0022filter_vintage\u0022 )]\npublic sealed class RetroPostProcess : BasePostProcess\u003CRetroPostProcess\u003E\n{\n\t/// \u003Csummary\u003E\n\t/// Select a look, or choose Custom to use the settings below.\n\t/// Custom settings are preserved when switching between presets.\n\t/// Presets affect post-processing and retro detail textures, not material filtering or lighting.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Presets\u0022, Order = -1 )] public RetroCameraPreset Preset { get; set; } = RetroCameraPreset.Custom;\n\n\t/// \u003Csummary\u003E\n\t/// Controls the color precision of the final image. Legacy reduces colors only when dithering is enabled.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public RetroColorDepth ColorDepth { get; set; } = RetroColorDepth.Legacy;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowColorBits ), true ), Range( 1, 8 )] public int RedBits { get; set; } = 5;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowColorBits ), true ), Range( 1, 8 )] public int GreenBits { get; set; } = 5;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowColorBits ), true ), Range( 1, 8 )] public int BlueBits { get; set; } = 5;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowColorLevels ), true ), Range( 2, 256 )] public float ColorLevels { get; set; } = 32;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowDither ), true )] public bool Dither { get; set; } = true;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( ShowDitherStrength ), true ), Range( 0, 1 )] public float DitherStrength { get; set; } = 0.5f;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public bool Downscale { get; set; } = true;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public bool Crop { get; set; } = true;\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public Vector2 TargetResolution { get; set; } = new( 320, 240 );\n\t[Property, Group( \u0022Post-processing\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public Vector2 TargetAspect { get; set; } = new( 4, 3 );\n\n\tprivate bool ShowColorBits =\u003E Preset == RetroCameraPreset.Custom \u0026\u0026 ColorDepth == RetroColorDepth.CustomBits;\n\tprivate bool ShowColorLevels =\u003E Preset == RetroCameraPreset.Custom \u0026\u0026 ColorDepth is RetroColorDepth.Legacy or RetroColorDepth.CustomLevels;\n\tprivate bool ShowDither =\u003E Preset == RetroCameraPreset.Custom \u0026\u0026 ColorDepth != RetroColorDepth.FullColor;\n\tprivate bool ShowDitherStrength =\u003E ShowDither \u0026\u0026 Dither;\n\n\t/// \u003Csummary\u003E\n\t/// Enables detail textures on retro materials visible to this camera.\n\t/// Each material must also have its detail texture feature enabled.\n\t/// Camera post-processing must be enabled for this setting to apply.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Rendering\u0022 ), ShowIf( nameof( Preset ), RetroCameraPreset.Custom )] public bool UseDetailTextures { get; set; } = true;\n\n\t/// \u003Csummary\u003E\n\t/// Overrides texture filtering only on compatible retro materials.\n\t/// Camera post-processing must be enabled for this setting to apply.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Rendering\u0022 )] public RetroTextureFiltering TextureFiltering { get; set; } = RetroTextureFiltering.MaterialDefault;\n\n\t/// \u003Csummary\u003E\n\t/// Applies Gouraud shading to directional diffuse lighting only on compatible retro materials.\n\t/// Point and spot lights remain per pixel. Camera post-processing must be enabled for this setting to apply.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Rendering\u0022 ), Title( \u0022Gouraud Shading (Sun Diffuse)\u0022 )] public bool GouraudSunDiffuse { get; set; } = false;\n\n\t/// \u003Csummary\u003E\n\t/// Uses a texel-aligned approximation of lighting and shadows only on compatible retro materials.\n\t/// Camera post-processing must be enabled for this setting to apply.\n\t/// \u003C/summary\u003E\n\t[Property, Group( \u0022Rendering\u0022 ), Title( \u0022Texel Lighting and Shadows\u0022 )] public bool TexelLighting { get; set; } = false;\n\n\tinternal readonly record struct CameraSettings(\n\t\tbool Dither, bool Downscale, bool Crop, Vector2 TargetResolution, Vector2 TargetAspect,\n\t\tfloat ColorLevels, float DitherStrength, bool UseDetailTextures, RetroColorDepth ColorDepth,\n\t\tint RedBits, int GreenBits, int BlueBits )\n\t{\n\t\tpublic bool ApplyReduction =\u003E ColorDepth switch\n\t\t{\n\t\t\tRetroColorDepth.FullColor =\u003E false,\n\t\t\tRetroColorDepth.Legacy =\u003E Dither,\n\t\t\t_ =\u003E true\n\t\t};\n\n\t\tpublic bool ApplyDither =\u003E Dither \u0026\u0026 ColorDepth != RetroColorDepth.FullColor;\n\n\t\tpublic Vector3 ChannelLevels =\u003E ColorDepth switch\n\t\t{\n\t\t\tRetroColorDepth.Rgb332 =\u003E new( 8, 8, 4 ),\n\t\t\tRetroColorDepth.Rgb555 =\u003E new( 32, 32, 32 ),\n\t\t\tRetroColorDepth.Rgb565 =\u003E new( 32, 64, 32 ),\n\t\t\tRetroColorDepth.Rgb888 =\u003E new( 256, 256, 256 ),\n\t\t\tRetroColorDepth.CustomBits =\u003E new(\n\t\t\t\t1 \u003C\u003C System.Math.Clamp( RedBits, 1, 8 ),\n\t\t\t\t1 \u003C\u003C System.Math.Clamp( GreenBits, 1, 8 ),\n\t\t\t\t1 \u003C\u003C System.Math.Clamp( BlueBits, 1, 8 ) ),\n\t\t\t_ =\u003E new( ColorLevels, ColorLevels, ColorLevels )\n\t\t};\n\t}\n\n\tinternal CameraSettings EffectiveSettings =\u003E Preset switch\n\t{\n\t\tRetroCameraPreset.PSX =\u003E new( true, true, true, new( 320, 240 ), new( 4, 3 ), 32, 1, false, RetroColorDepth.Rgb555, 5, 5, 5 ),\n\t\tRetroCameraPreset.HalfLife1 =\u003E new( false, true, true, new( 640, 480 ), new( 4, 3 ), 256, 0, false, RetroColorDepth.FullColor, 5, 6, 5 ),\n\t\tRetroCameraPreset.HalfLife2 =\u003E new( false, true, true, new( 1024, 768 ), new( 4, 3 ), 256, 0, true, RetroColorDepth.FullColor, 8, 8, 8 ),\n\t\t_ =\u003E new( Dither, Downscale, Crop, TargetResolution, TargetAspect, ColorLevels, DitherStrength, UseDetailTextures, ColorDepth, RedBits, GreenBits, BlueBits )\n\t};\n\n\t/// \u003Csummary\u003E\n\t/// Copies the selected preset to Custom so its settings can be adjusted.\n\t/// \u003C/summary\u003E\n\t[Button( \u0022Edit Preset\u0022 ), Group( \u0022Presets\u0022, Order = -1 ), HideIf( nameof( Preset ), RetroCameraPreset.Custom )]\n\tpublic void EditPreset()\n\t{\n\t\tvar settings = EffectiveSettings;\n\t\tusing var undo = Scene.Editor?.UndoScope( \u0022Edit Retro Preset\u0022 ).WithComponentChanges( this ).Push();\n\t\tDither = settings.Dither;\n\t\tDownscale = settings.Downscale;\n\t\tCrop = settings.Crop;\n\t\tTargetResolution = settings.TargetResolution;\n\t\tTargetAspect = settings.TargetAspect;\n\t\tColorDepth = settings.ColorDepth;\n\t\tRedBits = settings.RedBits;\n\t\tGreenBits = settings.GreenBits;\n\t\tBlueBits = settings.BlueBits;\n\t\tColorLevels = settings.ColorLevels;\n\t\tDitherStrength = settings.DitherStrength;\n\t\tUseDetailTextures = settings.UseDetailTextures;\n\t\tPreset = RetroCameraPreset.Custom;\n\t}\n\n\tprivate RetroDetailCameraEffect detailEffect;\n\n\tprotected override void OnEnabled()\n\t{\n\t\t// Scene attributes are merged into each camera before camera effects are applied.\n\t\tScene.RenderAttributes.Set( \u0022RetroDetailTexturesDisabled\u0022, 0.0f );\n\t\tScene.RenderAttributes.Set( \u0022RetroTextureFiltering\u0022, 0.0f );\n\t\tScene.RenderAttributes.Set( \u0022RetroGouraudSunDiffuse\u0022, 0.0f );\n\t\tScene.RenderAttributes.Set( \u0022RetroTexelLighting\u0022, 0.0f );\n\t\tdetailEffect = GameObject.Components.Create\u003CRetroDetailCameraEffect\u003E( false );\n\t\tdetailEffect.Flags = ComponentFlags.Hidden | ComponentFlags.NotSaved | ComponentFlags.NotCloned | ComponentFlags.NotNetworked;\n\t\tdetailEffect.Controls = this;\n\t\tdetailEffect.Enabled = true;\n\t}\n\n\tprotected override void OnDisabled()\n\t{\n\t\tdetailEffect?.Destroy();\n\t\tdetailEffect = null;\n\t}\n\n\tprivate static readonly Material Shader = Material.FromShader( \u0022shaders/retro_postprocess.shader\u0022 );\n\n\tpublic override void Render()\n\t{\n\t\tvar reduction = GetWeighted( x =\u003E x.EffectiveSettings.ApplyReduction ? 1.0f : 0.0f );\n\t\tvar dither = GetWeighted( x =\u003E x.EffectiveSettings.ApplyDither ? 1.0f : 0.0f );\n\t\tvar downscale = GetWeighted( x =\u003E x.EffectiveSettings.Downscale ? 1.0f : 0.0f );\n\t\tvar crop = GetWeighted( x =\u003E x.EffectiveSettings.Crop ? 1.0f : 0.0f );\n\t\tif ( reduction \u003C= 0 \u0026\u0026 downscale \u003C= 0 \u0026\u0026 crop \u003C= 0 ) return;\n\n\t\tAttributes.Set( \u0022ColorReduction\u0022, reduction );\n\t\tAttributes.Set( \u0022Dither\u0022, dither );\n\t\tAttributes.Set( \u0022Downscale\u0022, downscale );\n\t\tAttributes.Set( \u0022Crop\u0022, crop );\n\t\tAttributes.Set( \u0022TargetResolution\u0022, GetWeighted( x =\u003E x.EffectiveSettings.TargetResolution, new Vector2( 320, 240 ) ) );\n\t\tAttributes.Set( \u0022TargetAspect\u0022, GetWeighted( x =\u003E x.EffectiveSettings.TargetAspect, new Vector2( 4, 3 ) ) );\n\t\tAttributes.Set( \u0022ColorLevels\u0022, GetWeighted( x =\u003E x.EffectiveSettings.ChannelLevels, new Vector3( 256, 256, 256 ) ) );\n\t\tAttributes.Set( \u0022DitherStrength\u0022, GetWeighted( x =\u003E x.EffectiveSettings.DitherStrength ) );\n\n\t\tBlit( BlitMode.WithBackbuffer( Shader, Stage.AfterPostProcess, 10000 ), \u0022Retro Post Process\u0022 );\n\t}\n}\n"},{"Ident":"alex.rsm","Path":"Code/ShowcaseSpin.cs","FileName":"ShowcaseSpin.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":449511,"IsPrivate":false,"Code":"using Sandbox;\n\n[Title( \u0022Showcase Spin\u0022 )]\npublic sealed class ShowcaseSpin : Component\n{\n\t[Property] public float DegreesPerSecond { get; set; } = 30.0f;\n\n\tprotected override void OnUpdate()\n\t{\n\t\tLocalRotation *= Rotation.FromYaw( DegreesPerSecond * Time.Delta );\n\t}\n}\n"},{"Ident":"alex.rsm","Path":"RetroDetailCameraEffect.cs","FileName":"RetroDetailCameraEffect.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":449511,"IsPrivate":false,"Code":"using Sandbox;\n\n/// \u003Csummary\u003E\n/// Applies retro material settings to the view before scene materials are drawn.\n/// \u003C/summary\u003E\n[Hide]\npublic sealed class RetroDetailCameraEffect : BasePostProcess\u003CRetroDetailCameraEffect\u003E\n{\n\tinternal RetroPostProcess Controls { get; set; }\n\n\tpublic override bool IsCameraEffect =\u003E true;\n\n\tpublic override void Render()\n\t{\n\t\tvar disabled = GetWeighted( x =\u003E x.Controls.EffectiveSettings.UseDetailTextures ? 0.0f : 1.0f );\n\t\tTargetCamera.Attributes.Set( \u0022RetroDetailTexturesDisabled\u0022, disabled );\n\n\t\tvar point = GetWeighted( x =\u003E x.Controls.TextureFiltering == RetroTextureFiltering.Point ? 1.0f : 0.0f );\n\t\tvar bilinear = GetWeighted( x =\u003E x.Controls.TextureFiltering == RetroTextureFiltering.Bilinear ? 1.0f : 0.0f );\n\t\tvar trilinear = GetWeighted( x =\u003E x.Controls.TextureFiltering == RetroTextureFiltering.Trilinear ? 1.0f : 0.0f );\n\t\tvar filtering = point \u003E= 0.5f \u0026\u0026 point \u003E= bilinear \u0026\u0026 point \u003E= trilinear ? RetroTextureFiltering.Point\n\t\t\t: bilinear \u003E= 0.5f \u0026\u0026 bilinear \u003E= trilinear ? RetroTextureFiltering.Bilinear\n\t\t\t: trilinear \u003E= 0.5f ? RetroTextureFiltering.Trilinear\n\t\t\t: RetroTextureFiltering.MaterialDefault;\n\t\tTargetCamera.Attributes.Set( \u0022RetroTextureFiltering\u0022, (float)filtering );\n\t\tTargetCamera.Attributes.Set( \u0022RetroGouraudSunDiffuse\u0022, GetWeighted( x =\u003E x.Controls.GouraudSunDiffuse ? 1.0f : 0.0f ) );\n\t\tTargetCamera.Attributes.Set( \u0022RetroTexelLighting\u0022, GetWeighted( x =\u003E x.Controls.TexelLighting ? 1.0f : 0.0f ) );\n\t}\n}\n"},{"Ident":"alex.rsm","Path":"UnitTests/LibraryTest.cs","FileName":"LibraryTest.cs","PackageType":"library","CodeKind":"UnitTest","AssetVersionId":449511,"IsPrivate":false,"Code":"using Sandbox;\r\n\r\n[TestClass]\r\npublic partial class LibraryTests\r\n{\r\n\t[TestMethod]\r\n\tpublic void SceneTest()\r\n\t{\r\n\t\tvar scene = new Scene();\r\n\t\tusing ( scene.Push() )\r\n\t\t{\r\n\t\t\tvar go = new GameObject();\r\n\r\n\t\t\tAssert.AreEqual( 1, scene.Directory.GameObjectCount );\r\n\t\t}\r\n\t}\r\n\r\n}\r\n"}]}