ObjectStreamIn.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Core/Factory.h>
  5. #include <Jolt/ObjectStream/SerializableAttribute.h>
  6. #include <Jolt/ObjectStream/ObjectStreamIn.h>
  7. #include <Jolt/ObjectStream/ObjectStreamTextIn.h>
  8. #include <Jolt/ObjectStream/ObjectStreamBinaryIn.h>
  9. #include <Jolt/ObjectStream/SerializableObject.h>
  10. #include <unordered_set>
  11. namespace JPH {
  12. ObjectStreamIn::ObjectStreamIn(istream &inStream) :
  13. mStream(inStream)
  14. {
  15. }
  16. bool ObjectStreamIn::GetInfo(istream &inStream, EStreamType &outType, int &outVersion, int &outRevision)
  17. {
  18. // Read header and check if it is the correct format, e.g. "TOS 1.00"
  19. char header[9];
  20. memset(header, 0, 9);
  21. inStream.read(header, 8);
  22. if ((header[0] == 'B' || header[0] == 'T') && header[1] == 'O' && header[2] == 'S'
  23. && (header[3] == ' ' || isdigit(header[3])) && isdigit(header[4])
  24. && header[5] == '.' && isdigit(header[6]) && isdigit(header[7]))
  25. {
  26. // Check if this is a binary or text objectfile
  27. switch (header[0])
  28. {
  29. case 'T': outType = ObjectStream::EStreamType::Text; break;
  30. case 'B': outType = ObjectStream::EStreamType::Binary; break;
  31. default: JPH_ASSERT(false); break;
  32. }
  33. // Extract version and revision
  34. header[5] = '\0';
  35. outVersion = atoi(&header[3]);
  36. outRevision = atoi(&header[6]);
  37. return true;
  38. }
  39. Trace("ObjectStreamIn: Not a valid object stream.");
  40. return false;
  41. }
  42. ObjectStreamIn *ObjectStreamIn::Open(istream &inStream)
  43. {
  44. // Check if file is an ObjectStream of the correct version and revision
  45. EStreamType type;
  46. int version;
  47. int revision;
  48. if (GetInfo(inStream, type, version, revision))
  49. {
  50. if (version == sVersion && revision == sRevision)
  51. {
  52. // Create an input stream of the correct type
  53. switch (type)
  54. {
  55. case EStreamType::Text: return new ObjectStreamTextIn(inStream);
  56. case EStreamType::Binary: return new ObjectStreamBinaryIn(inStream);
  57. default: JPH_ASSERT(false);
  58. }
  59. }
  60. else
  61. {
  62. Trace("ObjectStreamIn: Different version stream (%d.%02d, expected %d.%02d).", version, revision, sVersion, sRevision);
  63. }
  64. }
  65. return nullptr;
  66. }
  67. void *ObjectStreamIn::Read(const RTTI *inRTTI)
  68. {
  69. using ObjectSet = unordered_set<void *>;
  70. // Read all information on the stream
  71. void *main_object = nullptr;
  72. bool continue_reading = true;
  73. for (;;)
  74. {
  75. // Get type of next operation
  76. EDataType data_type;
  77. if (!ReadDataType(data_type))
  78. break;
  79. if (data_type == EDataType::Declare)
  80. {
  81. // Read type declaration
  82. if (!ReadRTTI())
  83. {
  84. Trace("ObjectStreamIn: Fatal error while reading class description for class %s.", inRTTI->GetName());
  85. continue_reading = false;
  86. break;
  87. }
  88. }
  89. else if (data_type == EDataType::Object)
  90. {
  91. const RTTI *rtti;
  92. void *object = ReadObject(rtti);
  93. if (!main_object && object)
  94. {
  95. // This is the first and thus main object of the file.
  96. if (rtti->IsKindOf(inRTTI))
  97. {
  98. // Object is of correct type
  99. main_object = object;
  100. }
  101. else
  102. {
  103. Trace("ObjectStreamIn: Main object of different type. Expected %s, but found %s.", inRTTI->GetName(), rtti->GetName());
  104. continue_reading = false;
  105. break;
  106. }
  107. }
  108. }
  109. else
  110. {
  111. // Invalid or out of place token found
  112. Trace("ObjectStreamIn: Invalid or out of place token found.");
  113. continue_reading = false;
  114. break;
  115. }
  116. }
  117. // Resolve links (pointer, references)
  118. if (continue_reading)
  119. {
  120. // Resolve links
  121. ObjectSet referenced_objects;
  122. for (Link &link : mUnresolvedLinks)
  123. {
  124. IdentifierMap::const_iterator j = mIdentifierMap.find(link.mIdentifier);
  125. if (j != mIdentifierMap.end() && j->second.mRTTI->IsKindOf(link.mRTTI))
  126. {
  127. const ObjectInfo &obj_info = j->second;
  128. // Set pointer
  129. *link.mPointer = obj_info.mInstance;
  130. // Increment refcount if it was a referencing pointer
  131. if (link.mRefCountOffset != -1)
  132. ++(*(uint32 *)(((uint8 *)obj_info.mInstance) + link.mRefCountOffset));
  133. // Add referenced object to the list
  134. if (referenced_objects.find(obj_info.mInstance) == referenced_objects.end())
  135. referenced_objects.insert(obj_info.mInstance);
  136. }
  137. else
  138. {
  139. // Referenced object not found, set pointer to nullptr
  140. Trace("ObjectStreamIn: Setting incorrect pointer to class of type %s to nullptr.", link.mRTTI->GetName());
  141. *link.mPointer = nullptr;
  142. }
  143. }
  144. // Release unreferenced objects except the main object
  145. for (IdentifierMap::const_iterator j = mIdentifierMap.begin(); j != mIdentifierMap.end(); ++j)
  146. {
  147. const ObjectInfo &obj_info = j->second;
  148. if (obj_info.mInstance != main_object)
  149. {
  150. ObjectSet::const_iterator k = referenced_objects.find(obj_info.mInstance);
  151. if (k == referenced_objects.end())
  152. {
  153. Trace("ObjectStreamIn: Releasing unreferenced object of type %s.", obj_info.mRTTI->GetName());
  154. obj_info.mRTTI->DestructObject(obj_info.mInstance);
  155. }
  156. }
  157. }
  158. // Call OnLoaded callback
  159. unordered_set<SerializableObject *> visited_set;
  160. OSVisitCompounds(main_object, inRTTI, [&visited_set](const void *inObject, const RTTI *inType)
  161. {
  162. SerializableObject *so = const_cast<SerializableObject *>(reinterpret_cast<const SerializableObject *>(inType->CastTo(inObject, JPH_RTTI(SerializableObject))));
  163. if (so != nullptr && visited_set.insert(so).second)
  164. so->OnLoaded();
  165. });
  166. return main_object;
  167. }
  168. else
  169. {
  170. // Release all objects if a fatal error occurred
  171. for (IdentifierMap::iterator i = mIdentifierMap.begin(); i != mIdentifierMap.end(); ++i)
  172. {
  173. const ObjectInfo &obj_info = i->second;
  174. obj_info.mRTTI->DestructObject(obj_info.mInstance);
  175. }
  176. return nullptr;
  177. }
  178. }
  179. void *ObjectStreamIn::ReadObject(const RTTI *& outRTTI)
  180. {
  181. // Read the object class
  182. void *object = nullptr;
  183. string class_name;
  184. if (ReadName(class_name))
  185. {
  186. // Get class description
  187. ClassDescriptionMap::iterator i = mClassDescriptionMap.find(class_name);
  188. if (i != mClassDescriptionMap.end())
  189. {
  190. const ClassDescription &class_desc = i->second;
  191. // Read object identifier
  192. Identifier identifier;
  193. if (ReadIdentifier(identifier))
  194. {
  195. // Check if this object can be read or must be skipped
  196. if (identifier != sNullIdentifier
  197. && class_desc.mRTTI
  198. && !class_desc.mRTTI->IsAbstract())
  199. {
  200. // Create object instance
  201. outRTTI = class_desc.mRTTI;
  202. object = outRTTI->CreateObject();
  203. // Read object attributes
  204. if (ReadClassData(class_desc, object))
  205. {
  206. // Add object to identifier map
  207. mIdentifierMap.insert(IdentifierMap::value_type(identifier, ObjectInfo(object, outRTTI)));
  208. }
  209. else
  210. {
  211. // Fatal error while reading attributes, release object
  212. outRTTI->DestructObject(object);
  213. object = nullptr;
  214. }
  215. }
  216. else
  217. {
  218. // Skip this object
  219. // TODO: This operation can fail, but there is no check yet
  220. Trace("ObjectStreamIn: Found uncreatable object %s.", class_name.c_str());
  221. ReadClassData(class_desc, nullptr);
  222. }
  223. }
  224. }
  225. else
  226. {
  227. // TODO: This is a fatal error, but this function has no way of indicating this
  228. Trace("ObjectStreamIn: Found object of unknown class %s.", class_name.c_str());
  229. }
  230. }
  231. return object;
  232. }
  233. bool ObjectStreamIn::ReadRTTI()
  234. {
  235. // Read class name and find it's attribute info
  236. string class_name;
  237. if (!ReadName(class_name))
  238. return false;
  239. // Find class
  240. const RTTI *rtti = Factory::sInstance.Find(class_name.c_str());
  241. if (rtti == nullptr)
  242. Trace("ObjectStreamIn: Unknown class: \"%s\".", class_name.c_str());
  243. // Insert class description
  244. mClassDescriptionMap.insert(ClassDescriptionMap::value_type(class_name, ClassDescription(rtti)));
  245. ClassDescription &class_desc = mClassDescriptionMap.find(class_name)->second;
  246. // Read the number of entries in the description
  247. uint32 count;
  248. if (!ReadCount(count))
  249. return false;
  250. // Read the entries
  251. for (uint32 i = 0; i < count; ++i)
  252. {
  253. AttributeDescription attribute;
  254. // Read name
  255. string attribute_name;
  256. if (!ReadName(attribute_name))
  257. return false;
  258. // Read type
  259. if (!ReadDataType(attribute.mDataType))
  260. return false;
  261. // Read array depth
  262. while (attribute.mDataType == EDataType::Array)
  263. {
  264. ++attribute.mArrayDepth;
  265. if (!ReadDataType(attribute.mDataType))
  266. return false;
  267. }
  268. // Read instance/pointer class name
  269. if (attribute.mDataType == EDataType::Instance || attribute.mDataType == EDataType::Pointer)
  270. if (!ReadName(attribute.mClassName))
  271. return false;
  272. // Find attribute in rtti
  273. if (rtti)
  274. {
  275. // Find attribute index
  276. for (int idx = 0; idx < rtti->GetAttributeCount(); ++idx)
  277. {
  278. const SerializableAttribute *attr = DynamicCast<SerializableAttribute, RTTIAttribute>(rtti->GetAttribute(idx));
  279. if (attr != nullptr && strcmp(attr->GetName(), attribute_name.c_str()) == 0)
  280. {
  281. attribute.mIndex = idx;
  282. break;
  283. }
  284. }
  285. // Check if attribute is of expected type
  286. if (attribute.mIndex >= 0)
  287. {
  288. const SerializableAttribute *attr = (const SerializableAttribute *)rtti->GetAttribute(attribute.mIndex);
  289. if (!attr->IsType(attribute.mArrayDepth, attribute.mDataType, attribute.mClassName.c_str()))
  290. attribute.mIndex = -1;
  291. }
  292. }
  293. // Add attribute to the class description
  294. class_desc.mAttributes.push_back(attribute);
  295. }
  296. return true;
  297. }
  298. bool ObjectStreamIn::ReadClassData(const char *inClassName, void *inInstance)
  299. {
  300. // Find the class description
  301. ClassDescriptionMap::iterator i = mClassDescriptionMap.find(inClassName);
  302. if (i != mClassDescriptionMap.end())
  303. return ReadClassData(i->second, inInstance);
  304. return false;
  305. }
  306. bool ObjectStreamIn::ReadClassData(const ClassDescription &inClassDesc, void *inInstance)
  307. {
  308. // Read data for this class
  309. bool continue_reading = true;
  310. for (const AttributeDescription &attr_desc : inClassDesc.mAttributes)
  311. {
  312. // Read or skip the attribute data
  313. if (attr_desc.mIndex >= 0 && inInstance)
  314. {
  315. const SerializableAttribute *attr = (const SerializableAttribute *)inClassDesc.mRTTI->GetAttribute(attr_desc.mIndex);
  316. continue_reading = attr->ReadData(*this, inInstance);
  317. }
  318. else
  319. continue_reading = SkipAttributeData(attr_desc.mArrayDepth, attr_desc.mDataType, attr_desc.mClassName.c_str());
  320. if (!continue_reading)
  321. break;
  322. }
  323. return continue_reading;
  324. }
  325. bool ObjectStreamIn::ReadPointerData(const RTTI *inRTTI, void **inPointer, int inRefCountOffset)
  326. {
  327. Identifier identifier;
  328. if (ReadIdentifier(identifier))
  329. {
  330. if (identifier == sNullIdentifier)
  331. {
  332. // Set nullptr pointer
  333. inPointer = nullptr;
  334. }
  335. else
  336. {
  337. // Put pointer on the list to be resolved later on
  338. mUnresolvedLinks.push_back(Link());
  339. mUnresolvedLinks.back().mPointer = inPointer;
  340. mUnresolvedLinks.back().mRefCountOffset = inRefCountOffset;
  341. mUnresolvedLinks.back().mIdentifier = identifier;
  342. mUnresolvedLinks.back().mRTTI = inRTTI;
  343. }
  344. return true;
  345. }
  346. return false;
  347. }
  348. bool ObjectStreamIn::SkipAttributeData(int inArrayDepth, EDataType inDataType, const char *inClassName)
  349. {
  350. bool continue_reading = true;
  351. // Get number of items to read
  352. uint32 count = 1;
  353. for (; inArrayDepth > 0; --inArrayDepth)
  354. {
  355. uint32 temporary;
  356. if (ReadCount(temporary))
  357. {
  358. // Multiply for multi dimensional arrays
  359. count *= temporary;
  360. }
  361. else
  362. {
  363. // Fatal error while reading array size
  364. continue_reading = false;
  365. break;
  366. }
  367. }
  368. // Read data for all items
  369. if (continue_reading)
  370. {
  371. if (inDataType == EDataType::Instance)
  372. {
  373. // Get the class description
  374. ClassDescriptionMap::iterator i = mClassDescriptionMap.find(inClassName);
  375. if (i != mClassDescriptionMap.end())
  376. {
  377. for (; count > 0 && continue_reading; --count)
  378. continue_reading = ReadClassData(i->second, nullptr);
  379. }
  380. else
  381. {
  382. continue_reading = false;
  383. Trace("ObjectStreamIn: Found instance of unknown class %s.", inClassName);
  384. }
  385. }
  386. else
  387. {
  388. for (; count > 0 && continue_reading; --count)
  389. {
  390. switch (inDataType)
  391. {
  392. case EDataType::Pointer:
  393. {
  394. Identifier temporary;
  395. continue_reading = ReadIdentifier(temporary);
  396. break;
  397. }
  398. case EDataType::T_uint8:
  399. {
  400. uint8 temporary;
  401. continue_reading = ReadPrimitiveData(temporary);
  402. break;
  403. }
  404. case EDataType::T_uint16:
  405. {
  406. uint16 temporary;
  407. continue_reading = ReadPrimitiveData(temporary);
  408. break;
  409. }
  410. case EDataType::T_int:
  411. {
  412. int temporary;
  413. continue_reading = ReadPrimitiveData(temporary);
  414. break;
  415. }
  416. case EDataType::T_uint32:
  417. {
  418. uint32 temporary;
  419. continue_reading = ReadPrimitiveData(temporary);
  420. break;
  421. }
  422. case EDataType::T_uint64:
  423. {
  424. uint64 temporary;
  425. continue_reading = ReadPrimitiveData(temporary);
  426. break;
  427. }
  428. case EDataType::T_float:
  429. {
  430. float temporary;
  431. continue_reading = ReadPrimitiveData(temporary);
  432. break;
  433. }
  434. case EDataType::T_bool:
  435. {
  436. bool temporary;
  437. continue_reading = ReadPrimitiveData(temporary);
  438. break;
  439. }
  440. case EDataType::T_string:
  441. {
  442. string temporary;
  443. continue_reading = ReadPrimitiveData(temporary);
  444. break;
  445. }
  446. case EDataType::T_Float3:
  447. {
  448. Float3 temporary;
  449. continue_reading = ReadPrimitiveData(temporary);
  450. break;
  451. }
  452. case EDataType::T_Vec3:
  453. {
  454. Vec3 temporary;
  455. continue_reading = ReadPrimitiveData(temporary);
  456. break;
  457. }
  458. case EDataType::T_Vec4:
  459. {
  460. Vec4 temporary;
  461. continue_reading = ReadPrimitiveData(temporary);
  462. break;
  463. }
  464. case EDataType::T_Quat:
  465. {
  466. Quat temporary;
  467. continue_reading = ReadPrimitiveData(temporary);
  468. break;
  469. }
  470. case EDataType::T_Mat44:
  471. {
  472. Mat44 temporary;
  473. continue_reading = ReadPrimitiveData(temporary);
  474. break;
  475. }
  476. case EDataType::Array:
  477. case EDataType::Object:
  478. case EDataType::Declare:
  479. case EDataType::Instance:
  480. case EDataType::Invalid:
  481. default:
  482. continue_reading = false;
  483. break;
  484. }
  485. }
  486. }
  487. }
  488. return continue_reading;
  489. }
  490. // Define macro to declare functions for a specific primitive type
  491. #define JPH_DECLARE_PRIMITIVE(name) \
  492. bool OSReadData(ObjectStreamIn &ioStream, name &outPrimitive) \
  493. { \
  494. return ioStream.ReadPrimitiveData(outPrimitive); \
  495. }
  496. // This file uses the JPH_DECLARE_PRIMITIVE macro to define all types
  497. #include <Jolt/ObjectStream/ObjectStreamTypes.h>
  498. } // JPH