Skip to content

Commit

Permalink
Client (#14)
Browse files Browse the repository at this point in the history
* Moved stuff around

* Extra assert during LoadBlock

* wip

* [Client] fix OnBlockPacket

* [Client] Fix resizing block cache

* Fix compressed and large packets handling

* Beginning of CentrED#

* Fix depth for UI

* Optimal packets compression

* Embedded server

* Better LoadBlocks + allowed cache resize

* Reworked StaticBlock tiles handling + slight optimizations

* better packet logging

* wip

* Updated renderer

* debug ui

* register land packet + noop on no activity + fixed loading blocks

* update lastActivity on flush

* Rework camera

* Hues support

* client landscape packet handlers

* Removed shadowRenderer leftovers

* Let server manage client lastpos

* Bring back old billboard rendering

* Mouse selection + some fixes

* Resizable window

* No inheritance for tiles and blocks

* Made client changes work + aligned server

* WIP, unified tiledata with classicuo struct, Works on CentrED UI of server connect/disconnect/start/stop

* Start/Stop local server actually works

* LandTiles selection, basic tools, better tiles preparation

* TileSelection tool

* Preload art, refactor, scrolling tiles with arrows

* Replaced Tiles tabBar with checkbox

* Hues window, real art bounds, better info tool, pointClamp sampler for UI

* Small fixes

* Fix tiles filtering

* Beginning of hues manager

* Small improfement for radarmap init

* Hues filtering

* Small clienup of landRenderInfo

* Draw UI on Draw phase to get rid of unresponsive UI

* Optimise the rendering

* FPS and resolution in debug window

* fix selection

* fix info tool

* preload texmap

* MapRenderer cleanup

* Static HuesManager instance, cleanup in tools,

* MapManager reset function

* New Tools interface, RemoveTool, disabled inputs when app is not active

* Transparency as indicator for tile removal

* Fix map persistence

* Updated ElevateTool + beginning of DrawTool

* Fix client on insert packet

* InfoWindow, InfoTool=>SelectTool, Basic inheritance in tiles, working draw tool for statics, some bugfixes

* MoveTool, explicitly update static hue after change

* Fix UpdateRadar

* DrawTool for land

* Elevate land kind of working

* Basic crashlog

* Basic config

* Load only what's needed

* Don't preload all the graphics

* Fix solution for VisualStudio

* Added output to gitignore

* Fix UOP support

* Fix: incorrect cache size when moving or zooming (#11)

* Fix resizing of cache when moving/zooming

* Reduce size of previw range to / 8 instead of using * 4

* Reduce cache size even further

* Fix default selected tile

* Background image for the application

* Do not request invalid blocks

* Request more blocks than are in view range

* Prevent crash when creating password (#12)

* Forgot the braces (#13)

* Quit, Options placehoder, Server Sort tiles before sending to client, fix for config update

* Fix after merging master :)

---------

Co-authored-by: Blade12629 <[email protected]>
  • Loading branch information
kaczy93 and Blade12629 authored Oct 21, 2023
1 parent 292daee commit 1b080a0
Show file tree
Hide file tree
Showing 97 changed files with 5,462 additions and 932 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
bin/
obj/
output/
/packages/
riderModule.iml
/_ReSharper.Caches/
Expand Down
9 changes: 9 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[submodule "FNA"]
path = external/FNA
url = https://github.com/fna-xna/fna
[submodule "fna-libs"]
path = external/fna-libs
url = https://github.com/deccer/fna-libs
[submodule "ImGui"]
path = external/ImGui.NET
url = https://github.com/ImGuiNET/ImGui.NET
73 changes: 73 additions & 0 deletions CentrED/Camera.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using Microsoft.Xna.Framework;

namespace CentrED;

public class Camera
{
// 1.0 is standard. Large zooms in, smaller zooms out.
public float Zoom = 1.0f;

// Camera rotation around the Z axis, in degrees
public float Rotation = 0;

public Rectangle ScreenSize;

private Matrix _mirrorX = Matrix.CreateReflection(new Plane(-1, 0, 0, 0));

private Vector3 _up = new(-1, -1, 0);

/* This takes the coordinates (x, y, z) and turns it into the screen point (x, y + z, z) */
private Matrix _oblique = new Matrix(
1, 0, 0, 0,
0, 1, 0, 0,
0, 1, 1, 0,
0, 0, 0, 1);

private Matrix _translation = Matrix.CreateTranslation(new Vector3(0, 128 * 4, 0));

public Vector3 Position = new(0, 0, 128 * 4);

//Look directly below camera
public Vector3 LookAt => new(Position.X, Position.Y, 0);

public Matrix world;
public Matrix view;
public Matrix proj;

public Matrix WorldViewProj { get; private set; }

public bool Moved;

public void Move(float xDelta, float yDelta) {
Position.X += xDelta;
Position.Y += yDelta;
Moved = true;
}

public void ZoomIn(float delta) {
Zoom += delta;
Moved = true;
}

public void Update()
{
//Tiles are in world coordinates
world = Matrix.Identity;

var up = Vector3.Transform(_up, Matrix.CreateRotationZ(MathHelper.ToRadians(Rotation)));

view = Matrix.CreateLookAt(Position, LookAt, up);

Matrix ortho = Matrix.CreateOrthographic(ScreenSize.Width, ScreenSize.Height, 0, 128 * 8);

Matrix scale = Matrix.CreateScale(Zoom, Zoom, 1f);

proj = _mirrorX * _oblique * _translation * ortho * scale;

Matrix.Multiply(ref world, ref view, out var worldView);
Matrix.Multiply(ref worldView, ref proj, out var worldViewProj);

WorldViewProj = worldViewProj;
Moved = false;
}
}
111 changes: 111 additions & 0 deletions CentrED/CentrED.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using CentrED.Client;
using CentrED.Server;
using Microsoft.Xna.Framework;

namespace CentrED;

public class CentrED {

static private AssemblyLoadContext _loadContext;
static private string? _rootDir;

static private Assembly? LoadFromResource(string resourceName)
{
Console.WriteLine($"Loading resource {resourceName}");

foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var name = $"{assembly.GetName().Name}.{resourceName}.dll";
if (name.StartsWith("System."))
continue;

using Stream? s = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{resourceName}.dll");

if (s == null || s.Length == 0)
continue;

return _loadContext.LoadFromStream(s);
}

return null;
}

static private Assembly? ResolveAssembly(AssemblyLoadContext loadContext, AssemblyName assemblyName)
{
Console.WriteLine($"Resolving assembly {assemblyName}");

if (loadContext != _loadContext)
{
throw new Exception("Mismatched load contexts!");
}

if (assemblyName == null || assemblyName.Name == null)
{
throw new Exception("Unable to load null assembly");
}

/* Wasn't in same directory. Try to load it as a resource. */
return LoadFromResource(assemblyName.Name);
}

static private IntPtr ResolveUnmanagedDll(Assembly assembly, string unmanagedDllName)
{
Console.WriteLine($"Loading unmanaged DLL {unmanagedDllName} for {assembly.GetName().Name}");

/* Try the correct native libs directory first */
string osDir = "";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
osDir = "x64";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
osDir = "osx";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
osDir = "lib64";
}

var libraryPath = Path.Combine(_rootDir, osDir, unmanagedDllName);

Console.WriteLine($"Resolved DLL to {libraryPath}");

if (File.Exists(libraryPath))
return NativeLibrary.Load(libraryPath);

return IntPtr.Zero;
}

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetDllDirectory(string lpPathName);

public static CEDServer? Server;
public static readonly CentrEDClient Client = new();

[STAThread]
public static void Main(string[] args)
{
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

_rootDir = AppContext.BaseDirectory;
Console.WriteLine($"Root Dir: {_rootDir}");

_loadContext = AssemblyLoadContext.Default;
_loadContext.ResolvingUnmanagedDll += ResolveUnmanagedDll;
_loadContext.Resolving += ResolveAssembly;

using Game g = new CentrEDGame();
try {
g.Run();
}
catch (Exception e) {
File.WriteAllText("Crash.log", e.ToString());
}
}
}
58 changes: 56 additions & 2 deletions CentrED/CentrED.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,67 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<Platforms>x64</Platforms>

<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>

<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>

<EnableSingleFileAnalysis>true</EnableSingleFileAnalysis>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>

<OutDir>../output</OutDir>
<PublishDir>../publish</PublishDir>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\Client\Client.csproj" />
<ProjectReference Include="..\Shared\Shared.csproj" />
<ProjectReference Include="..\Client\Client.csproj" />
<ProjectReference Include="..\Server\Server.csproj" />
<ProjectReference Include="..\Shared\Shared.csproj" />
<ProjectReference Include="..\external\FNA\FNA.Core.csproj" />
<ProjectReference Include="..\external\ImGui.NET\src\ImGui.NET\ImGui.NET.csproj" />
</ItemGroup>

<ItemGroup>
<Content Include="..\external\ImGui.NET\deps\cimgui\win-x64\cimgui.dll" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

<ItemGroup>
<EmbeddedResource Include="Renderer\Effects\Shaders\*.fxc" />
</ItemGroup>

<ItemGroup>
<DataFiles_libs Include="..\external\fna-libs\**" />
<DataFiles_libs Include="..\lib\**" />
</ItemGroup>

<ItemGroup>
<Reference Include="ClassicUO.Assets">
<HintPath>..\lib\x64\ClassicUO.Assets.dll</HintPath>
</Reference>
<Reference Include="ClassicUO.IO">
<HintPath>..\lib\x64\ClassicUO.IO.dll</HintPath>
</Reference>
<Reference Include="ClassicUO.Utility">
<HintPath>..\lib\x64\ClassicUO.Utility.dll</HintPath>
</Reference>
</ItemGroup>

<ItemGroup>
<None Update="background.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

<Target Name="CopyExternalDeps_build" AfterTargets="Build">
<Copy SourceFiles="@(DataFiles_libs)" DestinationFiles="@(DataFiles_libs->'$(OutDir)/%(RecursiveDir)%(Filename)%(Extension)')" SkipUnchangedFiles="true" />
</Target>

<Target Name="CopyExternalDeps_publish" AfterTargets="Publish">
<Copy SourceFiles="@(DataFiles_libs)" DestinationFiles="@(DataFiles_libs->'$(PublishDir)/%(RecursiveDir)%(Filename)%(Extension)')" SkipUnchangedFiles="true" />
</Target>

</Project>
107 changes: 107 additions & 0 deletions CentrED/CentrEDGame.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
using System.Runtime.InteropServices;
using CentrED.Client;
using CentrED.Map;
using CentrED.UI;
using ClassicUO.Assets;
using ClassicUO.Utility;
using ClassicUO.Utility.Logging;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace CentrED;

internal class CentrEDGame : Game
{
private readonly GraphicsDeviceManager _gdm;

private CentrEDClient _centredClient;
private MapManager _mapManager;
private UIManager _uiManager;
private HuesManager _huesManager;

public CentrEDGame()
{
_gdm = new GraphicsDeviceManager(this)
{
IsFullScreen = false,
PreferredDepthStencilFormat = DepthFormat.Depth24
};

_gdm.PreparingDeviceSettings += (sender, e) => { e.GraphicsDeviceInformation.PresentationParameters.RenderTargetUsage = RenderTargetUsage.DiscardContents; };

IsMouseVisible = true;
Window.AllowUserResizing = true;
Window.ClientSizeChanged += OnWindowResized;
}

protected override unsafe void Initialize()
{
if (_gdm.GraphicsDevice.Adapter.IsProfileSupported(GraphicsProfile.HiDef))
{
_gdm.GraphicsProfile = GraphicsProfile.HiDef;
}

_gdm.ApplyChanges();

NativeLibrary.Load(Path.Combine(AppContext.BaseDirectory, "x64", "zlib.dll"));
Log.Start(LogTypes.All);
var version = ClientVersionHelper.IsClientVersionValid(Config.ClientVersion, out var clientVersion);
UOFileManager.BasePath = Config.ClientPath;
UOFileManager.Version = clientVersion;
UOFileManager.IsUOPInstallation = clientVersion >= ClientVersion.CV_7000 && File.Exists(UOFileManager.GetUOFilePath("MainMisc.uop"));

if (!Task.WhenAll( new List<Task>
{
ArtLoader.Instance.Load(),
HuesLoader.Instance.Load(),
TileDataLoader.Instance.Load(),
TexmapsLoader.Instance.Load(),
}).Wait(TimeSpan.FromSeconds(10.0)))
Log.Panic("Loading files timeout.");

TextureAtlas.InitializeSharedTexture(_gdm.GraphicsDevice);
HuesManager.Initialize(_gdm.GraphicsDevice);
var background = Content.Load<Texture2D>("background");
_mapManager = new MapManager(_gdm.GraphicsDevice, background);
_uiManager = new UIManager(this, _gdm.GraphicsDevice, _mapManager);

base.Initialize();
}

protected override void LoadContent()
{
base.LoadContent();
}

protected override void UnloadContent()
{
base.UnloadContent();
}

protected override void Update(GameTime gameTime)
{
CentrED.Client.Update();
_uiManager.Update(gameTime, IsActive);
_mapManager.Update(gameTime, IsActive, !_uiManager.CapturingMouse, !_uiManager.CapturingKeyboard);

base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
// if (!IsActive)
// return;

_mapManager.Draw();
_uiManager.Draw(gameTime);

base.Draw(gameTime);
}


private void OnWindowResized(object? sender, EventArgs e) {
GameWindow window = sender as GameWindow;
if (window != null)
_mapManager.OnWindowsResized(window);
}
}
Loading

0 comments on commit 1b080a0

Please sign in to comment.