StreamIn.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. JPH_NAMESPACE_BEGIN
  6. /// Simple binary input stream
  7. class StreamIn
  8. {
  9. public:
  10. /// Virtual destructor
  11. virtual ~StreamIn() = default;
  12. /// Read a string of bytes from the binary stream
  13. virtual void ReadBytes(void *outData, size_t inNumBytes) = 0;
  14. /// Returns true when an attempt has been made to read past the end of the file
  15. virtual bool IsEOF() const = 0;
  16. /// Returns true if there was an IO failure
  17. virtual bool IsFailed() const = 0;
  18. /// Read a primitive (e.g. float, int, etc.) from the binary stream
  19. template <class T>
  20. void Read(T &outT)
  21. {
  22. ReadBytes(&outT, sizeof(outT));
  23. }
  24. /// Read a vector of primitives from the binary stream
  25. template <class T, class A>
  26. void Read(std::vector<T, A> &outT)
  27. {
  28. typename Array<T>::size_type len = outT.size(); // Initialize to previous array size, this is used for validation in the StateRecorder class
  29. Read(len);
  30. if (!IsEOF() && !IsFailed())
  31. {
  32. outT.resize(len);
  33. for (typename Array<T>::size_type i = 0; i < len; ++i)
  34. Read(outT[i]);
  35. }
  36. else
  37. outT.clear();
  38. }
  39. /// Read a string from the binary stream (reads the number of characters and then the characters)
  40. template <class Type, class Traits, class Allocator>
  41. void Read(std::basic_string<Type, Traits, Allocator> &outString)
  42. {
  43. typename std::basic_string<Type, Traits, Allocator>::size_type len = 0;
  44. Read(len);
  45. if (!IsEOF() && !IsFailed())
  46. {
  47. outString.resize(len);
  48. ReadBytes(outString.data(), len * sizeof(Type));
  49. }
  50. else
  51. outString.clear();
  52. }
  53. /// Read a Vec3 (don't read W)
  54. void Read(Vec3 &outVec)
  55. {
  56. ReadBytes(&outVec, 3 * sizeof(float));
  57. outVec = Vec3::sFixW(outVec.mValue);
  58. }
  59. /// Read a DVec3 (don't read W)
  60. void Read(DVec3 &outVec)
  61. {
  62. ReadBytes(&outVec, 3 * sizeof(double));
  63. outVec = DVec3::sFixW(outVec.mValue);
  64. }
  65. /// Read a DMat44 (don't read W component of translation)
  66. void Read(DMat44 &outVec)
  67. {
  68. Vec4 x, y, z;
  69. Read(x);
  70. Read(y);
  71. Read(z);
  72. DVec3 t;
  73. Read(t);
  74. outVec = DMat44(x, y, z, t);
  75. }
  76. };
  77. JPH_NAMESPACE_END