1
This commit is contained in:
73
Src/Unity/Scripts/Entity/Core/EntityBinaryHeader.cs
Normal file
73
Src/Unity/Scripts/Entity/Core/EntityBinaryHeader.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
namespace BITKit.Entities
|
||||
{
|
||||
[CustomType(typeof(IEntityBinaryHeader))]
|
||||
public class EntityBinaryHeader : EntityBehavior,IEntityBinaryHeader
|
||||
{
|
||||
public int Id => (int)Entity.Id;
|
||||
public IDictionary<int, IEntityBinaryComponent> ComponentDictionary { get; } =
|
||||
new Dictionary<int, IEntityBinaryComponent>();
|
||||
|
||||
public override void OnStart()
|
||||
{
|
||||
base.OnStart();
|
||||
foreach (var component in Entity.Components.OfType<IEntityBinaryComponent>())
|
||||
{
|
||||
ComponentDictionary.Add(component.Id, component);
|
||||
}
|
||||
}
|
||||
|
||||
public void Serialize(BinaryWriter writer)
|
||||
{
|
||||
//写入组件数量
|
||||
//写入组件ID
|
||||
//写入组件数据
|
||||
//写入组件数据长度
|
||||
var length = ComponentDictionary.Count;
|
||||
writer.Write(length);
|
||||
foreach (var component in ComponentDictionary.Values)
|
||||
{
|
||||
writer.Write(component.Id);
|
||||
}
|
||||
foreach (var component in ComponentDictionary.Values)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
using var binaryWriter = new BinaryWriter(ms);
|
||||
component.Serialize(binaryWriter);
|
||||
binaryWriter.Flush();
|
||||
ms.Flush();
|
||||
var bytes = ms.ToArray();
|
||||
writer.Write(bytes.Length);
|
||||
writer.Write(bytes);
|
||||
}
|
||||
}
|
||||
public void Deserialize(BinaryReader reader)
|
||||
{
|
||||
//BIT4Log.Log<EntityBinaryHeader>("源数据长度:"+reader.BaseStream.Length);
|
||||
//读取组件数量
|
||||
//读取组件ID
|
||||
//读取组件数据
|
||||
var count = reader.ReadInt32();
|
||||
//BIT4Log.Log<EntityBinaryHeader>($"count:{count}");
|
||||
var ids = new int[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
ids[i] = reader.ReadInt32();
|
||||
}
|
||||
foreach (var id in ids)
|
||||
{
|
||||
var length = reader.ReadInt32();
|
||||
var bytes = reader.ReadBytes(length);
|
||||
using var stream = new MemoryStream(bytes);
|
||||
using var binaryReader = new BinaryReader(stream);
|
||||
//BIT4Log.Log<EntityBinaryHeader>($"id:{id},length:{length},bytes:\n{JsonHelper.Get(bytes)}");
|
||||
ComponentDictionary[id].Deserialize(binaryReader);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user