LSHelper.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System.IO;
  2. using ET.Client;
  3. namespace ET
  4. {
  5. public static class LSHelper
  6. {
  7. public static void RunRollbackSystem(Entity entity)
  8. {
  9. if (entity is LSEntity)
  10. {
  11. return;
  12. }
  13. LSSington.Instance.Rollback(entity);
  14. if (entity.ComponentsCount() > 0)
  15. {
  16. foreach (var kv in entity.Components)
  17. {
  18. RunRollbackSystem(kv.Value);
  19. }
  20. }
  21. if (entity.ChildrenCount() > 0)
  22. {
  23. foreach (var kv in entity.Children)
  24. {
  25. RunRollbackSystem(kv.Value);
  26. }
  27. }
  28. }
  29. // 回滚
  30. public static void Rollback(Room room, int frame)
  31. {
  32. Log.Debug($"roll back start {frame}");
  33. room.LSWorld.Dispose();
  34. FrameBuffer frameBuffer = room.FrameBuffer;
  35. // 回滚
  36. room.LSWorld = room.GetLSWorld(frame);
  37. OneFrameInputs authorityFrameInput = frameBuffer.FrameInputs(frame);
  38. // 执行RealFrame
  39. room.Update(authorityFrameInput, frame);
  40. // 重新执行预测的帧
  41. for (int i = room.AuthorityFrame + 1; i <= room.PredictionFrame; ++i)
  42. {
  43. OneFrameInputs oneFrameInputs = frameBuffer.FrameInputs(i);
  44. LSHelper.CopyOtherInputsTo(room, authorityFrameInput, oneFrameInputs); // 重新预测消息
  45. room.Update(oneFrameInputs, i);
  46. }
  47. RunRollbackSystem(room);
  48. Log.Debug($"roll back finish {frame}");
  49. }
  50. // 重新调整预测消息,只需要调整其他玩家的输入
  51. public static void CopyOtherInputsTo(Room room, OneFrameInputs from, OneFrameInputs to)
  52. {
  53. long myId = room.GetComponent<RoomClientUpdater>().MyId;
  54. foreach (var kv in from.Inputs)
  55. {
  56. if (kv.Key == myId)
  57. {
  58. continue;
  59. }
  60. to.Inputs[kv.Key] = kv.Value;
  61. }
  62. }
  63. public static void SaveReplay(Room room, string path)
  64. {
  65. if (room.IsReplay)
  66. {
  67. return;
  68. }
  69. Log.Debug($"save replay: {path} frame: {room.Replay.FrameInputs.Count}");
  70. byte[] bytes = MemoryPackHelper.Serialize(room.Replay);
  71. File.WriteAllBytes(path, bytes);
  72. }
  73. }
  74. }