StateRecorderImpl.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/StateRecorderImpl.h>
  6. JPH_NAMESPACE_BEGIN
  7. void StateRecorderImpl::WriteBytes(const void *inData, size_t inNumBytes)
  8. {
  9. mStream.write((const char *)inData, inNumBytes);
  10. }
  11. void StateRecorderImpl::Rewind()
  12. {
  13. mStream.seekg(0, std::stringstream::beg);
  14. }
  15. void StateRecorderImpl::ReadBytes(void *outData, size_t inNumBytes)
  16. {
  17. if (IsValidating())
  18. {
  19. // Read data in temporary buffer to compare with current value
  20. void *data = JPH_STACK_ALLOC(inNumBytes);
  21. mStream.read((char *)data, inNumBytes);
  22. if (memcmp(data, outData, inNumBytes) != 0)
  23. {
  24. // Mismatch, print error
  25. Trace("Mismatch reading %d bytes", inNumBytes);
  26. for (size_t i = 0; i < inNumBytes; ++i)
  27. {
  28. int b1 = reinterpret_cast<uint8 *>(outData)[i];
  29. int b2 = reinterpret_cast<uint8 *>(data)[i];
  30. if (b1 != b2)
  31. Trace("Offset %d: %02X -> %02X", i, b1, b2);
  32. }
  33. JPH_BREAKPOINT;
  34. }
  35. // Copy the temporary data to the final destination
  36. memcpy(outData, data, inNumBytes);
  37. return;
  38. }
  39. mStream.read((char *)outData, inNumBytes);
  40. }
  41. bool StateRecorderImpl::IsEqual(StateRecorderImpl &inReference)
  42. {
  43. // Get length of new state
  44. mStream.seekg(0, std::stringstream::end);
  45. std::streamoff this_len = mStream.tellg();
  46. mStream.seekg(0, std::stringstream::beg);
  47. // Get length of old state
  48. inReference.mStream.seekg(0, std::stringstream::end);
  49. std::streamoff reference_len = inReference.mStream.tellg();
  50. inReference.mStream.seekg(0, std::stringstream::beg);
  51. // Compare size
  52. bool fail = reference_len != this_len;
  53. if (fail)
  54. {
  55. Trace("Failed to properly recover state, different stream length!");
  56. return false;
  57. }
  58. // Compare byte by byte
  59. for (std::streamoff i = 0, l = this_len; !fail && i < l; ++i)
  60. {
  61. fail = inReference.mStream.get() != mStream.get();
  62. if (fail)
  63. {
  64. Trace("Failed to properly recover state, different at offset %d!", i);
  65. return false;
  66. }
  67. }
  68. return true;
  69. }
  70. JPH_NAMESPACE_END