commit f04752d09cd9a0e459a22c12cd85aca6c91c4314 Author: Jonathan Riedel Date: Sat May 18 11:30:34 2024 +0200 Initial commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8a30d25 --- /dev/null +++ b/.gitignore @@ -0,0 +1,398 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/LightingTest.sln b/LightingTest.sln new file mode 100644 index 0000000..6bd48d7 --- /dev/null +++ b/LightingTest.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34408.163 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightingTest", "LightingTest\LightingTest.csproj", "{917925A8-D4BE-40FB-B4FC-9BEABB11C386}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {917925A8-D4BE-40FB-B4FC-9BEABB11C386}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {917925A8-D4BE-40FB-B4FC-9BEABB11C386}.Debug|Any CPU.Build.0 = Debug|Any CPU + {917925A8-D4BE-40FB-B4FC-9BEABB11C386}.Release|Any CPU.ActiveCfg = Release|Any CPU + {917925A8-D4BE-40FB-B4FC-9BEABB11C386}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {159A7B77-D49A-4C73-BFE9-383151D4CB60} + EndGlobalSection +EndGlobal diff --git a/LightingTest/.config/dotnet-tools.json b/LightingTest/.config/dotnet-tools.json new file mode 100644 index 0000000..efabe22 --- /dev/null +++ b/LightingTest/.config/dotnet-tools.json @@ -0,0 +1,36 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-mgcb": { + "version": "3.8.1.303", + "commands": [ + "mgcb" + ] + }, + "dotnet-mgcb-editor": { + "version": "3.8.1.303", + "commands": [ + "mgcb-editor" + ] + }, + "dotnet-mgcb-editor-linux": { + "version": "3.8.1.303", + "commands": [ + "mgcb-editor-linux" + ] + }, + "dotnet-mgcb-editor-windows": { + "version": "3.8.1.303", + "commands": [ + "mgcb-editor-windows" + ] + }, + "dotnet-mgcb-editor-mac": { + "version": "3.8.1.303", + "commands": [ + "mgcb-editor-mac" + ] + } + } +} \ No newline at end of file diff --git a/LightingTest/Content/Content.mgcb b/LightingTest/Content/Content.mgcb new file mode 100644 index 0000000..ddc4c36 --- /dev/null +++ b/LightingTest/Content/Content.mgcb @@ -0,0 +1,15 @@ + +#----------------------------- Global Properties ----------------------------# + +/outputDir:bin/$(Platform) +/intermediateDir:obj/$(Platform) +/platform:DesktopGL +/config: +/profile:Reach +/compress:False + +#-------------------------------- References --------------------------------# + + +#---------------------------------- Content ---------------------------------# + diff --git a/LightingTest/Icon.bmp b/LightingTest/Icon.bmp new file mode 100644 index 0000000..2b48165 Binary files /dev/null and b/LightingTest/Icon.bmp differ diff --git a/LightingTest/Icon.ico b/LightingTest/Icon.ico new file mode 100644 index 0000000..7d9dec1 Binary files /dev/null and b/LightingTest/Icon.ico differ diff --git a/LightingTest/Lighting.cs b/LightingTest/Lighting.cs new file mode 100644 index 0000000..91090c7 --- /dev/null +++ b/LightingTest/Lighting.cs @@ -0,0 +1,198 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonoGame.Extended; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Orpticon.MonoGameLighting +{ + public static class Lighting + { + private static Texture2D pixelTexture; + public static float MaxOpacity { get; set; } = 0.5f; // Maximum opacity + public static float BaseDarkness { get; set; } = 0.95f; + private static Rectangle CameraRect; + private static float[] alphaMap; + public static void Initialize(GraphicsDeviceManager graphicsDevice, Rectangle cameraRect) + { + // TODO: Add your initialization logic here + + pixelTexture = new Texture2D(graphicsDevice.GraphicsDevice, 1, 1); + pixelTexture.SetData(new Color[] { Color.White }); + + CameraRect = cameraRect; + + alphaMap = new float[CameraRect.Width * CameraRect.Height]; + Array.Fill(alphaMap, 1f); + } + + public static void RenderCone(SpriteBatch _spriteBatch, Vector2 originPoint, float radius) => RenderCone(_spriteBatch, originPoint, new Vector2(0, -1), radius, 360, new List(), Color.White); + public static void RenderCone(SpriteBatch _spriteBatch, Vector2 originPoint, float radius, Color color) => RenderCone(_spriteBatch, originPoint, new Vector2(0, -1), radius, 360, new List(), color); + public static void RenderCone(SpriteBatch _spriteBatch, Vector2 originPoint, float radius, List collisionBoxes) => RenderCone(_spriteBatch, originPoint, new Vector2(0, -1), radius, 360, collisionBoxes, Color.White); + public static void RenderCone(SpriteBatch _spriteBatch, Vector2 originPoint, float radius, List collisionBoxes, Color color) => RenderCone(_spriteBatch, originPoint, new Vector2(0, -1), radius, 360, collisionBoxes, color); + public static void RenderCone(SpriteBatch _spriteBatch, Vector2 originPoint, Vector2 direction, float coneRadius, float coneAngleInDegrees) => RenderCone(_spriteBatch, originPoint, direction, coneRadius, coneAngleInDegrees, new List(), Color.White); + public static void RenderCone(SpriteBatch _spriteBatch, Vector2 originPoint, Vector2 direction, float coneRadius, float coneAngleInDegrees, List collisionBoxes) => RenderCone(_spriteBatch, originPoint, direction, coneRadius, coneAngleInDegrees, collisionBoxes, Color.White); + public static void RenderCone(SpriteBatch _spriteBatch, Vector2 originPoint, Vector2 notNormalizedDirection, float coneRadius, float coneAngleInDegrees, List collisionBoxes, Color color) + { + float halfAngle = MathHelper.ToRadians(coneAngleInDegrees) / 2; + Vector2 normalizedDirection = Vector2.Normalize(notNormalizedDirection); + float coneStartAngle = (float)Math.Atan2(normalizedDirection.Y, normalizedDirection.X) - halfAngle; + float coneEndAngle = (float)Math.Atan2(normalizedDirection.Y, normalizedDirection.X) + halfAngle; + + Vector2 startingPoint = new Vector2( + Math.Min(originPoint.X, originPoint.X + normalizedDirection.X * coneRadius) - coneRadius, + Math.Min(originPoint.Y, originPoint.Y + normalizedDirection.Y * coneRadius) - coneRadius + ); + + float radiusSquared = coneRadius * coneRadius; + float maxBoundingCircleRadius = (float)Math.Sqrt(2 * (1f / 2) * (1f / 2)); // Diagonal of a block + + List filteredCollisionBoxes = new List(); + + foreach (var collisionBox in collisionBoxes) + { + Vector2 boxCenter = new Vector2(collisionBox.Center.X, collisionBox.Center.Y); + Vector2 directionToBox = Vector2.Normalize(boxCenter - originPoint); + float distanceToBoxCenter = Vector2.Distance(originPoint, boxCenter); + if (distanceToBoxCenter > coneRadius + maxBoundingCircleRadius) + continue; + + float angleToBox = (float)Math.Atan2(directionToBox.Y, directionToBox.X); + if (angleToBox < 0) + angleToBox += MathHelper.TwoPi; + + float normalizedConeStartAngle = coneStartAngle < 0 ? coneStartAngle + MathHelper.TwoPi : coneStartAngle; + float normalizedConeEndAngle = coneEndAngle < 0 ? coneEndAngle + MathHelper.TwoPi : coneEndAngle; + + bool withinConeAngle = normalizedConeStartAngle <= angleToBox && angleToBox <= normalizedConeEndAngle; + if (normalizedConeEndAngle < normalizedConeStartAngle) + withinConeAngle = angleToBox >= normalizedConeStartAngle || angleToBox <= normalizedConeEndAngle; + + if (withinConeAngle) + { + filteredCollisionBoxes.Add(collisionBox); + } + } + + for (float y = startingPoint.Y; y < originPoint.Y + coneRadius; y += 1) + { + for (float x = startingPoint.X; x < originPoint.X + coneRadius; x += 1) + { + if(!CameraRect.Contains(x, y)) continue; + Vector2 blockCenter = new Vector2(x + 1 / 2, y + 1 / 2); + Vector2 toBlock = blockCenter - originPoint; + if (toBlock.LengthSquared() > radiusSquared) + continue; + + Vector2 directionToBlock = Vector2.Normalize(toBlock); + float angleToBlock = (float)Math.Atan2(directionToBlock.Y, directionToBlock.X); + if (angleToBlock < 0) + angleToBlock += MathHelper.TwoPi; + + float normalizedConeStartAngle = coneStartAngle < 0 ? coneStartAngle + MathHelper.TwoPi : coneStartAngle; + float normalizedConeEndAngle = coneEndAngle < 0 ? coneEndAngle + MathHelper.TwoPi : coneEndAngle; + + bool withinConeAngle = normalizedConeStartAngle <= angleToBlock && angleToBlock <= normalizedConeEndAngle; + if (normalizedConeEndAngle < normalizedConeStartAngle) + withinConeAngle = angleToBlock >= normalizedConeStartAngle || angleToBlock <= normalizedConeEndAngle; + + if (withinConeAngle) + { + bool clearLineOfSight = true; + foreach (var collisionBox in filteredCollisionBoxes) + { + if (collisionBox.Contains(blockCenter) || RayIntersectsRectangle(originPoint, blockCenter, collisionBox)) + { + clearLineOfSight = false; + break; + } + } + + if (clearLineOfSight) + { + float distanceToCenter = toBlock.Length(); + float opacity = MaxOpacity * (1 - MathHelper.Clamp(distanceToCenter / coneRadius, 0f, 1f)); + DrawFilledRectangle((int)x, (int)y, opacity); + } + } + } + } + } + + private static void DrawFilledRectangle(int x, int y, float opacity) + { + int i = (y - CameraRect.Y) * CameraRect.Width + (x - CameraRect.X); + alphaMap[i] *= (1 - opacity); + } + + private static bool PointInCone(Vector2 point, Vector2 originPoint, Vector2 endPoint, float coneRadius, float angleOffset) + { + Vector2 directionToPoint = point - originPoint; + Vector2 directionToEndpoint = endPoint - originPoint; + float dotProduct = Vector2.Dot(directionToPoint, directionToEndpoint); + + if (dotProduct < 0) + return false; // Point is behind the origin point of the cone + + float distanceSquaredToOrigin = Vector2.DistanceSquared(point, originPoint); + float maxDistanceSquared = coneRadius * coneRadius; + + if (distanceSquaredToOrigin > maxDistanceSquared) + return false; // Point is outside cone radius + + float angleToPoint = (float)Math.Acos(dotProduct / (directionToPoint.Length() * directionToEndpoint.Length())); + return angleToPoint <= angleOffset; + } + private static bool RayIntersectsRectangle(Vector2 rayStart, Vector2 rayEnd, RectangleF rectangle) + { + Vector2 direction = rayEnd - rayStart; + float invDirX = 1.0f / direction.X; + float invDirY = 1.0f / direction.Y; + + float tNearX = (rectangle.Left - rayStart.X) * invDirX; + float tNearY = (rectangle.Top - rayStart.Y) * invDirY; + float tFarX = (rectangle.Right - rayStart.X) * invDirX; + float tFarY = (rectangle.Bottom - rayStart.Y) * invDirY; + + if (tNearX > tFarX) (tNearX, tFarX) = (tFarX, tNearX); + if (tNearY > tFarY) (tNearY, tFarY) = (tFarY, tNearY); + + if (tNearX > tFarY || tNearY > tFarX) + return false; + + float tNear = Math.Max(tNearX, tNearY); + float tFar = Math.Min(tFarX, tFarY); + + return tNear >= 0 && tFar >= 0 && tNear <= 1; + } + public static void ApplyAlphaMap(SpriteBatch _spriteBatch) + { + for(int x = 0; x < CameraRect.Width; x++) + { + for(int y = 0; y < CameraRect.Height; y++) + { + int i = y * CameraRect.Width + x; + _spriteBatch.Draw(pixelTexture, new Rectangle(x + CameraRect.X, y + CameraRect.Y, 1, 1), Color.Black * BaseDarkness * alphaMap[i]); + } + } + } + //protected override void Draw(GameTime gameTime) + //{ + // GraphicsDevice.Clear(Color.Green); + + // _spriteBatch.Begin(); + // var pos = Mouse.GetState().Position.ToVector2(); + // var cen = new Vector2(_graphics.PreferredBackBufferWidth / 2, _graphics.PreferredBackBufferHeight / 2); + + // var rects = new List { new RectangleF(pos, new Vector2(48, 48)), new RectangleF(new Vector2(1024, 384), new Vector2(48, 48)) }; + // rects.ForEach(x => DrawFilledRectangle(_spriteBatch, x, Color.Brown)); + + // RenderCone(_spriteBatch, new Vector2(cen.X, cen.Y), 1000, rects); + // _spriteBatch.End(); + + // base.Draw(gameTime); + //} + } +} diff --git a/LightingTest/Orpticon.MonoGameLighting.csproj b/LightingTest/Orpticon.MonoGameLighting.csproj new file mode 100644 index 0000000..27e9a39 --- /dev/null +++ b/LightingTest/Orpticon.MonoGameLighting.csproj @@ -0,0 +1,30 @@ + + + Library + net6.0 + Major + false + false + + + app.manifest + Icon.ico + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/LightingTest/app.manifest b/LightingTest/app.manifest new file mode 100644 index 0000000..72338a1 --- /dev/null +++ b/LightingTest/app.manifest @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true/pm + permonitorv2,permonitor + + + +