GameObject * Factory::BuildJsonComposition(const char *file) { // Open the Json file and read in the components: Json::Value components = GetJsonRoot(file)["Components"]; ErrorIf(!components, "Failed to open file %s.", file); std::vector<std::string> componentList = components.getMemberNames(); GameObject *gameObject = new GameObject(); // Add each of the components to the new object: for (unsigned i = 0; i < components.size(); ++i) { // 1. Check if the component is registered and has a creator // in the component map: ComponentCreatorMap::iterator it = componentCreatorMap_.find(componentList.at(i)); ErrorIf(it == componentCreatorMap_.end(), "Failed to create unregistered component %s", componentList.at(i)); // 2. Create a new component once the creator is found in the // map: ComponentCreator *creator = it->second; Component *component = creator->Create(); // 3. Serialize the component using the Json value in the file: component->Deserialize(components[componentList.at(i)]); // 4. Add the component to the composition: gameObject->AddComponent(creator->TypeId, component); } IdGameObject(gameObject); return gameObject; }
// Called by the engine when the entity is spawned due to scene segment creation. Result Entity::Deserialize(Common::InputStream* pStream, const Vector& offset) { if (!pStream) return Result::CorruptedPointer; EntityDesc desc; size_t bytesRead = pStream->Read(sizeof(desc), &desc); if (bytesRead != sizeof(desc)) { if (bytesRead > 0) { LOG_ERROR("Could not deserialize entity."); return Result::Error; //failed to read entity descriptor } else { // End of Stream. This sould be checked outside to aviod pointless Entity object creation. return Result::Error; } } // decode rotation matrix mLocalMatrix = MatrixFromQuaternion(Vector(desc.quat)); // decode position mLocalMatrix.r[3] = Vector(desc.pos) + offset; mLocalMatrix.m[3][3] = 1.0f; UpdateGlobalMatrix(); // deserialize components for (uint16 i = 0; i < desc.compNum; i++) { char compType = 0; if (pStream->Read(sizeof(compType), &compType) != sizeof(compType)) { DebugBreak(); LOG_ERROR("Entity deserialization failed: invalid component type. Data could be corrupted."); return Result::Error; //failed to component type } Component* pComponent = nullptr; switch ((ComponentType)compType) { case ComponentType::Mesh: pComponent = new MeshComponent(this); break; case ComponentType::Light: pComponent = new LightComponent(this); break; case ComponentType::Physics: pComponent = new BodyComponent(this); break; case ComponentType::Camera: pComponent = new Camera(this); break; } if (pComponent == nullptr) { LOG_ERROR("Entity deserialization failed: allocation error."); return Result::AllocationError; //invalid component type } pComponent->Deserialize(pStream); } // deserialize children for (uint16 i = 0; i < desc.childrenNum; i++) { Entity* pChild = nullptr; if (mScene->DeserializeEntity(pStream, Vector(), &pChild) != Result::OK) { return Result::Error; } Attach(pChild); } return Result::OK; }