using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using Gamecraft.Blocks.BlockGroups;
using Svelto.ECS;
using Svelto.ECS.EntityStructs;
using RobocraftX.Common;
using RobocraftX.Blocks;
using Unity.Mathematics;
using Gamecraft.Blocks.GUI;
using GamecraftModdingAPI.Blocks;
using GamecraftModdingAPI.Utility;
using RobocraftX.Rendering.GPUI;
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 static readonly BlockCloneEngine BlockCloneEngine = new BlockCloneEngine();
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's material
/// 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
/// Whether the block should be flipped
/// Whether the block should be auto-wired (if functional)
/// The player who placed the block
/// The placed block or null if failed
public static Block PlaceNew(BlockIDs block, float3 position, bool autoWire = false, Player player = null)
{
return PlaceNew(block, position, autoWire, 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's materialr
/// 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
/// Whether the block should be flipped
/// Whether the block should be auto-wired (if functional)
/// The player who placed the block
/// The placed block or null if failed
public static T PlaceNew(BlockIDs block, float3 position, bool autoWire = false, Player player = null)
where T : Block
{
if (PlacementEngine.IsInGame && GameState.IsBuildMode())
{
var initializer = PlacementEngine.PlaceBlock(block, position, player, autoWire);
var egid = initializer.EGID;
var bl = New(egid.entityID, egid.groupID);
bl.InitData.Group = BlockEngine.InitGroup(initializer);
bl.InitData.Reference = initializer.reference;
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(LogicGate), new [] {CommonExclusiveGroups.LOGIC_BLOCK_GROUP}},
{typeof(Motor), new[] {CommonExclusiveGroups.MOTOR_BLOCK_GROUP}},
{typeof(MusicBlock), new[] {CommonExclusiveGroups.MUSIC_BLOCK_GROUP}},
{typeof(ObjectIdentifier), new[]{CommonExclusiveGroups.OBJID_BLOCK_GROUP}},
{typeof(Piston), new[] {CommonExclusiveGroups.PISTON_BLOCK_GROUP}},
{typeof(Servo), new[] {CommonExclusiveGroups.SERVO_BLOCK_GROUP}},
{
typeof(SpawnPoint),
new[]
{
CommonExclusiveGroups.SPAWNPOINT_BLOCK_GROUP,
CommonExclusiveGroups.BUILDINGSPAWN_BLOCK_GROUP
}
},
{
typeof(SfxBlock),
new[]
{
CommonExclusiveGroups.SIMPLESFX_BLOCK_GROUP,
CommonExclusiveGroups.LOOPEDSFX_BLOCK_GROUP
}
},
{typeof(DampedSpring), new [] {CommonExclusiveGroups.DAMPEDSPRING_BLOCK_GROUP}},
{typeof(TextBlock), new[] {CommonExclusiveGroups.TEXT_BLOCK_GROUP}},
{typeof(Timer), new[] {CommonExclusiveGroups.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 => ((uint)g).ToString()).Aggregate((a, b) => a + ", " + b)} instead of {(uint)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) && !typeof(CustomBlock).IsAssignableFrom(type))
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.");
}
///
/// Places a new block in the world.
///
/// The block's type
/// The block's position (a block is 0.2 wide in terms of position)
/// Whether the block should be auto-wired (if functional)
/// The player who placed the block
public Block(BlockIDs type, float3 position, bool autoWire = false, Player player = null)
{
if (!PlacementEngine.IsInGame || !GameState.IsBuildMode())
throw new BlockException("Blocks can only be placed in build mode.");
var initializer = PlacementEngine.PlaceBlock(type, position, player, autoWire);
Id = initializer.EGID;
InitData.Group = BlockEngine.InitGroup(initializer);
Placed += OnPlacedInit;
}
public EGID Id { get; }
internal BlockEngine.BlockInitData InitData;
private EGID copiedFrom;
///
/// 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);
if (blockGroup != null)
blockGroup.PosAndRotCalculated = false;
BlockEngine.UpdateDisplayedBlock(Id);
}
}
///
/// 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);
if (blockGroup != null)
blockGroup.PosAndRotCalculated = false;
BlockEngine.UpdateDisplayedBlock(Id);
}
}
///
/// 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
{
int uscale = UniformScale;
if (value.x < 4e-5) value.x = uscale;
if (value.y < 4e-5) value.y = uscale;
if (value.z < 4e-5) value.z = uscale;
BlockEngine.SetBlockInfo(this, (ref ScalingEntityStruct st, float3 val) => st.scale = val, value);
if (!Exists) return; //UpdateCollision needs the block to exist
ScalingEngine.UpdateCollision(Id);
BlockEngine.UpdateDisplayedBlock(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
{
if (value < 1) value = 1;
BlockEngine.SetBlockInfo(this, (ref UniformBlockScaleEntityStruct st, int val) => st.scaleFactor = val,
value);
Scale = new float3(value, value, value);
}
}
/**
* Whether the block is flipped.
*/
public bool Flipped
{
get => BlockEngine.GetBlockInfo(this, (ScalingEntityStruct st) => st.scale.x < 0);
set
{
BlockEngine.SetBlockInfo(this, (ref ScalingEntityStruct st, bool val) =>
st.scale.x = math.abs(st.scale.x) * (val ? -1 : 1), value);
BlockEngine.SetBlockInfo(this, (ref GFXPrefabEntityStructGPUI st, bool val) =>
{
uint prefabId = PrefabsID.GetOrCreatePrefabID((ushort) Type, (byte) Material, 0, value);
st.prefabID = prefabId;
}, 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) =>
{ //TODO: Check if setting to 255 works
color.indexInPalette = val.Index;
color.hasNetworkChange = 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.paletteColour);
set
{
BlockEngine.SetBlockInfo(this, (ref ColourParameterEntityStruct color, float4 val) =>
{
color.paletteColour = val;
color.hasNetworkChange = true;
}, value);
}
}
/**
* The block's material.
*/
public BlockMaterial Material
{
get => BlockEngine.GetBlockInfo(this, (CubeMaterialStruct cmst) => (BlockMaterial) cmst.materialId, BlockMaterial.Default);
set => BlockEngine.SetBlockInfo(this,
(ref CubeMaterialStruct cmst, BlockMaterial val) => cmst.materialId = (byte) val, 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);
}
}
private BlockGroup blockGroup;
///
/// Returns the block group this block is a part of. Block groups can also be placed using blueprints.
/// Returns null if not part of a group.
/// Setting the group after the block has been initialized will not update everything properly,
/// so you can only set this property on blocks newly placed by your code.
/// To set it for existing blocks, you can use the Copy() method and set the property on the resulting block
/// (and remove this block).
///
public BlockGroup BlockGroup
{
get
{
if (blockGroup != null) return blockGroup;
return blockGroup = BlockEngine.GetBlockInfo(this,
(BlockGroupEntityComponent bgec) =>
bgec.currentBlockGroup == -1 ? null : new BlockGroup(bgec.currentBlockGroup, this));
}
set
{
if (Exists)
{
Logging.LogWarning("Attempted to set group of existing block. This is not supported."
+ " Copy the block and set the group of the resulting block.");
return;
}
blockGroup?.RemoveInternal(this);
BlockEngine.SetBlockInfo(this,
(ref BlockGroupEntityComponent bgec, BlockGroup val) => bgec.currentBlockGroup = val?.Id ?? -1,
value);
value?.AddInternal(this);
blockGroup = 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);
}
///
/// Creates a copy of the block in the game with the same properties, stats and wires.
///
///
public T Copy() where T : Block
{
var block = PlaceNew(Type, Position);
block.Rotation = Rotation;
block.Color = Color;
block.Material = Material;
block.UniformScale = UniformScale;
block.Scale = Scale;
block.copiedFrom = Id;
return block;
}
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
if (copiedFrom != EGID.Empty)
BlockCloneEngine.CopyBlockStats(copiedFrom, Id);
}
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);
GameEngineManager.AddGameEngine(BlockCloneEngine);
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
}
}