public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { this.light = parentNode.GetGameObject().AddComponent <Light>(); ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] bytes = resource.GetResourceData(); int count = (bytes.Length / 4); float[] data = new float[count]; for (int i = 0; i < count; i++) { data[i] = BitConverter.ToSingle(bytes, (i * 4)); } light.color = new Color(data[0], data[1], data[2], data[3]); light.type = (LightType)Enum.ToObject(typeof(LightType), (int)data[4]); light.intensity = data[5]; this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { //Deserialize pointed node id. ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); UInt32 pointedNodeID = BitConverter.ToUInt32(resource.GetResourceData(), 0); UnityNodeBase currentParent = parentNode; while (currentParent.ParentNode != null) { currentParent = currentParent.ParentNode; } UnityNodeBase referencedNode = FindNodeWithID(currentParent, pointedNodeID); if (referencedNode is UnityMaterialNode) { UnityMaterialNode materialNode = referencedNode as UnityMaterialNode; Material mat = materialNode.GetMaterial(); ResourceResponse request = resourceResponse.CanHandle(pointedNodeID); if (request != null) { request.HandleMaterialResponse(mat); } } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { this.camera = parentNode.GetGameObject().AddComponent <Camera>(); ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] bytes = resource.GetResourceData(); int count = (bytes.Length / 4); float[] data = new float[count]; for (int i = 0; i < count; i++) { data[i] = BitConverter.ToSingle(bytes, (i * 4)); } camera.backgroundColor = new Color(data[0], data[1], data[2], data[3]); camera.fieldOfView = data[4]; camera.aspect = data[5]; this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] metaDataBuffer = resource.GetMetaData(); SerializedFieldData fieldData = ProtocolBufferSerializer.DeserializeFieldData(metaDataBuffer); string assemblyName = ProtocolBufferSerializer.GetAssemblyName(fieldData.assemblyType); string scriptTypeName = fieldData.typeName; string fieldName = fieldData.fieldName; Type scriptType = null; //Qualify type check with assembly name, GetType only looks in current assembly otherwise. if (!string.IsNullOrEmpty(assemblyName)) { scriptType = Type.GetType(scriptTypeName + ", " + assemblyName); } else { scriptType = Type.GetType(scriptTypeName); } if (scriptType != null) { Gradient gradient = new Gradient(); PropertySetter colorKeySetter = new PropertySetter("colorKeys", (System.Object val) => { gradient.colorKeys = val as GradientColorKey[]; }); PropertySetter alphaKeySetter = new PropertySetter("alphaKeys", (System.Object val) => { gradient.alphaKeys = val as GradientAlphaKey[]; }); List <PropertySetter> customValueSetters = new List <PropertySetter>(); customValueSetters.Add(colorKeySetter); customValueSetters.Add(alphaKeySetter); FieldDeserializer fieldDeserializer = new FieldDeserializer(customValueSetters, gradient); ResourceResponse response = new ResourceResponse(); response.SetFieldDeserializer(fieldDeserializer); for (int i = 0; i < this.ChildNodes.Count; i++) { UnityNodeBase child = this.ChildNodes[i]; child.Deserialize(dataBlocks, this, response, postInstallActions, optimizedLoad); } if (resourceResponse != null) { resourceResponse.GetFieldDeserializer.SetField(fieldName, gradient); } } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { this.animator = parentNode.GetGameObject().AddComponent <UnityEngine.Animator>(); ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] metaDataBuffer = resource.GetMetaData(); JObject metaData = JObject.Parse(System.Text.Encoding.UTF8.GetString(metaDataBuffer)); this.animator.applyRootMotion = metaData["applyRootMotion"].ToObject <bool>(); UInt32 avatarID = metaData.Value <UInt32>("avatarReferenceID"); for (int i = 0; i < this.ChildNodes.Count; i++) { UnityNodeBase child = this.ChildNodes[i]; ResourceResponse avatarResponse = new ResourceResponse(avatarID, (ResourceResponse response) => { this.animator.avatar = response.GetAvatarRequest; }); child.Deserialize(dataBlocks, this, avatarResponse, postInstallActions, optimizedLoad); } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); if (resource != null) { byte[] metaDataBuffer = resource.GetMetaData(); SerializedCollectionData collectionData = ProtocolBufferSerializer.DeserializeCollectionData(metaDataBuffer); string assemblyName = ProtocolBufferSerializer.GetAssemblyName(collectionData.assemblyType); string scriptTypeName = collectionData.typeName; string fieldName = collectionData.fieldName; int itemCount = collectionData.count; Type scriptType = null; //Qualify type check with assembly name, GetType only looks in current assembly otherwise. if (!string.IsNullOrEmpty(assemblyName)) { scriptType = Type.GetType(scriptTypeName + ", " + assemblyName); } else { scriptType = Type.GetType(scriptTypeName); } if (scriptType != null) { Array array = Array.CreateInstance(scriptType, itemCount); if (array != null) { FieldDeserializer arrayDeserializer = new FieldDeserializer(array); ResourceResponse response = new ResourceResponse(); response.SetFieldDeserializer(arrayDeserializer); foreach (UnityNodeBase node in this.ChildNodes) { node.Deserialize(dataBlocks, this, response, postInstallActions, optimizedLoad); arrayDeserializer.IncrementIndex(); } } if (resourceResponse != null) { resourceResponse.GetFieldDeserializer.SetField(fieldName, array); } } } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] bytes = resource.GetResourceData(); int vectorCount = (bytes.Length / 12); Vector3[] vectors = new Vector3[vectorCount]; for (int i = 0; i < vectorCount; i++) { vectors[i] = new Vector3( BitConverter.ToSingle(bytes, (i * 12)), BitConverter.ToSingle(bytes, (i * 12) + 4), BitConverter.ToSingle(bytes, (i * 12) + 8) ); } GameObject parentGO = parentNode.GetGameObject(); //Gameobject creates a transform itself when its created, we only need to get the component. if (parentGO != null) { this.transform = parentGO.GetComponent <Transform>(); } if (this.transform != null) { //Get the node above the parentNode and parent to it. Transform parentTransform = parentNode.ParentNode.GetTransform(); //Parent this transform to the object above it, if one exists. if (parentTransform != null) { this.transform.SetParent(parentTransform); } //Set the attributes after we have parented the transform. this.transform.localPosition = vectors[0]; this.transform.localRotation = Quaternion.Euler(vectors[1]); this.transform.localScale = vectors[2]; } this.isDeserialized = true; } }
public void AddResource(uint refID, PCFResourceType resourceType, AssetResource resource) { if (this.dataBlocks.ContainsKey(resourceType)) { ResourceBlock dataBlock = this.dataBlocks[resourceType] as ResourceBlock; dataBlock.AddResource(refID, resource); } else { ResourceBlock block = new ResourceBlock(resourceType); block.AddResource(refID, resource); this.dataBlocks.Add(resourceType, block); } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { GameObject parentGameObject = parentNode.GetGameObject(); this.meshFilter = parentGameObject.AddComponent <MeshFilter>(); this.meshRenderer = parentGameObject.AddComponent <MeshRenderer>(); ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] metaDataBuffer = resource.GetMetaData(); JObject metaData = JObject.Parse(System.Text.Encoding.UTF8.GetString(metaDataBuffer)); UInt32 materialID = metaData.Value <UInt32>("materialID"); this.mesh = MeshSerializeUtilities.ReadMesh(resource.GetResourceData(), false); this.meshFilter.sharedMesh = this.mesh; if (optimizedLoad) { //Free up cached ram memory for this mesh, disables access to mesh components like verts etc. this.mesh.UploadMeshData(true); } for (int i = 0; i < this.ChildNodes.Count; i++) { UnityNodeBase child = this.ChildNodes[i]; //Create a request to be send down the chain of children, see if any child will handle it. ResourceResponse materialRequest = new ResourceResponse(materialID, (ResourceResponse response) => { meshRenderer.material = response.GetMaterialRequest; }); child.Deserialize(dataBlocks, this, materialRequest, postInstallActions, optimizedLoad); } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] metaDataBuffer = resource.GetMetaData(); JObject metaData = JObject.Parse(System.Text.Encoding.UTF8.GetString(metaDataBuffer)); string scriptName = metaData["scriptname"].ToString(); Type scriptType = null; if (scriptMask == null) { scriptType = Type.GetType(scriptName); } else if (this.scriptMask != null && this.scriptMask.Contains(scriptName)) { scriptType = Type.GetType(scriptName); } if (scriptType != null) { this.script = parentNode.GetGameObject().AddComponent(scriptType) as MonoBehaviour; FieldDeserializer fieldDeserializer = new FieldDeserializer(scriptType.GetFields(), this.script); ResourceResponse response = new ResourceResponse(); response.SetFieldDeserializer(fieldDeserializer); foreach (UnityNodeBase node in this.ChildNodes) { node.Deserialize(dataBlocks, this, response, postInstallActions, optimizedLoad); } } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); string jsonString = System.Text.Encoding.UTF8.GetString(resource.GetMetaData()); JObject jsonObject = JObject.Parse(jsonString); animationClip = new AnimationClip(); animationClip.name = jsonObject.Value <string>("name"); animationClip.frameRate = jsonObject.Value <float>("frameRate"); animationClip.wrapMode = (UnityEngine.WrapMode)jsonObject.Value <int>("wrapMode"); animationClip.legacy = true; SerializedAnimationClip serializedAnimationClip = ProtocolBufferSerializer.DeserializeAnimationClipData(resource.GetResourceData()); foreach (int key in serializedAnimationClip.AnimationChannels.Keys) { SerializedAnimationChannelName channel = (SerializedAnimationChannelName)key; SerializedAnimationKeyFrame[] keyFrames = serializedAnimationClip.GetChannel(channel); AnimationCurve curve = CreateAnimationCurve(serializedAnimationClip.PostWrapMode, serializedAnimationClip.PreWrapMode, keyFrames); animationClip.SetCurve("", typeof(Transform), AnimationClipUtils.GetAnimationClipChannelName(channel), curve); } string fieldName = jsonObject.Value <string>("fieldName"); if (resourceResponse != null) { resourceResponse.GetFieldDeserializer.SetField(fieldName, animationClip); } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[this.resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); ResourceResponse request = resourceResponse.CanHandle(GetReferenceID()); if (request != null) { byte[] bundleBytes = resource.GetResourceData(); this.internalBundle = AssetBundle.LoadFromMemory(bundleBytes); request.HandleAssetBundleResponse(this.internalBundle); } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { //Deserialize pointed node id. ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] bytes = resource.GetResourceData(); UInt32 referencedNodeID = BitConverter.ToUInt32(bytes, 0); //JObject metaData = JObject.Parse(System.Text.Encoding.UTF8.GetString(metaDataBuffer)); //UInt32 referencedNodeID = metaData.Value<UInt32>("targetReferenceID"); Dictionary <UInt32, UnityNodeBase> referencedNodes = resourceResponse.GetReferencedNodes; if (referencedNodes.ContainsKey(referencedNodeID)) { UnityNodeBase referencedNode = referencedNodes[referencedNodeID]; Transform transform = referencedNode.GetTransform(); if (transform != null) { resourceResponse.GetFieldDeserializer.SetArrayItem(transform); } } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); UInt32 pointedNodeID = BitConverter.ToUInt32(resource.GetResourceData(), 0); postInstallActions.Add((UnityNodeBase rootNode) => { UnityNodeBase referencedNode = FindNodeWithID(rootNode, pointedNodeID); if (referencedNode is UnityAnimationClipNode) { UnityAnimationClipNode animationClip = referencedNode as UnityAnimationClipNode; AnimationClip animation = animationClip.GetAnimationClip(); string jsonString = System.Text.Encoding.UTF8.GetString(resource.GetMetaData()); JObject jsonObject = JObject.Parse(jsonString); string fieldName = jsonObject.Value <string>("fieldName"); if (resourceResponse != null) { resourceResponse.GetFieldDeserializer.SetField(fieldName, animation); } } }); this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[this.resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); byte[] metaDataBuffer = resource.GetMetaData(); SerializedMaterial serializedMaterial = ProtocolBufferSerializer.DeserializeMaterialData(metaDataBuffer); string shaderName = serializedMaterial.ShaderName; this.material = new UnityEngine.Material(Shader.Find(shaderName)); this.material.name = serializedMaterial.DisplayName; ResourceResponse previousRequest = null; if (serializedMaterial.MaterialProperties != null) { foreach (KeyValuePair <string, SerializedMaterialProperty> pair in serializedMaterial.MaterialProperties) { if (pair.Value != null) { MaterialPropertyType propertyType = (MaterialPropertyType)pair.Value.PropertyType; if (propertyType == MaterialPropertyType.FloatType) { SerializedMaterialFloatProperty floatProperty = pair.Value as SerializedMaterialFloatProperty; this.material.SetFloat(pair.Key, floatProperty.Val); } else if (propertyType == MaterialPropertyType.VectorType) { SerializedMaterialVectorProperty vectorProperty = pair.Value as SerializedMaterialVectorProperty; Vector4 vector = new Vector4(vectorProperty.X, vectorProperty.Y, vectorProperty.Z, vectorProperty.W); this.material.SetVector(pair.Key, vector); } else if (propertyType == MaterialPropertyType.ColorType) { SerializedMaterialColorProperty colorProperty = pair.Value as SerializedMaterialColorProperty; Color color = new Color(colorProperty.R, colorProperty.G, colorProperty.B, colorProperty.A); this.material.SetColor(pair.Key, color); } else if (propertyType == MaterialPropertyType.TextureType) { SerializedMaterialTextureProperty textureProperty = pair.Value as SerializedMaterialTextureProperty; string propertyName = pair.Key; ResourceResponse textureRequest = new ResourceResponse(textureProperty.ReferenceID, (ResourceResponse response) => { material.SetTexture(propertyName, response.GetTextureRequest); }); if (previousRequest != null) { textureRequest.SetPreviousResponse(previousRequest); previousRequest.SetNextResponse(textureRequest); } previousRequest = textureRequest; } } } } if (previousRequest != null) { //Get the first request created. ResourceResponse firstRequest = previousRequest; while (true) { ResourceResponse previous = firstRequest.GetPreviousResponse(); if (previous == null) { break; } firstRequest = previous; } //Have each request set by one of the child nodes. for (int i = 0; i < this.ChildNodes.Count; i++) { UnityNodeBase child = this.ChildNodes[i]; child.Deserialize(dataBlocks, parentNode, firstRequest, postInstallActions, optimizedLoad); } } //Finish up and set material to whatever field/object that owns this node. ResourceResponse request = resourceResponse.CanHandle(GetReferenceID()); if (request != null) { request.HandleMaterialResponse(this.material); } watch.Stop(); //Debug.Log("Time to deserialize material: " + watch.ElapsedMilliseconds); this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[this.resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); if (resource == null) { ResourceResponse textureLookUp = resourceResponse.CanHandle(GetReferenceID()); if (textureLookUp != null) { textureLookUp.HandleTextureResponse(null); } return; } byte[] textureBytes = resource.GetResourceData(); byte[] metaDataBuffer = resource.GetMetaData(); JObject metaData = JObject.Parse(System.Text.Encoding.UTF8.GetString(metaDataBuffer)); int width = metaData.Value <int>("width"); int height = metaData.Value <int>("height"); TextureDataFormat textureFormat = (TextureDataFormat)metaData.Value <int>("textureFormat"); string fieldName = metaData.Value <string>("fieldName"); if (textureFormat == TextureDataFormat.PVRTC4BPP) { #if MEASURE_PERFORMANCE System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); #endif #if UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR int dataSize = 0; IntPtr dataPointer = PVRTCEncoderWrapper.DecompressData(textureBytes, width, height, false, ref dataSize); if (dataPointer != IntPtr.Zero) { this.texture = new Texture2D(width, height, TextureFormat.RGBA32, false); this.texture.LoadRawTextureData(dataPointer, dataSize); this.texture.Apply(false, true); //TODO: Probably better to use IDisposable here.... PVRTCEncoderWrapper.FreeCompressedDataPointer(dataPointer); } #else this.texture = new Texture2D(width, height, TextureFormat.PVRTC_RGBA4, false); this.texture.LoadRawTextureData(textureBytes); this.texture.Apply(false, true); #endif #if MEASURE_PERFORMANCE watch.Stop(); Debug.Log("Time to deserialize texture: " + watch.ElapsedMilliseconds); #endif } else if (textureFormat == TextureDataFormat.ASTC6X6) { #if MEASURE_PERFORMANCE System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); #endif this.texture = new Texture2D(width, height, TextureFormat.ASTC_RGBA_6x6, false); this.texture.LoadRawTextureData(textureBytes); this.texture.Apply(false, true); #if MEASURE_PERFORMANCE watch.Stop(); Debug.Log("Time to deserialize texture: " + watch.ElapsedMilliseconds); #endif } else if (textureFormat == TextureDataFormat.RGB32) { this.texture = new Texture2D(width, height, TextureFormat.RGBA32, false); this.texture.LoadRawTextureData(textureBytes); if (optimizedLoad) { this.texture.Apply(false, true); } else { this.texture.Apply(false); } } if (fieldName == null) { ResourceResponse request = resourceResponse.CanHandle(GetReferenceID()); if (request != null) { request.HandleTextureResponse(texture); } } else { if (resourceResponse != null) { resourceResponse.GetFieldDeserializer.SetField(fieldName, this.texture); } } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { GameObject parentGameObject = parentNode.GetGameObject(); this.skinnedMesh = parentGameObject.AddComponent <SkinnedMeshRenderer>(); ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] metaDataBuffer = resource.GetMetaData(); JObject metaData = JObject.Parse(System.Text.Encoding.UTF8.GetString(metaDataBuffer)); UInt32 materialID = metaData.Value <UInt32>("materialID"); string rootBoneName = metaData.Value <string>("rootBone"); string probeBoneName = metaData.Value <string>("probeAnchor"); int quality = metaData.Value <int>("quality"); string[] boneNames = metaData.Value <JArray>("bones").ToObject <string[]>(); float[] blendShapeWeights = metaData.Value <JArray>("blendShapeWeights").ToObject <float[]>(); // Add a post install action so the bones will have time to be created. postInstallActions.Add((UnityNodeBase node) => { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); Transform[] bones = new Transform[boneNames.Length]; //Mapp all bone transform in the hierarchy. Dictionary <string, Transform> bonesMapping = new Dictionary <string, Transform>(); FindTransformsInHierarchy(node, bonesMapping); for (int i = 0; i < boneNames.Length; i++) { string name = boneNames[i]; if (bonesMapping.ContainsKey(name)) { bones[i] = bonesMapping[name]; } else { bones[i] = null; } } this.mesh = MeshSerializeUtilities.ReadMesh(resource.GetResourceData(), true); if (optimizedLoad) { //Free up mono memory for this mesh, now owned by the GPU. this.mesh.UploadMeshData(true); } this.skinnedMesh.sharedMesh = this.mesh; this.skinnedMesh.bones = bones; this.skinnedMesh.quality = (SkinQuality)Enum.ToObject(typeof(SkinQuality), quality); for (int i = 0; i < blendShapeWeights.Length; i++) { this.skinnedMesh.SetBlendShapeWeight(i, blendShapeWeights[i]); } if (bonesMapping.ContainsKey(rootBoneName)) { this.skinnedMesh.rootBone = bonesMapping[rootBoneName]; } if (probeBoneName != null) { this.skinnedMesh.probeAnchor = bonesMapping[probeBoneName]; } watch.Stop(); //Debug.Log("time to deserialize skinned mesh: " + watch.ElapsedMilliseconds); }); for (int i = 0; i < this.ChildNodes.Count; i++) { UnityNodeBase child = this.ChildNodes[i]; //Create a request to be send down the chain of children, see if any child will handle it. ResourceResponse materialRequest = new ResourceResponse(materialID, (ResourceResponse response) => { skinnedMesh.material = response.GetMaterialRequest; }); child.Deserialize(dataBlocks, this, materialRequest, postInstallActions, optimizedLoad); } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] metaDataBuffer = resource.GetMetaData(); SerializedFieldData fieldData = ProtocolBufferSerializer.DeserializeFieldData(metaDataBuffer); if (fieldData != null) { byte[] data = resource.GetResourceData(); System.Object obj = null; if (data != null) { if (fieldData.type == 1) { obj = System.Text.Encoding.UTF8.GetString(data); } else if (fieldData.type == 2) { obj = BitConverter.ToInt32(data, 0); } else if (fieldData.type == 3) { obj = BitConverter.ToUInt32(data, 0); } else if (fieldData.type == 4) { obj = BitConverter.ToSingle(data, 0); } else if (fieldData.type == 5) { obj = BitConverter.ToDouble(data, 0); } else if (fieldData.type == 6) { obj = BitConverter.ToBoolean(data, 0); } else if (fieldData.type == 7) { obj = data; } if (resourceResponse != null) { if (fieldData.arrayItem) { resourceResponse.GetFieldDeserializer.SetArrayItem(obj); } else { resourceResponse.GetFieldDeserializer.SetField(fieldData.fieldName, obj); } } } } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] metaDataBuffer = resource.GetMetaData(); JObject metaData = JObject.Parse(System.Text.Encoding.UTF8.GetString(metaDataBuffer)); string avatarName = metaData.Value <string>("avatarName"); this.sharedAvatar = bool.Parse(metaData.Value <string>("sharedAvatar")); string rootBone = metaData.Value <string>("rootBone"); JArray mappedBones = metaData.Value <JArray>("mappedBones"); if (!sharedAvatar) { //Run after hierarchy is created since we need it when creating a avatar. postInstallActions.Add((UnityNodeBase rootNode) => { UnityNodeBase skeletonRootNode = FindNodeWithName(rootNode, rootBone); if (skeletonRootNode != null) { //recreate avatar from meta data. List <SkeletonBone> skeletonBones = new List <SkeletonBone>(mappedBones.Count); List <HumanBone> humanBones = new List <HumanBone>(mappedBones.Count); int humanBoneCount = 0; int skeletonBoneCount = 0; foreach (JObject bone in mappedBones) { JObject humanBoneData = bone.Value <JObject>("humanBone"); if (humanBoneData != null) { HumanBone humanBone = new HumanBone(); humanBone.humanName = humanBoneData.Value <string>("humanName"); humanBone.boneName = humanBoneData.Value <string>("boneName"); humanBone.limit.useDefaultValues = bool.Parse(humanBoneData.Value <string>("useDefaultValues")); humanBones.Add(humanBone); } JObject skeletonBoneData = bone.Value <JObject>("skeletonBone"); SkeletonBone skeletonBone = new SkeletonBone(); skeletonBone.name = skeletonBoneData.Value <string>("name"); float[] posArray = skeletonBoneData.Value <JArray>("position").ToObject <float[]>(); skeletonBone.position = new Vector3(posArray[0], posArray[1], posArray[2]); float[] rotArray = skeletonBoneData.Value <JArray>("rotation").ToObject <float[]>(); skeletonBone.rotation = new Quaternion(rotArray[0], rotArray[1], rotArray[2], rotArray[3]); float[] scaleArray = skeletonBoneData.Value <JArray>("scale").ToObject <float[]>(); skeletonBone.scale = new Vector3(scaleArray[0], scaleArray[1], scaleArray[2]); skeletonBones.Add(skeletonBone); } HumanDescription desc = new HumanDescription(); desc.human = humanBones.ToArray(); desc.skeleton = skeletonBones.ToArray(); //set the default values for the rest of the human descriptor parameters desc.upperArmTwist = 0.5f; desc.lowerArmTwist = 0.5f; desc.upperLegTwist = 0.5f; desc.lowerLegTwist = 0.5f; desc.armStretch = 0.05f; desc.legStretch = 0.05f; desc.feetSpacing = 0.0f; this.avatar = AvatarBuilder.BuildHumanAvatar(skeletonRootNode.GetGameObject(), desc); this.avatar.name = avatarName; ResourceResponse request = resourceResponse.CanHandle(GetReferenceID()); if (request != null) { request.HandleAvatarResponse(this.avatar); } } else { Debug.LogError("Unable to find rootnode for avatar: " + avatarName); } }); } else { //Load avatar from resources by name. string avatarResourcePath = Path.Combine("Avatars", avatarName); this.avatar = Resources.Load(avatarResourcePath) as Avatar; ResourceResponse request = resourceResponse.CanHandle(GetReferenceID()); if (request != null) { request.HandleAvatarResponse(this.avatar); } } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); /* * byte[] serializedProbes = resource.GetResourceData(); * * //30 floats in each array element. * int sizeOfArray = numberOfProbes * 30; * float[] lightProbeData = new float[sizeOfArray]; * * for (int i = 0; i < sizeOfArray; i++) * { * lightProbeData[i] = BitConverter.ToSingle(serializedProbes, i * sizeof(float)); * } * * Vector3[] probePositions = new Vector3[numberOfProbes]; * SphericalHarmonicsL2[] bakedProbes = new SphericalHarmonicsL2[numberOfProbes]; * * int stride = 0; * for (int i = 0; i < numberOfProbes; i++) * { * probePositions[i] = new Vector3(lightProbeData[stride], lightProbeData[stride + 1], lightProbeData[stride + 2]); * stride += 3; * * SphericalHarmonicsL2 probe = new SphericalHarmonicsL2(); * for (int k = 0; k < 27; k++) * { * probe[0, k] = lightProbeData[stride + k]; * } * bakedProbes[i] = probe; * * stride += 27; * } */ byte[] metaDataBuffer = resource.GetMetaData(); JObject metaData = JObject.Parse(System.Text.Encoding.UTF8.GetString(metaDataBuffer)); int numberOfProbes = metaData.Value <int>("numberOfProbes"); JArray bundleReferences = metaData.Value <JArray>("bundleReferences"); UInt32 mappedNodeID = 0; //Load the correct bundle depending on what platform we are running. if (mapping.ContainsKey(Application.platform)) { string mappedPlatform = mapping[Application.platform]; foreach (JObject item in bundleReferences) { string platform = item.Value <string>("platform"); if (string.CompareOrdinal(mappedPlatform, platform) == 0) { mappedNodeID = item.Value <UInt32>("referenceID"); } } } if (mappedNodeID != 0) { //Create a request to be send down the chain of children, see if any child will handle it. ResourceResponse lightprobeResponse = new ResourceResponse(mappedNodeID, (ResourceResponse response) => { AssetBundle internalBundle = response.GetAssetBundleRequest; if (internalBundle != null) { UnityEngine.Object[] objects = internalBundle.LoadAllAssets <UnityEngine.Object>(); foreach (UnityEngine.Object obj in objects) { if (obj is LightProbes) { this.lightProbes = obj as LightProbes; break; } } if (this.lightProbes == null) { Debug.LogError("Unable to find lightprobe data!"); } } }); for (int i = 0; i < this.ChildNodes.Count; i++) { UnityNodeBase child = this.ChildNodes[i]; child.Deserialize(dataBlocks, this, lightprobeResponse, postInstallActions, optimizedLoad); } } this.isDeserialized = true; } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); if (resource != null) { this.resourceResponse = resourceResponse; byte[] metaDataBuffer = resource.GetMetaData(); JObject metaData = JObject.Parse(System.Text.Encoding.UTF8.GetString(metaDataBuffer)); this.fieldName = metaData.Value <string>("fieldName"); this.audioPlayerName = metaData.Value <string>("name"); this.arrayItem = bool.Parse(metaData.Value <string>("arrayItem")); this.samplesLength = metaData.Value <int>("samples"); //Lets us know if this audioclip should be streamed directly from the main pcf file. this.streamed = bool.Parse(metaData.Value <string>("streamed")); if (resource.IsStreamed()) { UnityNodeBase current = parentNode; while (current.ParentNode != null) { current = current.ParentNode; } IFileHandle filePath = null; if (current is UnityRootNode) { UnityRootNode rootNode = current as UnityRootNode; filePath = rootNode.GetFile(); } if (filePath != null & filePath.Exists) { int streamPosition = (int)resource.GetStreamPosition(); int streamLength = (int)resource.GetStreamLength(); //Copy ogg file to temporary cache path for use. this.cachePath = Application.temporaryCachePath + "/" + this.referenceID + ".ogg"; if (File.Exists(this.cachePath)) { File.Delete(this.cachePath); } Stream streamedFile = filePath.GetFileStream(FileMode.Open); FileStream oggOutput = new FileStream(this.cachePath, FileMode.Create, FileAccess.Write); streamedFile.Seek(streamPosition, SeekOrigin.Begin); int bytesLeft = streamLength; int bytesWritten = 0; while (bytesLeft > 0) { int bytesRead = streamedFile.Read(COPY_BUFFER, 0, Math.Min(bytesLeft, COPY_BUFFER.Length)); int bytesToWrite = COPY_BUFFER.Length; //Should happen for the last buffer we write. if (bytesLeft < COPY_BUFFER.Length) { bytesToWrite = bytesLeft; } oggOutput.Write(COPY_BUFFER, 0, bytesToWrite); bytesWritten += bytesToWrite; bytesLeft -= bytesRead; } oggOutput.Dispose(); oggOutput.Close(); streamedFile.Close(); if (bytesWritten != streamLength) { Debug.LogError("Missmatch in ogg cache file!"); } if (streamed) { this.audioPlayer = new StreamedAudioPlayer(this.referenceID, this.audioPlayerName, this.cachePath, this.samplesLength); } else { this.audioPlayer = new BufferedAudioPlayer(this.referenceID, this.audioPlayerName, this.cachePath, this.samplesLength); } } } if (resourceResponse != null && this.audioPlayer != null) { if (arrayItem) { this.index = resourceResponse.GetFieldDeserializer.SetArrayItem(this.audioPlayer.GetAudioClip()); } else { resourceResponse.GetFieldDeserializer.SetField(fieldName, this.audioPlayer.GetAudioClip()); } } } this.isDeserialized = true; } }
void LoadDataFromDisk(PCFResourceType loadFlags, bool streamResources, bool assemblyMode) { Stream file = this.path.GetFileStream(FileMode.Open); //Load header first. this.fileHeader = LoadHeader(file); int bytesRead = HeaderByteLength; int fileLength = (int)file.Length; while (bytesRead < fileLength) { int chunkLength = GetNextSegmentLength(file); PCFBlockTypes blockType = GetNextBlockType(file); DataBlockBase block = null; PCFResourceType resourceType = PCFResourceType.NONE; if (blockType == PCFBlockTypes.INDEXBLOCK) { block = new IndexBlock(); this.blockData.Add(PCFResourceType.INDEX, block); } else if (blockType == PCFBlockTypes.NODEBLOCK) { block = new NodeBlock(loadFlags); this.blockData.Add(PCFResourceType.NODE, block); } else if (blockType == PCFBlockTypes.RESOURCEBLOCK) { //Read 4 bytes to determine resourcetype. file.Read(INT_BUFFER, 0, ChunkByteLength); int rawResourceTypeValue = BitConverter.ToInt32(INT_BUFFER, 0); resourceType = (PCFResourceType)Enum.ToObject(typeof(PCFResourceType), rawResourceTypeValue); //Allows us to mask what blocks to read in from file. if ((resourceType & loadFlags) != 0) { block = new ResourceBlock(resourceType, streamResources); this.blockData.Add(resourceType, block); } } else { Debug.LogError("Unknown block type"); } //Increment file position, make sure to count the chunk size bytes. bytesRead += chunkLength + ChunkByteLength; if (block != null) { if (memStream) { int bytsOffset = ChunkByteLength; if (blockType == PCFBlockTypes.RESOURCEBLOCK) { bytsOffset += ChunkByteLength; } long fileStreamPos = file.Position; byte[] streamBytes = new byte[chunkLength - bytsOffset]; file.Read(streamBytes, 0, chunkLength - bytsOffset); Stream stream = new MemoryStream(streamBytes); block.SetBytes(stream, chunkLength, fileStreamPos, assemblyMode); } else { //Will internally read from file and increment its position. block.SetBytes(file, chunkLength, 0, assemblyMode); } } else { //Manually seek to next chunk incase SetBytes was never called. file.Seek(bytesRead, SeekOrigin.Begin); } } if (file != null) { //Stop reading pcf file. file.Close(); } }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { if (!this.isDeserialized) { ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); if (resource != null) { byte[] metaDataBuffer = resource.GetMetaData(); SerializedFieldData fieldData = ProtocolBufferSerializer.DeserializeFieldData(metaDataBuffer); string assemblyName = ProtocolBufferSerializer.GetAssemblyName(fieldData.assemblyType); if (assemblyName != null) { Type scriptType = null; //Qualify type check with assembly name, GetType only looks in current assembly otherwise. if (!string.IsNullOrEmpty(assemblyName)) { scriptType = Type.GetType(fieldData.typeName + ", " + assemblyName); } else { scriptType = Type.GetType(fieldData.typeName); } if (scriptType != null) { System.Object objectInstance = Activator.CreateInstance(scriptType); FieldDeserializer fieldDeserializer = new FieldDeserializer(scriptType.GetFields(), objectInstance); ResourceResponse response = new ResourceResponse(); response.SetFieldDeserializer(fieldDeserializer); foreach (UnityNodeBase node in this.ChildNodes) { node.Deserialize(dataBlocks, this, response, postInstallActions, optimizedLoad); } //if fieldname is empty its an array item. if (resourceResponse != null) { if (fieldData.arrayItem) { resourceResponse.GetFieldDeserializer.SetArrayItem(objectInstance); } else { resourceResponse.GetFieldDeserializer.SetField(fieldData.fieldName, objectInstance); } } } } } this.isDeserialized = true; } }