Skip to content

Unity compatibility adjustments #68

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ riderModule.iml

# Rider
# Rider auto-generates .iml files, and contentModel.xml
.idea
**/.idea/**/*.iml
**/.idea/**/contentModel.xml
**/.idea/**/modules.xml
Expand All @@ -42,4 +43,5 @@ Desktop.ini
Footer
© 2022 GitHub, Inc.
Footer navigation
Terms
Terms
/UnityPublish
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Publish Arch.AOT.SourceGenerator to Unity Publish" type="DotNetFolderPublish" factoryName="Publish to folder">
<riderPublish configuration="Release" platform="Any CPU" runtime="Portable" target_folder="$PROJECT_DIR$/UnityPublish/SourceGenerators" target_framework="netstandard2.0" uuid_high="720741342265887674" uuid_low="-5713872599858624605" />
<method v="2" />
</configuration>
</component>
6 changes: 6 additions & 0 deletions .run/Publish Arch.EventBus to Unity Publish.run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Publish Arch.EventBus to Unity Publish" type="DotNetFolderPublish" factoryName="Publish to folder">
<riderPublish configuration="Release" platform="Any CPU" runtime="Portable" target_folder="$PROJECT_DIR$/UnityPublish/SourceGenerators" target_framework="netstandard2.0" uuid_high="-8378326082408201200" uuid_low="-8691373370981991138" />
<method v="2" />
</configuration>
</component>
6 changes: 6 additions & 0 deletions .run/Publish Arch.LowLevel to Unity Publish.run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Publish Arch.LowLevel to Unity Publish" type="DotNetFolderPublish" factoryName="Publish to folder">
<riderPublish configuration="Release" platform="Any CPU" runtime="Portable" target_folder="$PROJECT_DIR$/UnityPublish/Plugins" target_framework="netstandard2.1" uuid_high="50739187434734475" uuid_low="-7009414175307955308" />
<method v="2" />
</configuration>
</component>
6 changes: 6 additions & 0 deletions .run/Publish Arch.Persistence to Unity Publish.run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Publish Arch.Persistence to Unity Publish" type="DotNetFolderPublish" factoryName="Publish to folder">
<riderPublish configuration="Release" platform="Any CPU" runtime="Portable" target_folder="$PROJECT_DIR$/UnityPublish/Plugins" target_framework="netstandard2.1" uuid_high="5662267713841744598" uuid_low="-8394478303791080086" />
<method v="2" />
</configuration>
</component>
6 changes: 6 additions & 0 deletions .run/Publish Arch.Relationships to Unity Publish.run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Publish Arch.Relationships to Unity Publish" type="DotNetFolderPublish" factoryName="Publish to folder">
<riderPublish configuration="Release" platform="Any CPU" runtime="Portable" target_folder="$PROJECT_DIR$/UnityPublish/Plugins" target_framework="netstandard2.1" uuid_high="5995509060479107102" uuid_low="-5315975434817346068" />
<method v="2" />
</configuration>
</component>
6 changes: 6 additions & 0 deletions .run/Publish Arch.System to Unity Publish.run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Publish Arch.System to Unity Publish" type="DotNetFolderPublish" factoryName="Publish to folder">
<riderPublish configuration="Release" platform="Any CPU" runtime="Portable" target_folder="$PROJECT_DIR$/UnityPublish/Plugins" target_framework="netstandard2.1" uuid_high="4122545287363773375" uuid_low="-9004959171293611199" />
<method v="2" />
</configuration>
</component>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Publish Arch.System.SourceGenerator to UnityPublish" type="DotNetFolderPublish" factoryName="Publish to folder">
<riderPublish configuration="Release" platform="Any CPU" runtime="Portable" target_folder="$PROJECT_DIR$/UnityPublish/SourceGenerators" target_framework="netstandard2.0" uuid_high="-3748783982788918185" uuid_low="-8107627493768795406" />
<method v="2" />
</configuration>
</component>
3 changes: 2 additions & 1 deletion Arch.AOT.SourceGenerator/Arch.AOT.SourceGenerator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>

