public static void Write(Stream s, int width, int height, IEnumerable<byte[]> frames) { var compressedFrames = frames.Select(f => Format80.Encode(f)).ToArray(); // note: end-of-file and all-zeroes headers var dataOffset = 14 + (compressedFrames.Length + 2) * ImageHeader.SizeOnDisk; using (var bw = new BinaryWriter(s)) { bw.Write((ushort)compressedFrames.Length); bw.Write((ushort)0); // unused bw.Write((ushort)0); // unused bw.Write((ushort)width); bw.Write((ushort)height); bw.Write((uint)0); // unused foreach (var f in compressedFrames) { var ih = new ImageHeader { Format = Format.Format80, Offset = (uint)dataOffset }; dataOffset += f.Length; ih.WriteTo(bw); } var eof = new ImageHeader { Offset = (uint)dataOffset }; eof.WriteTo(bw); var allZeroes = new ImageHeader { }; allZeroes.WriteTo(bw); foreach (var f in compressedFrames) bw.Write(f); } }
void ProcessImageHeader(SocketAsyncEventArgs args) { // Have we received an entire image header yet? numHeaderBytesReceived += args.BytesTransferred; if (numHeaderBytesReceived < ImageHeaderSize) { // No, so wait till we get some more data. args.SetBuffer(numHeaderBytesReceived, ImageHeaderSize - numHeaderBytesReceived); ReceiveNextPacketAsync(args); return; } // Marshal it into a struct. GCHandle pinnedBuffer = GCHandle.Alloc(args.Buffer, GCHandleType.Pinned); imageHeader = (ImageHeader)Marshal.PtrToStructure(pinnedBuffer.AddrOfPinnedObject(), typeof(ImageHeader)); pinnedBuffer.Free(); // Check it looks sensible. if (imageHeader.MagicNumber != ImageHeaderMagicNumber || imageHeader.Height <= 0 && imageHeader.Height > 10000 || imageHeader.Width <= 0 || imageHeader.Width > 10000 || imageHeader.Size <= 0 || imageHeader.Size > 10000000) { Debug.WriteLine("ERROR: bad image header"); ReceiveNextPacketAsync(args); return; } // Looks like we've got a new image to download. Setup to receive the image data. numImagesAttemptedToReceive++; imageBuffer = new byte[imageHeader.Size]; numImagesBytesReceived = 0; receiveState = ReceiveState.WaitingForDataBlock; args.SetBuffer(imageBuffer, 0, imageBuffer.Length); ReceiveNextPacketAsync(args); }
public TrimmedFrame(ImageHeader header) { var origData = header.Data; var origSize = header.Size; var top = origSize.Height - 1; var bottom = 0; var left = origSize.Width - 1; var right = 0; // Scan frame data to find left-, top-, right-, bottom-most // rows/columns with non-zero pixel data var i = 0; for (var y = 0; y < origSize.Height; y++) { for (var x = 0; x < origSize.Width; x++, i++) { if (origData[i] != 0) { top = Math.Min(y, top); bottom = Math.Max(y, bottom); left = Math.Min(x, left); right = Math.Max(x, right); } } } // Keep a 1px empty border to work avoid rounding issues in the gpu shader if (left > 0) { left -= 1; } if (top > 0) { top -= 1; } if (right < origSize.Width - 1) { right += 1; } if (bottom < origSize.Height - 1) { bottom += 1; } var trimmedWidth = right - left + 1; var trimmedHeight = bottom - top + 1; // Pad the dimensions to an even number to avoid issues with half-integer offsets var widthFudge = trimmedWidth % 2; var heightFudge = trimmedHeight % 2; var destWidth = trimmedWidth + widthFudge; var destHeight = trimmedHeight + heightFudge; if (trimmedWidth == origSize.Width && trimmedHeight == origSize.Height) { // Nothing to trim, so copy old data directly Size = header.Size; FrameSize = header.FrameSize; Offset = header.Offset; Data = header.Data; } else if (trimmedWidth > 0 && trimmedHeight > 0) { // Trim frame Data = new byte[destWidth * destHeight]; for (var y = 0; y < trimmedHeight; y++) { Array.Copy(origData, (y + top) * origSize.Width + left, Data, y * destWidth, trimmedWidth); } Size = new Size(destWidth, destHeight); FrameSize = origSize; Offset = 0.5f * new float2( left + right + widthFudge - origSize.Width + 1, top + bottom + heightFudge - origSize.Height + 1); } else { // Empty frame Data = new byte[0]; } }
private void BuildTilesetFromImage(XElement xTileset, AtlasBuilder atlas) { m_TilesetScript.m_IsImageCollection = false; XElement xImage = xTileset.Element("image"); string textureAssetPath = xImage.GetAttributeAs <string>("source"); int textureWidth = xImage.GetAttributeAs <int>("width"); int textureHeight = xImage.GetAttributeAs <int>("height"); // Load the texture. We will make sprites and tiles out of this image. var tex2d = m_Importer.RequestAssetAtPath <Texture2D>(textureAssetPath); if (tex2d == null) { // Texture was not found so report the error to the importer UI and bail m_Importer.ReportError("Missing texture asset: {0}", textureAssetPath); m_TilesetScript.m_HasErrors = true; return; } // This is annoying but a tileset may have recently changed but Tiled hasn't been updated on the status yet var texAssetPath = AssetDatabase.GetAssetPath(tex2d); var texFullPath = Path.GetFullPath(texAssetPath); var imgHeaderDims = ImageHeader.GetDimensions(texFullPath); if (imgHeaderDims.x != textureWidth || imgHeaderDims.y != textureHeight) { // Tileset needs to be resaved in Tiled m_Importer.ReportError("Mismatching width/height detected. Tileset = ({0}, {1}), image = {2}. This may happen when a tileset image has been resized. Open map and tileset in Tiled Map Editor and resave.", textureWidth, textureHeight, imgHeaderDims); m_TilesetScript.m_HasErrors = true; return; } if (tex2d.width < textureWidth || tex2d.height < textureHeight) { // Texture was not imported into Unity correctly var max = Mathf.Max(textureWidth, textureHeight); m_Importer.ReportError("Texture was imported at a smaller size. Make sure 'Max Size' on '{0}' is at least '{1}'", textureAssetPath, max); m_TilesetScript.m_HasErrors = true; return; } for (int i = 0; i < m_TilesetScript.m_TileCount; i++) { // Get grid x,y coords int x = i % m_TilesetScript.m_TileColumns; int y = i / m_TilesetScript.m_TileColumns; // Get x source on texture int srcx = x * m_TilesetScript.m_TileWidth; srcx += x * m_TilesetScript.m_Spacing; srcx += m_TilesetScript.m_Margin; // Get y source on texture int srcy = y * m_TilesetScript.m_TileHeight; srcy += y * m_TilesetScript.m_Spacing; srcy += m_TilesetScript.m_Margin; // In Tiled, texture origin is the top-left. However, in Unity the origin is bottom-left. srcy = (textureHeight - srcy) - m_TilesetScript.m_TileHeight; if (srcy < 0) { // This is an edge condition in Tiled if a tileset's texture may have been resized break; } // Add the tile to our atlas Rect rcSource = new Rect(srcx, srcy, m_TilesetScript.m_TileWidth, m_TilesetScript.m_TileHeight); atlas.AddTile(i, tex2d, rcSource); } }
// V3 exploit // Magic // internal async static Task LumiaV3CustomFlash(PhoneNotifierViewModel Notifier, List <FlashPart> FlashParts, bool CheckSectorAlignment = true, SetWorkingStatus SetWorkingStatus = null, UpdateWorkingStatus UpdateWorkingStatus = null, ExitSuccess ExitSuccess = null, ExitFailure ExitFailure = null) { if (SetWorkingStatus == null) { SetWorkingStatus = (m, s, v, a, st) => { } } ; if (UpdateWorkingStatus == null) { UpdateWorkingStatus = (m, s, v, st) => { } } ; if (ExitSuccess == null) { ExitSuccess = (m, s) => { } } ; if (ExitFailure == null) { ExitFailure = (m, s) => { } } ; uint chunkSize = 131072u; int chunkSizes = 131072; if (FlashParts != null) { foreach (FlashPart Part in FlashParts) { if (Part.Stream == null) { throw new ArgumentException("Stream is null"); } if (!Part.Stream.CanSeek) { throw new ArgumentException("Streams must be seekable"); } if (((Part.StartSector * 0x200) % chunkSize) != 0) { throw new ArgumentException("Invalid StartSector alignment"); } if (CheckSectorAlignment) { if ((Part.Stream.Length % chunkSize) != 0) { throw new ArgumentException("Invalid Data length"); } } } } try { NokiaFlashModel Model = (NokiaFlashModel)Notifier.CurrentModel; PhoneInfo Info = Model.ReadPhoneInfo(); if ((Info.SecureFfuSupportedProtocolMask & ((ushort)FfuProtocol.ProtocolSyncV2)) == 0) // Exploit needs protocol v2 -> This check is not conclusive, because old phones also report support for this protocol, although it is really not supported. { throw new WPinternalsException("Flash failed!", "Protocols not supported. The phone reports that it does not support the Protocol Sync V2."); } if (Info.FlashAppProtocolVersionMajor < 2) // Old phones do not support the hack. These phones have Flash protocol 1.x. { throw new WPinternalsException("Flash failed!", "Protocols not supported. The phone reports that Flash App communication protocol is lower than 2. Reported version by the phone: " + Info.FlashAppProtocolVersionMajor + "."); } if (Info.UefiSecureBootEnabled) { throw new WPinternalsException("Flash failed!", "UEFI Secureboot must be disabled for the Flash V3 exploit to work."); } // The payloads must be ordered by the number of locations // // FlashApp processes payloads like this: // - First payloads which are with one location, those can be sent in bulk // - Then payloads with more than one location, those should not be sent in bulk // // If you do not order payloads like this, you will get an error, most likely hash mismatch // LumiaV2UnlockBootViewModel.FlashingPayload[] payloads = new LumiaV2UnlockBootViewModel.FlashingPayload[0]; if (FlashParts != null) { payloads = LumiaV2UnlockBootViewModel.GetNonOptimizedPayloads(FlashParts, chunkSizes, (uint)(Info.WriteBufferSize / chunkSize), SetWorkingStatus, UpdateWorkingStatus).OrderBy(x => x.TargetLocations.Count()).ToArray(); } MemoryStream Headerstream1 = new MemoryStream(); // ============================== // Header 1 start ImageHeader image = new ImageHeader(); FullFlash ffimage = new FullFlash(); Store simage = new Store(); // Todo make this read the image itself ffimage.OSVersion = "10.0.11111.0"; ffimage.DevicePlatformId0 = Info.PlatformID; ffimage.AntiTheftVersion = "1.1"; simage.SectorSize = 512; simage.MinSectorCount = Info.EmmcSizeInSectors; //Logging.Log("Generating image manifest..."); string manifest = ManifestIni.BuildUpManifest(ffimage, simage);//, partitions); byte[] TextBytes = System.Text.Encoding.ASCII.GetBytes(manifest); image.ManifestLength = (UInt32)TextBytes.Length; byte[] ImageHeaderBuffer = new byte[0x18]; ByteOperations.WriteUInt32(ImageHeaderBuffer, 0, image.Size); ByteOperations.WriteAsciiString(ImageHeaderBuffer, 0x04, image.Signature); ByteOperations.WriteUInt32(ImageHeaderBuffer, 0x10, image.ManifestLength); ByteOperations.WriteUInt32(ImageHeaderBuffer, 0x14, image.ChunkSize); Headerstream1.Write(ImageHeaderBuffer, 0, 0x18); Headerstream1.Write(TextBytes, 0, TextBytes.Length); RoundUpToChunks(Headerstream1, chunkSize); // Header 1 stop + round // ============================== MemoryStream Headerstream2 = new MemoryStream(); // ============================== // Header 2 start StoreHeader store = new StoreHeader(); store.WriteDescriptorCount = (UInt32)payloads.Count(); store.FinalTableIndex = (UInt32)payloads.Count() - store.FinalTableCount; store.PlatformId = Info.PlatformID; foreach (LumiaV2UnlockBootViewModel.FlashingPayload payload in payloads) { store.WriteDescriptorLength += payload.GetStoreHeaderSize(); } foreach (LumiaV2UnlockBootViewModel.FlashingPayload payload in payloads) { /*if (payload.TargetLocations.First() > PlatEnd) * break;*/ store.FlashOnlyTableIndex += 1; } byte[] StoreHeaderBuffer = new byte[0xF8]; ByteOperations.WriteUInt32(StoreHeaderBuffer, 0, store.UpdateType); ByteOperations.WriteUInt16(StoreHeaderBuffer, 0x04, store.MajorVersion); ByteOperations.WriteUInt16(StoreHeaderBuffer, 0x06, store.MinorVersion); ByteOperations.WriteUInt16(StoreHeaderBuffer, 0x08, store.FullFlashMajorVersion); ByteOperations.WriteUInt16(StoreHeaderBuffer, 0x0A, store.FullFlashMinorVersion); ByteOperations.WriteAsciiString(StoreHeaderBuffer, 0x0C, store.PlatformId); ByteOperations.WriteUInt32(StoreHeaderBuffer, 0xCC, store.BlockSizeInBytes); ByteOperations.WriteUInt32(StoreHeaderBuffer, 0xD0, store.WriteDescriptorCount); ByteOperations.WriteUInt32(StoreHeaderBuffer, 0xD4, store.WriteDescriptorLength); ByteOperations.WriteUInt32(StoreHeaderBuffer, 0xD8, store.ValidateDescriptorCount); ByteOperations.WriteUInt32(StoreHeaderBuffer, 0xDC, store.ValidateDescriptorLength); ByteOperations.WriteUInt32(StoreHeaderBuffer, 0xE0, store.InitialTableIndex); ByteOperations.WriteUInt32(StoreHeaderBuffer, 0xE4, store.InitialTableCount); ByteOperations.WriteUInt32(StoreHeaderBuffer, 0xE8, store.FlashOnlyTableIndex); ByteOperations.WriteUInt32(StoreHeaderBuffer, 0xEC, store.FlashOnlyTableCount); ByteOperations.WriteUInt32(StoreHeaderBuffer, 0xF0, store.FinalTableIndex); ByteOperations.WriteUInt32(StoreHeaderBuffer, 0xF4, store.FinalTableCount); Headerstream2.Write(StoreHeaderBuffer, 0, 0xF8); byte[] descriptorsBuffer = new byte[store.WriteDescriptorLength]; UInt32 NewWriteDescriptorOffset = 0; foreach (LumiaV2UnlockBootViewModel.FlashingPayload payload in payloads) { ByteOperations.WriteUInt32(descriptorsBuffer, NewWriteDescriptorOffset + 0x00, (UInt32)payload.TargetLocations.Count()); // Location count ByteOperations.WriteUInt32(descriptorsBuffer, NewWriteDescriptorOffset + 0x04, payload.ChunkCount); // Chunk count NewWriteDescriptorOffset += 0x08; foreach (UInt32 location in payload.TargetLocations) { ByteOperations.WriteUInt32(descriptorsBuffer, NewWriteDescriptorOffset + 0x00, 0x00000000); // Disk access method (0 = Begin, 2 = End) ByteOperations.WriteUInt32(descriptorsBuffer, NewWriteDescriptorOffset + 0x04, location); // Chunk index NewWriteDescriptorOffset += 0x08; } } Headerstream2.Write(descriptorsBuffer, 0, (Int32)store.WriteDescriptorLength); RoundUpToChunks(Headerstream2, chunkSize); // Header 2 stop + round // ============================== SecurityHeader security = new SecurityHeader(); Headerstream1.Seek(0, SeekOrigin.Begin); Headerstream2.Seek(0, SeekOrigin.Begin); security.HashTableSize = 0x20 * (UInt32)((Headerstream1.Length + Headerstream2.Length) / chunkSize); foreach (LumiaV2UnlockBootViewModel.FlashingPayload payload in payloads) { security.HashTableSize += payload.GetSecurityHeaderSize(); } byte[] HashTable = new byte[security.HashTableSize]; BinaryWriter bw = new BinaryWriter(new MemoryStream(HashTable)); SHA256 crypto = SHA256.Create(); for (int i = 0; i < Headerstream1.Length / chunkSize; i++) { byte[] buffer = new byte[chunkSize]; Headerstream1.Read(buffer, 0, (Int32)chunkSize); byte[] hash = crypto.ComputeHash(buffer); bw.Write(hash, 0, hash.Length); } for (int i = 0; i < Headerstream2.Length / chunkSize; i++) { byte[] buffer = new byte[chunkSize]; Headerstream2.Read(buffer, 0, (Int32)chunkSize); byte[] hash = crypto.ComputeHash(buffer); bw.Write(hash, 0, hash.Length); } foreach (LumiaV2UnlockBootViewModel.FlashingPayload payload in payloads) { bw.Write(payload.ChunkHashes[0], 0, payload.ChunkHashes[0].Length); } bw.Close(); //Logging.Log("Generating image catalog..."); byte[] catalog = GenerateCatalogFile(HashTable); security.CatalogSize = (UInt32)catalog.Length; byte[] SecurityHeaderBuffer = new byte[0x20]; ByteOperations.WriteUInt32(SecurityHeaderBuffer, 0, security.Size); ByteOperations.WriteAsciiString(SecurityHeaderBuffer, 0x04, security.Signature); ByteOperations.WriteUInt32(SecurityHeaderBuffer, 0x10, security.ChunkSizeInKb); ByteOperations.WriteUInt32(SecurityHeaderBuffer, 0x14, security.HashAlgorithm); ByteOperations.WriteUInt32(SecurityHeaderBuffer, 0x18, security.CatalogSize); ByteOperations.WriteUInt32(SecurityHeaderBuffer, 0x1C, security.HashTableSize); MemoryStream retstream = new MemoryStream(); retstream.Write(SecurityHeaderBuffer, 0, 0x20); retstream.Write(catalog, 0, (Int32)security.CatalogSize); retstream.Write(HashTable, 0, (Int32)security.HashTableSize); RoundUpToChunks(retstream, chunkSize); Headerstream1.Seek(0, SeekOrigin.Begin); Headerstream2.Seek(0, SeekOrigin.Begin); byte[] buff = new byte[Headerstream1.Length]; Headerstream1.Read(buff, 0, (Int32)Headerstream1.Length); Headerstream1.Close(); retstream.Write(buff, 0, buff.Length); buff = new byte[Headerstream2.Length]; Headerstream2.Read(buff, 0, (Int32)Headerstream2.Length); Headerstream2.Close(); retstream.Write(buff, 0, buff.Length); // -------- // Go back to the beginning retstream.Seek(0, SeekOrigin.Begin); byte[] FfuHeader = new byte[retstream.Length]; await retstream.ReadAsync(FfuHeader, 0, (int)retstream.Length); retstream.Close(); byte Options = 0; if (!Info.IsBootloaderSecure) { Options = (byte)((FlashOptions)Options | FlashOptions.SkipSignatureCheck); } LogFile.Log("Flash in progress...", LogType.ConsoleOnly); SetWorkingStatus("Flashing...", null, (UInt64?)payloads.Count(), Status: WPinternalsStatus.Flashing); Model.SendFfuHeaderV1(FfuHeader, Options); UInt64 counter = 0; int numberOfPayloadsToSendAtOnce = (int)Math.Round((double)Info.WriteBufferSize / chunkSize); byte[] payloadBuffer; for (int i = 0; i < payloads.Count(); i += numberOfPayloadsToSendAtOnce) { if (i + numberOfPayloadsToSendAtOnce - 1 >= payloads.Count()) { numberOfPayloadsToSendAtOnce = payloads.Count() - i; } payloadBuffer = new byte[numberOfPayloadsToSendAtOnce * chunkSizes]; string ProgressText = "Flashing resources"; for (int j = 0; j < numberOfPayloadsToSendAtOnce; j++) { LumiaV2UnlockBootViewModel.FlashingPayload payload = payloads[i + j]; UInt32 StreamIndex = payload.StreamIndexes.First(); FlashPart flashPart = FlashParts[(int)StreamIndex]; if (flashPart.ProgressText != null) { ProgressText = flashPart.ProgressText; } Stream Stream = flashPart.Stream; Stream.Seek(payload.StreamLocations.First(), SeekOrigin.Begin); Stream.Read(payloadBuffer, j * chunkSizes, chunkSizes); counter++; } Model.SendFfuPayloadV2(payloadBuffer, int.Parse((counter * 100 / (ulong)payloads.Count()).ToString())); UpdateWorkingStatus(ProgressText, null, counter, WPinternalsStatus.Flashing); } Model.ResetPhone(); await Notifier.WaitForRemoval(); ExitSuccess("Flash succeeded!", null); } catch { throw new WPinternalsException("Custom flash failed"); } } } }
}//end CreateDirectory private void CreateXml(JArray qs, Topic topic) { if (!File.Exists(string.Format(@"Assets/Resources/Minigames/Millionaire/NEW{0}/{0}Questions.xml", topic.Title))) { XmlDocument doc = new XmlDocument(); //Creates the XML header: <?xml version="1.0" encoding="UTF-8"?> XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(docNode); //Creates the questions Node: <questions type="array"> XmlNode questionNode = doc.CreateElement("questions"); XmlAttribute questionAttribute = doc.CreateAttribute("type"); questionAttribute.Value = "array"; questionNode.Attributes.Append(questionAttribute); doc.AppendChild(questionNode); //Creates the title Node: <title>TOPIC</title> XmlNode titleNode = doc.CreateElement("title"); titleNode.AppendChild(doc.CreateTextNode(topic.Title)); questionNode.AppendChild(titleNode); //Creates the description Node: <description>EMPTY RIGHT NOW</description> XmlNode descritionNode = doc.CreateElement("description"); descritionNode.AppendChild(doc.CreateTextNode(topic.Description)); questionNode.AppendChild(descritionNode); //Creates the category Node: <category>UNUSED</category> XmlNode categoryNode = doc.CreateElement("category"); categoryNode.AppendChild(doc.CreateTextNode("Has been unused since I started")); questionNode.AppendChild(categoryNode); //Creates the path Node: <path>PATH WHERE IMAGES ARE STORED</path> XmlNode imgPathNode = doc.CreateElement("path"); imgPathNode.AppendChild(doc.CreateTextNode(string.Format(@"NEW{0}/Images/", topic.Title))); questionNode.AppendChild(imgPathNode); //Creates the previewImage Node: <previewImage>EMPTY RIGHT NOW</previewImage> XmlNode previewImageNode = doc.CreateElement("previewImage"); previewImageNode.AppendChild(doc.CreateTextNode("")); questionNode.AppendChild(imgPathNode); //Creates The tags Node: <tags type="array" /> XmlNode tagsNode = doc.CreateElement("tags"); XmlAttribute tagsAttribute = doc.CreateAttribute("type"); tagsAttribute.Value = "array"; tagsNode.Attributes.Append(tagsAttribute); questionNode.AppendChild(tagsNode); int questionNumber = 0; for (int currentLevel = 1; currentLevel <= 15; currentLevel++) { int numOfQuestions = 0; for (int i = 0; i < qs.Count; i++) { if (qs[i]["Level"].ToString().Equals(currentLevel.ToString())) { numOfQuestions++; } } if (numOfQuestions > 0) // While there are questions do the following //Creates the level node: <level type="array" name="LEVELNUMBER"> { XmlNode levelNode = doc.CreateElement("level"); XmlAttribute levelAttribute = doc.CreateAttribute("type"); levelAttribute.Value = "array"; levelNode.Attributes.Append(levelAttribute); levelAttribute = doc.CreateAttribute("name"); levelAttribute.Value = currentLevel.ToString(); levelNode.Attributes.Append(levelAttribute); questionNode.AppendChild(levelNode); for (int currentQuestion = 0; currentQuestion < numOfQuestions; currentQuestion++) { //Creates the question node: <question name="QUESTIONNUMBER"> XmlNode gameQuestionNode = doc.CreateElement("question"); XmlAttribute gameQuestionAttributes = doc.CreateAttribute("name"); gameQuestionAttributes.Value = (currentQuestion + 1).ToString(); gameQuestionNode.Attributes.Append(gameQuestionAttributes); levelNode.AppendChild(gameQuestionNode); //Creates the content node the contains each question: <content>QUESTION HERE</content> XmlNode actualQuestionNode = doc.CreateElement("content"); actualQuestionNode.AppendChild(doc.CreateTextNode(qs[questionNumber]["Content"].ToString())); gameQuestionNode.AppendChild(actualQuestionNode); //Creates the image node: <image>IMAGEFILENAME</image> XmlNode imageNode = doc.CreateElement("image"); imageNode.AppendChild(doc.CreateTextNode("question" + questionNumber.ToString())); gameQuestionNode.AppendChild(imageNode); string filename = string.Format(@"Assets/Resources/Minigames/Millionaire/NEW{0}/Images/question{1}.png", topic.Title, questionNumber.ToString()); FileInfo f = new FileInfo(filename); if (f.Exists) { ImageHeader.Vector2Int imgSize = ImageHeader.GetDimensions(filename); UnityEngine.Debug.Log("Topic: " + topic.Title + "\nQuestionNumber: " + questionNumber + "\nimgSize.x =" + imgSize.x + "\nimgSize.y =" + imgSize.y); XmlNode imgWidth = doc.CreateElement("imgWidth"); XmlNode imgHeight = doc.CreateElement("imgHeight"); if (imgSize.x == 0 || imgSize.y == 0) { imgWidth.AppendChild(doc.CreateTextNode("0")); gameQuestionNode.AppendChild(imgWidth); imgHeight.AppendChild(doc.CreateTextNode("0")); gameQuestionNode.AppendChild(imgHeight); } else { imgWidth.AppendChild(doc.CreateTextNode(XmlConvert.ToString(imgSize.x))); gameQuestionNode.AppendChild(imgWidth); imgHeight.AppendChild(doc.CreateTextNode(XmlConvert.ToString(imgSize.y))); gameQuestionNode.AppendChild(imgHeight); } } else { XmlNode imgWidth = doc.CreateElement("imgWidth"); XmlNode imgHeight = doc.CreateElement("imgHeight"); imgWidth.AppendChild(doc.CreateTextNode("0")); gameQuestionNode.AppendChild(imgWidth); imgHeight.AppendChild(doc.CreateTextNode("0")); gameQuestionNode.AppendChild(imgHeight); } //Creates the answers node: <answers type="array"> XmlNode answersNode = doc.CreateElement("answers"); XmlAttribute answersAttrubutes = doc.CreateAttribute("type"); answersAttrubutes.Value = "array"; answersNode.Attributes.Append(answersAttrubutes); gameQuestionNode.AppendChild(answersNode); string[] answers = qs[questionNumber]["Answers"].ToObject <string[]>(); for (int i = 0; i < 4; i++) { XmlNode answerNode = doc.CreateElement("answer"); answersNode.AppendChild(answerNode); //Creates the correct node which says whether the current answer is the correct answer or not: <correct>TRUE or FALSE</correct> XmlNode correctNode = doc.CreateElement("correct"); correctNode.AppendChild(doc.CreateTextNode((int)qs[questionNumber]["CorrectAnswerIndex"] == i ? "true" : "false")); answerNode.AppendChild(correctNode); //Creates the answer node which contains the answer: <answer>ANSWERDATA</answer> XmlNode answerContentNode = doc.CreateElement("content"); answerContentNode.AppendChild(doc.CreateTextNode(answers[i])); answerNode.AppendChild(answerContentNode); } questionNumber++; } //end for } //end if } //end for //Saves the data after it has all been retrieved doc.Save(string.Format(@"Assets/Resources/Minigames/Millionaire/NEW{0}/{0}Questions.xml", topic.Title)); doc = null; //Garbage Collect to help improve memory: Resources.UnloadUnusedAssets(); GC.WaitForPendingFinalizers(); GC.Collect(); } } //end CreateXML
public ShpTDSprite(Stream stream) { imageCount = stream.ReadUInt16(); stream.Position += 4; var width = stream.ReadUInt16(); var height = stream.ReadUInt16(); Size = new Size(width, height); stream.Position += 4; var headers = new ImageHeader[imageCount]; Frames = headers.AsReadOnly(); for (var i = 0; i < headers.Length; i++) headers[i] = new ImageHeader(stream, this); // Skip eof and zero headers stream.Position += 16; var offsets = headers.ToDictionary(h => h.FileOffset, h => h); for (var i = 0; i < imageCount; i++) { var h = headers[i]; if (h.Format == Format.XORPrev) h.RefImage = headers[i - 1]; else if (h.Format == Format.XORLCW && !offsets.TryGetValue(h.RefOffset, out h.RefImage)) throw new InvalidDataException("Reference doesn't point to image data {0}->{1}".F(h.FileOffset, h.RefOffset)); } shpBytesFileOffset = stream.Position; shpBytes = stream.ReadBytes((int)(stream.Length - stream.Position)); foreach (var h in headers) Decompress(h); }
object GetImageHeight() { return(ImageHeader.GetDimensions( ProjectManager.MakeAbsolute(((ReferencedFileSave)Instance).Name)).Height); }
public static void Write(Stream s, Size size, IEnumerable<byte[]> frames) { var compressedFrames = frames.Select(f => LCWCompression.Encode(f)).ToList(); // note: end-of-file and all-zeroes headers var dataOffset = 14 + (compressedFrames.Count + 2) * 8; using (var bw = new BinaryWriter(s)) { bw.Write((ushort)compressedFrames.Count); bw.Write((ushort)0); bw.Write((ushort)0); bw.Write((ushort)size.Width); bw.Write((ushort)size.Height); bw.Write((uint)0); foreach (var f in compressedFrames) { var ih = new ImageHeader { Format = Format.LCW, FileOffset = (uint)dataOffset }; dataOffset += f.Length; ih.WriteTo(bw); } var eof = new ImageHeader { FileOffset = (uint)dataOffset }; eof.WriteTo(bw); var allZeroes = new ImageHeader { }; allZeroes.WriteTo(bw); foreach (var f in compressedFrames) bw.Write(f); } }
void Decompress(ImageHeader h) { // No extra work is required for empty frames if (h.Size.Width == 0 || h.Size.Height == 0) return; if (recurseDepth > imageCount) throw new InvalidDataException("Format20/40 headers contain infinite loop"); switch (h.Format) { case Format.XORPrev: case Format.XORLCW: { if (h.RefImage.Data == null) { ++recurseDepth; Decompress(h.RefImage); --recurseDepth; } h.Data = CopyImageData(h.RefImage.Data); XORDeltaCompression.DecodeInto(shpBytes, h.Data, (int)(h.FileOffset - shpBytesFileOffset)); break; } case Format.LCW: { var imageBytes = new byte[Size.Width * Size.Height]; LCWCompression.DecodeInto(shpBytes, imageBytes, (int)(h.FileOffset - shpBytesFileOffset)); h.Data = imageBytes; break; } default: throw new InvalidDataException(); } }
public void Load(System.IO.Stream stream) { Text = FileName; using (var reader = new FileReader(stream)) { reader.SetByteOrder(true); uint Identifier = reader.ReadUInt32(); //TPL has multiple versions i assume? Some games like F Zero use a custom one so try that if (Identifier != 0x0020AF30) { reader.Position = 0; uint ImageCount = reader.ReadUInt32(); Console.WriteLine("ImageCount" + ImageCount); for (int i = 0; i < ImageCount; i++) { reader.SeekBegin(4 + (i * 0x10)); uint format = reader.ReadUInt32(); uint offset = reader.ReadUInt32(); uint width = reader.ReadUInt16(); uint height = reader.ReadUInt16(); uint mipCount = reader.ReadUInt16(); ushort unknown = reader.ReadUInt16(); if (format == 256) { break; } Console.WriteLine(offset); Console.WriteLine(format); var GXFormat = (Decode_Gamecube.TextureFormats)format; //Now create a wrapper var texWrapper = new TplTextureWrapper(); texWrapper.Text = $"Texture {i}"; texWrapper.ImageKey = "Texture"; texWrapper.SelectedImageKey = "Texture"; texWrapper.Format = Decode_Gamecube.ToGenericFormat(GXFormat); texWrapper.Width = width; texWrapper.Height = height; texWrapper.MipCount = mipCount; texWrapper.ImageData = reader.getSection(offset, (uint)Decode_Gamecube.GetDataSize(GXFormat, (int)width, (int)height)); texWrapper.PlatformSwizzle = PlatformSwizzle.Platform_Gamecube; Nodes.Add(texWrapper); } } else { uint ImageCount = reader.ReadUInt32(); uint ImageOffsetTable = reader.ReadUInt32(); for (int i = 0; i < ImageCount; i++) { reader.SeekBegin(ImageOffsetTable + (i * 8)); uint ImageHeaderOffset = reader.ReadUInt32(); uint PaletteHeaderOffset = reader.ReadUInt32(); reader.SeekBegin(ImageHeaderOffset); var image = new ImageHeader(); image.Read(reader); ImageHeaders.Add(image); var GXFormat = (Decode_Gamecube.TextureFormats)image.Format; Console.WriteLine($"ImageOffset {image.ImageOffset}"); //Now create a wrapper var texWrapper = new TplTextureWrapper(); texWrapper.Text = $"Texture {i}"; texWrapper.ImageKey = "Texture"; texWrapper.SelectedImageKey = "Texture"; texWrapper.Format = Decode_Gamecube.ToGenericFormat(GXFormat); texWrapper.Width = image.Width; texWrapper.Height = image.Height; texWrapper.MipCount = 1; texWrapper.PlatformSwizzle = PlatformSwizzle.Platform_Gamecube; texWrapper.ImageData = reader.getSection(image.ImageOffset, (uint)Decode_Gamecube.GetDataSize(GXFormat, (int)image.Width, (int)image.Height)); //Palette is sometimes unused to check if (PaletteHeaderOffset != 0) { reader.SeekBegin(PaletteHeaderOffset); var palette = new PaletteHeader(); palette.Read(reader); PaletteHeaders.Add(palette); var GXPaletteFormat = (Decode_Gamecube.PaletteFormats)palette.PaletteFormat; Console.WriteLine($"GXPaletteFormat {GXPaletteFormat}"); texWrapper.SetPaletteData(palette.Data, Decode_Gamecube.ToGenericPaletteFormat(GXPaletteFormat)); } Nodes.Add(texWrapper); } } } }
public ImagePassEventArgs(Thread source, ImageHeader image) { Source = source; BlockedImageHeader = image; }
void Update() { if (Input.GetMouseButtonDown(0) && !playdatshit) { if (!File.Exists(Application.dataPath + "/Resources/" + "sizeTest.png")) { ScreenCapture.CaptureScreenshot(Application.dataPath + "/Resources/" + "sizeTest.png"); Debug.Log("[INFO] Creating size template."); } else { Vector2Int imgSize = ImageHeader.GetDimensions(Application.dataPath + "/Resources/" + "sizeTest.png"); Debug.Log("Image width: " + imgSize.x + "\n\t" + "Image height: " + imgSize.y); screenshotWidth = imgSize.x; screenshotHeight = imgSize.y; playdatshit = true; encodedList.ims = new RLEncoding[myPath.getLength()]; string folderPath; folderPath = Application.persistentDataPath + "/images"; System.IO.DirectoryInfo di = new DirectoryInfo(folderPath); if (Directory.Exists(folderPath)) { foreach (FileInfo file in di.GetFiles()) { file.Delete(); } } Debug.Log("[INFO] Saving data to: " + folderPath); System.IO.Directory.CreateDirectory(folderPath); } } if (Input.GetMouseButtonDown(1)) { int randomCombination = rand.Next(combsCombined.Count); for (int j = 0; j < targetObjects.Length; ++j) { targetObjects[j].SetActive(Array.Exists(combsCombined[randomCombination], el => el == j)); if (Array.Exists(combsCombined[randomCombination], el => el == j)) { Debug.Log("Setting active " + j); } else { Debug.Log("Setting inactive " + j); } } } if (playdatshit) { if (myPath.next()) { if (randomObjectActivation) { int randomCombination = rand.Next(combsCombined.Count); for (int j = 0; j < targetObjects.Length; ++j) { targetObjects[j].SetActive(Array.Exists(combsCombined[randomCombination], el => el == j)); } int r = rand.Next(combsCombined[randomCombination].Length); // 1: 0; 2: 0,1; 3: 0,1,2 int cnt = 0; // 0-7 index of object to look at foreach (var obj in targetObjects) { if (obj.activeSelf) { if (cnt == r) { focusObject = obj.transform; } cnt++; } } transform.position = focusObject.position + myPath.nextPosition(); transform.LookAt(focusObject.position); } else { transform.position = focusObject.position + myPath.nextPosition(); transform.LookAt(focusObject.position); } string scrPath, folderName = "images/", imageName = myPath.currentID.ToString() + ".png"; int maskID = myPath.currentID; // Path to screenshot of the view from the normal camera scrPath = Path.Combine(Application.persistentDataPath, "images", imageName); ScreenCapture.CaptureScreenshot(scrPath); // save encoding for given (object,material,image) encodedList.ims[myPath.currentID] = createRLEncoding4Image(folderName, imageName, maskID); if (saveBinaryMask) { for (int i = 0; i < encodedList.ims[myPath.currentID].annotations.Count; i++) { Texture2D tex = RLE2alpha8(encodedList.ims[myPath.currentID].annotations[i].segmentation, true); byte[] bytes = tex.EncodeToPNG(); File.WriteAllBytes(Path.Combine(Application.persistentDataPath, "images/" + maskID.ToString() + "-" + i.ToString() + ".png"), bytes); } } } else { Debug.Log("[INFO] Finished taking photos."); playdatshit = false; string jsonString = JsonUtility.ToJson(encodedList, true); using (TextWriter tw = new StreamWriter(Path.Combine(Application.persistentDataPath, "mask_data.json"))) { tw.Write(jsonString); Debug.Log("[INFO] Saved json."); } } } }
private static void SerializeHeader(ref ImageHeader header, Serializer serializer) { byte usage = (byte)header.Usage, alpha = (byte)header.AlphaBits, format = (byte)header.Format, mips = (byte)header.MipLevels; if (serializer.Serialize(ref usage)) header.Usage = (ImageHeader.UsageE)usage; if (serializer.Serialize(ref alpha)) header.AlphaBits = alpha; if (serializer.Serialize(ref format)) header.Format = (ImageHeader.FormatE)format; if (serializer.Serialize(ref mips)) header.MipLevels = mips; serializer.Serialize(ref header.Width); serializer.Serialize(ref header.Height); }
public ImageHeader MountImageHeader(string overlapImagePath, double overlapWidth, double overlapHeight, string bgImagePath, double bgWidth, double bgHeight, bool hasSearchBar = false) { ImageHeader imageHeader = new ImageHeader { grid = new Grid() { RowDefinitions = { new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, }, ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) } }, } }; Image _imageOver = new Image { Source = ImageSource.FromUri(new Uri(overlapImagePath)), WidthRequest = overlapWidth, HeightRequest = overlapHeight }; Image _imageBg = new Image { Source = ImageSource.FromUri(new Uri(bgImagePath)), WidthRequest = bgWidth, HeightRequest = bgHeight }; imageHeader.innerElements = new InnerElementsImageHeader { imageOverlay = _imageOver, imageBackground = _imageBg }; //SETS OVERLAP imageHeader.innerElements.imageOverlay.HorizontalOptions = LayoutOptions.Center; imageHeader.innerElements.imageOverlay.Aspect = Aspect.AspectFill; //SETS BACKGROUND imageHeader.innerElements.imageBackground.HorizontalOptions = LayoutOptions.FillAndExpand; imageHeader.innerElements.imageBackground.Aspect = Aspect.AspectFill; if (hasSearchBar) { imageHeader.innerElements.searchBar = new SearchBar() { Placeholder = "", }; } imageHeader.grid.Children.Add(imageHeader.innerElements.imageBackground); imageHeader.grid.Children.Add(imageHeader.innerElements.imageOverlay); Grid.SetColumn(imageHeader.innerElements.imageOverlay, 0); Grid.SetColumn(imageHeader.innerElements.imageBackground, 0); Grid.SetRow(imageHeader.innerElements.imageOverlay, 0); Grid.SetRow(imageHeader.innerElements.imageBackground, 0); imageHeader.Content = imageHeader.grid; return(imageHeader); }