using System; using System.Collections.Generic; using System.Linq; using System.Reflection.Emit; using Svelto.ECS; using Svelto.ECS.EntityStructs; using RobocraftX.Common; using RobocraftX.Blocks; using Unity.Mathematics; using Unity.Entities; using Gamecraft.Blocks.GUI; using GamecraftModdingAPI.Blocks; using GamecraftModdingAPI.Utility; namespace GamecraftModdingAPI { /// /// A single (perhaps scaled) block. Properties may return default values if the block is removed and then setting them is ignored. /// For specific block type operations, use the specialised block classes in the GamecraftModdingAPI.Blocks namespace. /// public class Block : IEquatable, IEquatable { protected static readonly PlacementEngine PlacementEngine = new PlacementEngine(); protected static readonly MovementEngine MovementEngine = new MovementEngine(); protected static readonly RotationEngine RotationEngine = new RotationEngine(); protected static readonly RemovalEngine RemovalEngine = new RemovalEngine(); protected static readonly SignalEngine SignalEngine = new SignalEngine(); protected static readonly BlockEventsEngine BlockEventsEngine = new BlockEventsEngine(); protected static readonly ScalingEngine ScalingEngine = new ScalingEngine(); protected internal static readonly BlockEngine BlockEngine = new BlockEngine(); /// /// Place a new block at the given position. If scaled, position means the center of the block. The default block size is 0.2 in terms of position. /// Place blocks next to each other to connect them. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game. /// /// The block's type /// The block's color /// The block color's darkness (0-9) - 0 is default color /// The block's position - default block size is 0.2 /// The block's rotation in degrees /// The block's uniform scale - default scale is 1 (with 0.2 width) /// The block's non-uniform scale - 0 means is used /// The player who placed the block /// The placed block or null if failed public static Block PlaceNew(BlockIDs block, float3 position, float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0, int uscale = 1, float3 scale = default, Player player = null) { return PlaceNew(block, position, rotation, color, darkness, uscale, scale, player); } /// /// Place a new block at the given position. If scaled, position means the center of the block. The default block size is 0.2 in terms of position. /// Place blocks next to each other to connect them. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game. /// /// The block's type /// The block's color /// The block color's darkness (0-9) - 0 is default color /// The block's position - default block size is 0.2 /// The block's rotation in degrees /// The block's uniform scale - default scale is 1 (with 0.2 width) /// The block's non-uniform scale - 0 means is used /// The player who placed the block /// The placed block or null if failed public static T PlaceNew(BlockIDs block, float3 position, float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0, int uscale = 1, float3 scale = default, Player player = null) where T : Block { if (PlacementEngine.IsInGame && GameState.IsBuildMode()) { var egid = PlacementEngine.PlaceBlock(block, color, darkness, position, uscale, scale, player, rotation, out var initializer); var bl = New(egid.entityID, egid.groupID); bl.InitData.Group = BlockEngine.InitGroup(initializer); Placed += bl.OnPlacedInit; return bl; } return null; } /// /// Returns the most recently placed block. /// /// The block object public static Block GetLastPlacedBlock() { return New(BlockIdentifiers.LatestBlockID); } /// /// An event that fires each time a block is placed. /// public static event EventHandler Placed { add => BlockEventsEngine.Placed += value; remove => BlockEventsEngine.Placed -= value; } /// /// An event that fires each time a block is removed. /// public static event EventHandler Removed { add => BlockEventsEngine.Removed += value; remove => BlockEventsEngine.Removed -= value; } private static Dictionary> initializers = new Dictionary>(); private static Dictionary typeToGroup = new Dictionary { {typeof(ConsoleBlock), new[] {CommonExclusiveGroups.BUILD_CONSOLE_BLOCK_GROUP}}, {typeof(LogicGate), new [] {CommonExclusiveGroups.BUILD_LOGIC_BLOCK_GROUP}}, {typeof(Motor), new[] {CommonExclusiveGroups.BUILD_MOTOR_BLOCK_GROUP}}, {typeof(MusicBlock), new[] {CommonExclusiveGroups.BUILD_MUSIC_BLOCK_GROUP}}, {typeof(ObjectIdentifier), new[]{CommonExclusiveGroups.BUILD_OBJID_BLOCK_GROUP}}, {typeof(Piston), new[] {CommonExclusiveGroups.BUILD_PISTON_BLOCK_GROUP}}, {typeof(Servo), new[] {CommonExclusiveGroups.BUILD_SERVO_BLOCK_GROUP}}, { typeof(SpawnPoint), new[] { CommonExclusiveGroups.BUILD_SPAWNPOINT_BLOCK_GROUP, CommonExclusiveGroups.BUILD_BUILDINGSPAWN_BLOCK_GROUP } }, { typeof(SfxBlock), new[] { CommonExclusiveGroups.BUILD_SIMPLESFX_BLOCK_GROUP, CommonExclusiveGroups.BUILD_LOOPEDSFX_BLOCK_GROUP } }, {typeof(DampedSpring), new [] {CommonExclusiveGroups.BUILD_DAMPEDSPRING_BLOCK_GROUP}}, {typeof(TextBlock), new[] {CommonExclusiveGroups.BUILD_TEXT_BLOCK_GROUP}}, {typeof(Timer), new[] {CommonExclusiveGroups.BUILD_TIMER_BLOCK_GROUP}} }; /// /// Constructs a new instance of T with the given ID and group using dynamically created delegates. /// It's equivalent to new T(EGID) with a minimal overhead thanks to caching the created delegates. /// /// The block ID /// The block group /// The block's type or Block itself /// An instance of the provided type /// The block group doesn't match or cannot be found /// The block class doesn't have the needed constructor private static T New(uint id, ExclusiveGroupStruct? group = null) where T : Block { var type = typeof(T); EGID egid; if (!group.HasValue) { if (typeToGroup.TryGetValue(type, out var gr) && gr.Length == 1) egid = new EGID(id, gr[0]); else egid = BlockEngine.FindBlockEGID(id) ?? throw new BlockTypeException("Could not find block group!"); } else { egid = new EGID(id, group.Value); if (typeToGroup.TryGetValue(type, out var gr) && gr.All(egs => egs != group.Value)) //If this subclass has a specific group, then use that - so Block should still work throw new BlockTypeException($"Incompatible block type! Type {type.Name} belongs to group {gr.Select(g => g.ToString()).Aggregate((a, b) => a + ", " + b)} instead of {group.Value}"); } if (initializers.TryGetValue(type, out var func)) { var bl = (T) func(egid); return bl; } //https://stackoverflow.com/a/10593806/2703239 var ctor = type.GetConstructor(new[] {typeof(EGID)}); if (ctor == null) throw new MissingMethodException("There is no constructor with an EGID parameter for this object"); DynamicMethod dynamic = new DynamicMethod(string.Empty, type, new[] {typeof(EGID)}, type); ILGenerator il = dynamic.GetILGenerator(); //il.DeclareLocal(type); il.Emit(OpCodes.Ldarg_0); //Load EGID and pass to constructor il.Emit(OpCodes.Newobj, ctor); //Call constructor //il.Emit(OpCodes.Stloc_0); - doesn't seem like we need these //il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ret); func = (Func) dynamic.CreateDelegate(typeof(Func)); initializers.Add(type, func); var block = (T) func(egid); return block; } public Block(EGID id) { Id = id; var type = GetType(); if (typeToGroup.TryGetValue(type, out var groups)) { if (groups.All(gr => gr != id.groupID)) throw new BlockTypeException("The block has the wrong group! The type is " + GetType() + " while the group is " + id.groupID); } else if (type != typeof(Block)) Logging.LogWarning($"Unknown block type! Add {type} to the dictionary."); } /// /// This overload searches for the correct group the block is in. /// It will throw an exception if the block doesn't exist. /// Use the EGID constructor where possible or subclasses of Block as those specify the group. /// public Block(uint id) { Id = BlockEngine.FindBlockEGID(id) ?? throw new BlockTypeException("Could not find the appropriate group for the block. The block probably doesn't exist or hasn't been submitted."); } public EGID Id { get; } internal BlockEngine.BlockInitData InitData; /// /// The block's current position or zero if the block no longer exists. /// A block is 0.2 wide by default in terms of position. /// public float3 Position { get => MovementEngine.GetPosition(Id, InitData); set { MovementEngine.MoveBlock(Id, InitData, value); } } /// /// The block's current rotation in degrees or zero if the block doesn't exist. /// public float3 Rotation { get => RotationEngine.GetRotation(Id, InitData); set { RotationEngine.RotateBlock(Id, InitData, value); } } /// /// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling. /// The default scale of 1 means 0.2 in terms of position. /// public float3 Scale { get => BlockEngine.GetBlockInfo(this, (ScalingEntityStruct st) => st.scale); set { BlockEngine.SetBlockInfo(this, (ref ScalingEntityStruct st, float3 val) => st.scale = val, value); if (!Exists) return; //UpdateCollision needs the block to exist ScalingEngine.UpdateCollision(Id); } } /// /// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale. /// The default scale of 1 means 0.2 in terms of position. /// public int UniformScale { get => BlockEngine.GetBlockInfo(this, (UniformBlockScaleEntityStruct st) => st.scaleFactor); set { BlockEngine.SetBlockInfo(this, (ref UniformBlockScaleEntityStruct st, int val) => st.scaleFactor = val, value); Scale = new float3(value, value, value); } } /// /// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore. /// public BlockIDs Type { get { return BlockEngine.GetBlockInfo(this, (DBEntityStruct st) => (BlockIDs) st.DBID, BlockIDs.Invalid); } } /// /// The block's color. Returns BlockColors.Default if the block no longer exists. /// public BlockColor Color { get { byte index = BlockEngine.GetBlockInfo(this, (ColourParameterEntityStruct st) => st.indexInPalette, byte.MaxValue); return new BlockColor(index); } set { BlockEngine.SetBlockInfo(this, (ref ColourParameterEntityStruct color, BlockColor val) => { color.indexInPalette = (byte) (val.Color + val.Darkness * 10); color.overridePaletteColour = false; color.needsUpdate = true; color.paletteColour = BlockEngine.ConvertBlockColor(color.indexInPalette); }, value); } } /// /// The block's exact color. Gets reset to the palette color (Color property) after reentering the game. /// public float4 CustomColor { get => BlockEngine.GetBlockInfo(this, (ColourParameterEntityStruct st) => st.overriddenColour); set { BlockEngine.SetBlockInfo(this, (ref ColourParameterEntityStruct color, float4 val) => { color.overriddenColour = val; color.overridePaletteColour = true; color.needsUpdate = true; }, value); } } /// /// The text displayed on the block if applicable, or null. /// Setting it is temporary to the session, it won't be saved. /// public string Label { get => BlockEngine.GetBlockInfoViewStruct(this, (TextLabelEntityViewStruct st) => st.textLabelComponent?.text); set { BlockEngine.SetBlockInfoViewStruct(this, (ref TextLabelEntityViewStruct text, string val) => { if (text.textLabelComponent != null) text.textLabelComponent.text = val; }, value); } } /// /// Whether the block exists. The other properties will return a default value if the block doesn't exist. /// If the block was just placed, then this will also return false but the properties will work correctly. /// public bool Exists => BlockEngine.BlockExists(Id); /// /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist. /// public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id); /// /// Removes this block. /// /// True if the block exists and could be removed. public bool Remove() => RemovalEngine.RemoveBlock(Id); /// /// Returns the rigid body of the chunk of blocks this one belongs to during simulation. /// Can be used to apply forces or move the block around while the simulation is running. /// /// The SimBody of the chunk or null if the block doesn't exist or not in simulation mode. public SimBody GetSimBody() { return BlockEngine.GetBlockInfo(this, (GridConnectionsEntityStruct st) => st.machineRigidBodyId != uint.MaxValue ? new SimBody(st.machineRigidBodyId, st.clusterId) : null); } private void OnPlacedInit(object sender, BlockPlacedRemovedEventArgs e) { //Member method instead of lambda to avoid constantly creating delegates if (e.ID != Id) return; Placed -= OnPlacedInit; //And we can reference it InitData = default; //Remove initializer as it's no longer valid - if the block gets removed it shouldn't be used again } public override string ToString() { return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Type)}: {Type}, {nameof(Color)}: {Color}, {nameof(Exists)}: {Exists}"; } public bool Equals(Block other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Id.Equals(other.Id); } public bool Equals(EGID other) { return Id.Equals(other); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Block) obj); } public override int GetHashCode() { return Id.GetHashCode(); } public static void Init() { GameEngineManager.AddGameEngine(PlacementEngine); GameEngineManager.AddGameEngine(MovementEngine); GameEngineManager.AddGameEngine(RotationEngine); GameEngineManager.AddGameEngine(RemovalEngine); GameEngineManager.AddGameEngine(BlockEngine); GameEngineManager.AddGameEngine(BlockEventsEngine); GameEngineManager.AddGameEngine(ScalingEngine); GameEngineManager.AddGameEngine(SignalEngine); Wire.signalEngine = SignalEngine; // requires same functionality, no need to duplicate the engine } /// /// Convert the block to a specialised block class. /// /// The block. /// The specialised block type. public T Specialise() where T : Block { // What have I gotten myself into? // C# can't cast to a child of Block unless the object was originally that child type // And C# doesn't let me make implicit cast operators for child types // So thanks to Microsoft, we've got this horrible implementation using reflection //Lets improve that using delegates var block = New(Id.entityID, Id.groupID); if (this.InitData.Group != null) { block.InitData = this.InitData; Placed += block.OnPlacedInit; //Reset InitData of new object } return block; } #if DEBUG public static EntitiesDB entitiesDB { get { return BlockEngine.GetEntitiesDB(); } } #endif } }