<GenerateDocumentationFile>true</GenerateDocumentationFile>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
<IncludeSymbols>true</IncludeSymbols>
Expand All @@ -29,6 +29,7 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Copyright>Apache2.0</Copyright>
<PackageLicenseUrl></PackageLicenseUrl>
<SatelliteResourceLanguages>en-US</SatelliteResourceLanguages>
</PropertyGroup>

<ItemGroup>
Expand Down
32 changes: 20 additions & 12 deletions Arch.AOT.SourceGenerator/Extensions/StringBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,29 +16,37 @@ public static class StringBuilderExtensions
/// <returns></returns>
public static StringBuilder AppendComponentTypes(this StringBuilder sb, IList<ComponentType> componentTypes)
{
// Lists the component registration commands line by line.
// Lists the component registration commands line by line.
var components = new StringBuilder();
foreach (var type in componentTypes)
{
var componentType = type;
components.AppendComponentType(ref componentType);
}

sb.AppendLine(
$$"""
using System.Runtime.CompilerServices;
using Arch.Core.Utils;


#if UNITY_5_6_OR_NEWER
using UnityEngine;
#endif

namespace Arch.AOT.SourceGenerator
{
internal static class GeneratedComponentRegistry
{
[ModuleInitializer]
public static void Initialize()
{
{{components}}
}
}
internal static class GeneratedComponentRegistry
{
#if UNITY_5_6_OR_NEWER
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
#else
[ModuleInitializer]
#endif
public static void Initialize()
{
{{components}}
}
}
}
"""
);
Expand All @@ -55,7 +63,7 @@ public static StringBuilder AppendComponentType(this StringBuilder sb, ref Compo
{
//var size = componentType.IsValueType ? $"Unsafe.SizeOf<{componentType.TypeName}>()" : "IntPtr.Size";
//sb.AppendLine($"ComponentRegistry.Add(typeof({componentType.TypeName}), new ComponentType(ComponentRegistry.Size + 1, {size}));");

sb.AppendLine($"ArrayRegistry.Add<{componentType.TypeName}>();");
return sb;
}
Expand Down
13 changes: 8 additions & 5 deletions Arch.AOT.SourceGenerator/SourceGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ namespace Arch.AOT.SourceGenerator;
public sealed class ComponentRegistryGenerator : IIncrementalGenerator
{
/// <summary>
/// A <see cref="List{T}"/> of annotated components (their types) found via the source-gen.
/// A <see cref="List{T}"/> of annotated components (their types) found via the source-gen.
/// </summary>
private readonly List<ComponentType> _componentTypes = new();

/// <summary>
/// The attribute to mark components with in order to be found by this source-gen.
/// The attribute to mark components with in order to be found by this source-gen.
/// </summary>
private const string AttributeTemplate = """
using System;
Expand Down Expand Up @@ -122,7 +122,7 @@ private void GenerateCode(SourceProductionContext productionContext, Compilation
foreach (var member in typeSymbol.GetMembers())
{
if (member is not IFieldSymbol) continue;

hasZeroFields = false;
break;
}
Expand All @@ -131,7 +131,10 @@ private void GenerateCode(SourceProductionContext productionContext, Compilation
_componentTypes.Add(new ComponentType(typeName, hasZeroFields, typeSymbol.IsValueType));
}

// Order component types by type name (a-z)
_componentTypes.Sort((x, y) => x.TypeName.CompareTo(y.TypeName));

sb.AppendComponentTypes(_componentTypes);
productionContext.AddSource("GeneratedComponentRegistry.g.cs",CSharpSyntaxTree.ParseText(sb.ToString()).GetRoot().NormalizeWhitespace().ToFullString());
}
}
}
1 change: 1 addition & 0 deletions Arch.EventBus/Arch.EventBus.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Copyright>Apache2.0</Copyright>
<PackageLicenseUrl></PackageLicenseUrl>
<SatelliteResourceLanguages>en-US</SatelliteResourceLanguages>
</PropertyGroup>

<ItemGroup>
Expand Down
3 changes: 2 additions & 1 deletion Arch.Extended.Sample/Arch.Extended.Sample.csproj
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Arch.Extended</RootNamespace>
<LangVersion>11</LangVersion>
<OutputType>WinExe</OutputType>
</PropertyGroup>

<ItemGroup>
Expand Down
62 changes: 30 additions & 32 deletions Arch.Extended.Sample/Game.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
using Arch.Core.Extensions;
using Arch.Bus;
using Arch.Core.Extensions.Dangerous;
using Arch.Core.Utils;
using Arch.Persistence;
using Arch.Relationships;
using Arch.System;
using MessagePack;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
Expand All @@ -28,23 +28,23 @@ public class Game : Microsoft.Xna.Framework.Game
// The world and a job scheduler for multithreading
private World _world;
private global::JobScheduler.JobScheduler _jobScheduler;

// Our systems processing entities
private System.Group<GameTime> _systems;
private Group<GameTime> _systems;
private DrawSystem _drawSystem;

// Monogame stuff
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
private Texture2D _texture2D;
private Random _random;

public Game()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}

protected override void Initialize()
{
// Setup texture and randomness
Expand All @@ -53,88 +53,86 @@ protected override void Initialize()

base.Initialize();
}

protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
_spriteBatch = new SpriteBatch(GraphicsDevice);
}

protected override void BeginRun()
{
base.BeginRun();

// Create world & JobScheduler for multithreading
_world = World.Create();
_jobScheduler = new("SampleWorkerThreads");

// Spawn in entities with position, velocity and sprite
for (var index = 0; index < 1000; index++)
{
_world.Create(
new Position{ Vector2 = _random.NextVector2(GraphicsDevice.Viewport.Bounds) },
new Velocity{ Vector2 = _random.NextVector2(-0.25f,0.25f) },
new Position{ Vector2 = _random.NextVector2(GraphicsDevice.Viewport.Bounds) },
new Velocity{ Vector2 = _random.NextVector2(-0.25f,0.25f) },
new Sprite{ Texture2D = _texture2D, Color = _random.NextColor() }
);
}

// Serialize world and deserialize it back. Just for showcasing the serialization, its actually not necessary.
var archSerializer = new ArchJsonSerializer(new SpriteSerializer{GraphicsDevice = GraphicsDevice});
var worldJson = archSerializer.ToJson(_world);
_world = archSerializer.FromJson(worldJson);

// Create systems, running in order
_systems = new System.Group<GameTime>(
_systems = new Group<GameTime>(
"Systems",
new MovementSystem(_world, GraphicsDevice.Viewport.Bounds),
new ColorSystem(_world),
new DebugSystem(_world)
);
_drawSystem = new DrawSystem(_world, _spriteBatch); // Draw system must be its own system since monogame differentiates between update and draw.
_drawSystem = new DrawSystem(_world, _spriteBatch); // Draw system must be its own system since monogame differentiates between update and draw.

// Initialize systems
_systems.Initialize();
_drawSystem.Initialize();

ComponentRegistry.Add(new ComponentType());
}

protected override void Update(GameTime gameTime)
{
// Exit game on press
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit();

// Forward keyboard state as an event to another handles by using the eventbus
var @event = (_world, Keyboard.GetState());
EventBus.Send(ref @event);

// Update systems
_systems.BeforeUpdate(in gameTime);
_systems.Update(in gameTime);
_systems.AfterUpdate(in gameTime);
_systems.BeforeExecute(in gameTime);
_systems.Execute(in gameTime);
_systems.AfterExecute(in gameTime);
base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
_graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

// Update draw system and draw stuff
_drawSystem.BeforeUpdate(in gameTime);
_drawSystem.Update(in gameTime);
_drawSystem.AfterUpdate(in gameTime);
_drawSystem.BeforeExecute(in gameTime);
_drawSystem.Execute(in gameTime);
_drawSystem.AfterExecute(in gameTime);
base.Draw(gameTime);
}

protected override void EndRun()
{
base.EndRun();
// Destroy world and shutdown the jobscheduler

// Destroy world and shutdown the jobscheduler
World.Destroy(_world);
_jobScheduler.Dispose();

// Dispose systems
_systems.Dispose();
}
}
}
Loading