public static LoadTGA ( Stream TGAStream ) : |
||
TGAStream | Stream | |
return |
public override Texture2D LoadImageAt(int index, bool Alpha) { switch (_RES) { case GAME_UW2: { return(extractUW2Bitmap("data\\byt.ark", index, Alpha)); } default: { if (File.Exists(BasePath + FilePaths[index].Replace(".", "_") + "\\001.tga")) { return(TGALoader.LoadTGA(BasePath + FilePaths[index].Replace(".", "_") + "\\001.tga")); } if (currentIndex != index) { //Only load from disk if the image to bring back has changed. DataLoaded = false; Path = FilePaths[index]; LoadImageFile(); } return(Image(ImageFileData, 0, 320, 200, "name_goes_here", GameWorldController.instance.palLoader.Palettes[PaletteIndices[index]], Alpha)); } } }
private void LoadTGATextures(ZipFile pk3) { foreach (Texture tex in Textures) { // The size of the new Texture2D object doesn't matter. It will be replaced (including its size) with the data from the texture that's getting pulled from the pk3 file. if (pk3.ContainsEntry(tex.Name + ".tga")) { Texture2D readyTex = new Texture2D(4, 4); var entry = pk3 [tex.Name + ".tga"]; using (var stream = entry.OpenReader()) { var ms = new MemoryStream(); entry.Extract(ms); readyTex = TGALoader.LoadTGA(ms); } readyTex.name = tex.Name; readyTex.filterMode = FilterMode.Trilinear; readyTex.Compress(true); if (readyTextures.ContainsKey(tex.Name)) { Debug.Log("Updating texture with name " + tex.Name + ".tga"); readyTextures [tex.Name] = readyTex; } else { readyTextures.Add(tex.Name, readyTex); } } } }
/*public GRLoader(int File, string AuxPalToUse, int AuxPalIndex) * { * if (AuxPalIndex!=-1) * { * useOverrideAuxPalIndex=true; * //OverrideAuxPalIndex=OverrideAuxPalIndex ; * } * AuxPalPath=AuxPalToUse; * FileToLoad=File; * LoadImageFile(); * }*/ public override bool LoadImageFile() { string ModPath = BasePath + pathGR[FileToLoad].Replace("--", sep.ToString()).Replace(".", "_"); if (Directory.Exists(ModPath)) { LoadMod = true; } if (!DataLoader.ReadStreamFile(BasePath + pathGR[FileToLoad].Replace("--", sep.ToString()), out ImageFileData)) { Debug.Log("Unable to load " + BasePath + pathGR[FileToLoad].Replace("--", sep.ToString())); return(false); } else { NoOfImages = (int)DataLoader.getValAtAddress(ImageFileData, 1, 16); ImageCache = new Texture2D[NoOfImages]; if (LoadMod) { //Load up modded image data at the path for (int i = 0; i <= ImageCache.GetUpperBound(0); i++) { if (File.Exists(ModPath + sep + i.ToString("d3") + ".tga")) { ImageCache[i] = TGALoader.LoadTGA(ModPath + sep + i.ToString("d3") + ".tga"); } } } ImageFileDataLoaded = true; return(true); } }
public void Awake() { var x = Screen.width / 2 - _width / 2; var y = Screen.height / 2 - _height / 2; _atlas = TGALoader.LoadTGA($"{Central.Instance.HomePath}/resources/icons.tga", false); _windowRect = new Rect(x, y, _width, _height); _coordsCache = new List <Rect>(); _spritesCache = new List <Rect>(); _itemNameStyle = new GUIStyle() { fixedHeight = 64, fontSize = 12, fontStyle = FontStyle.BoldAndItalic, wordWrap = true }; _itemNameStyle.normal.textColor = Color.yellow; _itemNameStyle.alignment = TextAnchor.MiddleCenter; _itemSimilarStyle = new GUIStyle(_itemNameStyle) { fontSize = 10, fontStyle = FontStyle.Bold, fixedHeight = 20, fixedWidth = 20 }; _itemSimilarStyle.normal.textColor = Color.white; }
public bool GetMapPreview(string Mapname, out Texture2D preview) { preview = new Texture2D(1, 1); if (!isReady || Mapname == "") { return(false); } var mapPreviewPath = Path.Combine(MapFitPath, Mapname + ".tga").ToUpper(); var fileData = MechCommanderUnity.Instance.FileManager.File(mapPreviewPath); if (fileData != null) { MechCommanderUnity.LogMessage("TGA file " + mapPreviewPath); preview = TGALoader.LoadTGA(new MemoryStream(fileData)); return(true); } else { var missionFile = new FITFile(MechCommanderUnity.Instance.FileManager.File(MCGExtensions.PathCombine(new string[] { "missions", Mapname + ".fit" }))); missionFile.SeekSection("TerrainSystem"); missionFile.GetString("TerrainFileName", out string terrainFileName); mapPreviewPath = Path.Combine(MapFitPath, terrainFileName + ".tga").ToUpper(); fileData = MechCommanderUnity.Instance.FileManager.File(mapPreviewPath); if (fileData != null) { MechCommanderUnity.LogMessage("TGA file DIFFERENT NAME " + mapPreviewPath); preview = TGALoader.LoadTGA(new MemoryStream(fileData)); return(true); } } MechCommanderUnity.LogMessage("Can´t Find TGA file " + mapPreviewPath); return(false); }
// Start is called before the first frame update void Start() { Material mat = GetComponent <MeshRenderer>().material; MeshFilter mf = GetComponent <MeshFilter>(); string objName = mf.mesh.name.Split(' ')[0]; string path = Application.dataPath + "/objects/" + objName + "/"; string[] lines = File.ReadAllLines(path + objName + ".txt"); List <Vector4> list = new List <Vector4>(); int num = 1; while (true) { if (lines[num].Split(' ').Length == 1) { break; } num++; } string imageName = path + lines[num]; Texture2D tex = TGALoader.LoadTGA(imageName); mat.mainTexture = tex; }
void Awake() { GameObject player = GameObject.Find("Gronk"); return; //Debug.Log ("Moving " + player.name); player.transform.position = new Vector3(38.72f, 4.152f, 3.244f); GameObject skul = GameObject.Find("a_skull_30_03_00_1016"); //if (skul!=null) //{ string filePath = "c:\\objects_0000.tga"; //Debug.Log (filePath); SpriteRenderer sprt = skul.GetComponentInChildren <SpriteRenderer>(); //Sprite newimage= new Sprite(); //Texture2D newtex= new Texture2D(22,11); Texture2D newTex = TGALoader.LoadTGA(filePath); //newTex.height=newTex.height*2; //newTex.width=newTex.width*2; Sprite newSprite = Sprite.Create(newTex, new Rect(0, 0, newTex.width, newTex.height), new Vector2(0.5f, 0.0f)); //Sprite newSprite = TGALoader.LoadTGASprite(filePath);e sprt.sprite = newSprite; GameObject theWallBrotha = GameObject.Find("Wall_30_03"); Material[] myMat = theWallBrotha.GetComponent <Renderer>().materials; for (int i = 0; i < myMat.GetUpperBound(0); i++) { //Debug.Log (myMat[i].name); myMat[i].mainTexture = newTex; } Mesh mesh = theWallBrotha.GetComponent <MeshFilter>().mesh; Vector3[] vertices = mesh.vertices; Vector2[] uvs = new Vector2[vertices.Length]; int j = 0; while (j < uvs.Length) { uvs[j] = new Vector2(vertices[j].x, vertices[j].z); j++; } //mesh.uv = uvs; //if (newimage!=null) //{ //Debug.Log("New image loaded"); //} //else //{ //Debug.Log("f**k"); //} //} //CreateObj(); }
private Texture2D GetTexture(WWW loader) { string ext = Path.GetExtension(loader.url).ToLower(); if (ext != ".png" && ext != ".jpg" && ext != ".tga") { //Debug.LogWarning("maybe unsupported texture format:"+ext); } return(ext == ".tga" ? TGALoader.LoadTGA(new MemoryStream(loader.bytes)) : loader.texture); // refactor this method to add support for more formats }
private void ChangeColor(string color, string folder) { var material = Resources.Load <Material>($"Materials/{folder}/{characterConfig.HairMaterial}"); var directory = Application.streamingAssetsPath; var characterFolder = $"Colors/{characterConfig.PrefabName}/{folder}"; var path = Path.Combine(directory, characterFolder); var file = Path.Combine(path, $"{color}.tga"); var texture2D = TGALoader.LoadTGA(file); material.mainTexture = texture2D; }
/// <summary> /// Loads specified atlas into memory. /// </summary> /// <param name="name">Raw file name of an atlas. It gets converted into 'maps/[name].tga'</param> /// <param name="blackIsTransparency">Specifies whether to use black color as a transparency or rely on the alpha channel</param> public void LoadAtlas(string name, bool blackIsTransparency = false) { if (atlases.ContainsKey(name)) { return; } var atlas = new UIAtlas(); atlas.atlas = TGALoader.LoadTGA(GameAPI.instance.fileSystem.GetStreamFromPath(Path.Combine("maps", name + ".tga")), blackIsTransparency); atlases.Add(name, atlas); }
/// <summary> /// Initializes a new instance of the <see cref="TextureLoader"/> class. /// </summary> /// <param name="index">Index.</param> /// <param name="TextureType">Texture type. 0 = normal, 1 = palette cycled</param> public Texture2D LoadImageAt(int index, short TextureType) { switch (TextureType) { case 1: // Palette cycled return(LoadImageAt(index, GameWorldController.instance.palLoader.GreyScale)); case 2: //normal map return(TGALoader.LoadTGA(ModPathW + sep + index.ToString("d3") + "_normal.tga")); default: return(LoadImageAt(index, GameWorldController.instance.palLoader.Palettes[0])); } }
private static bool LoadTextureData(string path, out U::UnityEngine.Texture2D texture2D) { bool flag; texture2D = null; try { path = string.Concat(Texture2DOverride.TranslationImageDir, path); string extension = Path.GetExtension(path); if (extension == ".dds") { flag = DXTLoader.LoadDXT(path, out texture2D); } else if (extension == ".jpeg" || extension == ".jpg") { texture2D = new Texture2D(2, 2, TextureFormat.RGB24, false); flag = texture2D.LoadImage(File.ReadAllBytes(path)); } else if (extension == ".png") { texture2D = new Texture2D(2, 2, TextureFormat.ARGB32, false); flag = texture2D.LoadImage(File.ReadAllBytes(path)); } else if (extension == ".psd") { flag = PSDLoader.LoadPSD(path, out texture2D); } else if (extension == ".tga") { flag = TGALoader.LoadTGA(path, out texture2D); } else { return(false); } } catch (Exception exception) { IniSettings.Error(string.Concat("LoadImage:\n", exception.ToString())); return(false); } return(flag); }
/// <summary> /// Loads specified atlas into memory. /// </summary> /// <param name="name">Raw file name of an atlas. It gets converted into 'maps/[name].tga'</param> /// <param name="blackIsTransparency">Specifies whether to use black color as a transparency or rely on the alpha channel</param> public void LoadAtlas(string name, bool blackIsTransparency = false) { if (atlases.ContainsKey(name)) { return; } var atlas = new UIAtlas(); var stream = GameAPI.instance.fileSystem.GetStreamFromPath(Path.Combine("maps", name + ".tga")); if (stream == null) { Debug.LogWarning(string.Format("Atlas {0} was not found!", name)); return; } atlas.atlas = TGALoader.LoadTGA(stream, blackIsTransparency); atlases.Add(name, atlas); }
GameObject LoadTGA(string path, Vector3 position) { var bg1 = new GameObject("bg1", typeof(RectTransform)); var rect = bg1.GetComponent <RectTransform>(); bg1.transform.SetParent(canvas.transform); bg1.AddComponent <CanvasRenderer>(); var image = bg1.AddComponent <Image>(); Texture2D tex = TGALoader.LoadTGA(path); bg1.GetComponent <RectTransform>().sizeDelta = new Vector2(tex.width, tex.height); Sprite spr = Sprite.Create(tex, Rect.MinMaxRect(0, 0, tex.width, tex.height), Vector2.zero); image.sprite = spr; rect.anchorMin = new Vector2(0.5f, 0.5f); rect.anchorMax = new Vector2(0.5f, 0.5f); rect.localPosition = position; return(bg1); }
private void OnPointerEnter(PointerEventData x) { try { toolTip.SetActive(true); GameObject obj = x.pointerEnter; MapTeleport mt = obj.GetComponent <MapTeleport>(); RectTransform rw = obj.GetComponent <RectTransform>(); WorldSpawn spawn = mt.spawn; RectTransform rrt = toolTip.GetComponent <RectTransform>(); rrt.anchoredPosition = new Vector3(((spawn.pos.x / 256.0f) * pixelsPerMeter) + rw.sizeDelta.x / 2, ((spawn.pos.z / 256.0f) * pixelsPerMeter) + rw.sizeDelta.y / 2, 0); RawImage ri = toolTip.transform.FindDeepChild("TooltipImage").GetComponent <RawImage>(); Text txt = toolTip.transform.FindDeepChild("SpawnName").GetComponent <Text>(); string img = spawn.imagePath; string nameOnly = Path.GetFileName(img); AssetDatabase adb = AssetDatabaseInst.DB; byte[] data = adb.extractUsingFilename(nameOnly, AssetDatabase.RequestCategory.TEXTURE); if (nameOnly.EndsWith("dds")) { ri.texture = DDSLoader.DatabaseLoaderTexture_DDS.LoadDDS(data); } else if (nameOnly.EndsWith("tga")) { ri.texture = TGALoader.LoadTGA(new MemoryStream(data)); } else { throw new Exception("Unknown texture type:" + nameOnly); } rrt.sizeDelta = new Vector2(ri.texture.width, ri.texture.height); txt.text = spawn.spawnName; } catch (Exception ex) { Debug.LogWarning(ex); toolTip.SetActive(true); } }
public List <Texture2D> LoadTorsoTextures() { string path = Path.Combine(Application.streamingAssetsPath, _characterPrefabName, "Torso"); List <Texture2D> torsoTextures = new List <Texture2D>(); var directoryInfo = new DirectoryInfo(path); var allFiles = directoryInfo.GetFiles("*.*"); foreach (var fileInfo in allFiles) { if (fileInfo.Name.Contains("meta")) { continue; } var bytes = File.ReadAllBytes(fileInfo.FullName); // TGA format is not supported => I have to use wrapper var texture2D = TGALoader.LoadTGA(fileInfo.FullName); torsoTextures.Add(texture2D); } return(torsoTextures); }
// Start is called before the first frame update void Start() { mat = GetComponent <MeshRenderer>().material; MeshFilter mf = GetComponent <MeshFilter>(); string objName = mf.mesh.name.Split(' ')[0]; string path = Application.dataPath + "/objects/" + objName + "/"; string[] lines = File.ReadAllLines(path + objName + ".txt"); List <Vector4> list = new List <Vector4>(); int num = 1; while (true) { Vector4 vec = new Vector4(); if (!ToVector(lines[num], ref vec)) { break; } list.Add(vec); num++; } if (list.Count == 12) { mat.SetVectorArray("texelVector", list.ToArray()); } int imgIdx = 0; while (num < lines.Length) { string imageName = path + lines[num]; Texture2D tex = TGALoader.LoadTGA(imageName); mat.SetTexture("_Tex" + imgIdx, tex); num++; imgIdx++; } }
public static Texture2D LoadTexture2D(string resref) { if (!loadedTextures.ContainsKey(resref)) { Texture2D tex; Stream stream; if (null != (stream = data.GetStream(resref, ResourceType.TPC))) { TPCObject tpc = new TPCObject(stream); tex = new Texture2D(tpc.Width, tpc.Height, tpc.Format, false); tex.LoadRawTextureData(tpc.RawData); tex.Apply(); tex.anisoLevel = ANISO_LEVEL; } else if (null != (stream = data.GetStream(resref, ResourceType.TGA))) { tex = TGALoader.LoadTGA(stream); tex.anisoLevel = ANISO_LEVEL; } else { //Debug.Log("Missing texture: " + resref); return(new Texture2D(1, 1)); } //loadedTextures[resref + "_base"] = tex; //tex = ImageFilter.Upscale(tex); loadedTextures[resref] = tex; } //return NormalGeneration.Diff2Normal(loadedTextures[resref]); return(loadedTextures[resref]); }
public static Texture2D LoadTexture2D(string resref) { Stream stream; if (null != (stream = GetStream(resref, ResourceType.TPC))) { TPCObject tpc = new TPCObject(stream); Texture2D tex = new Texture2D(tpc.Width, tpc.Height, tpc.Format, false); tex.LoadRawTextureData(tpc.RawData); tex.Apply(); return(tex); } else if (null != (stream = GetStream(resref, ResourceType.TGA))) { return(TGALoader.LoadTGA(stream)); } else { //Debug.Log("Missing texture: " + resref); return(new Texture2D(1, 1)); } }
public Texture2D extractUW2Bitmap(string path, int index, bool Alpha) { char[] textureFile; // Pointer to our buffered data (little endian format) //int i; long NoOfTextures; if (File.Exists(BasePath + path.Replace(".", "_") + "\\" + index.ToString("d3") + ".tga")) { return(TGALoader.LoadTGA(BasePath + path.Replace(".", "_") + "\\" + index.ToString("d3") + ".tga")); } if (!DataLoader.ReadStreamFile(BasePath + path, out textureFile)) { return(null); } // Get the size of the file in bytes NoOfTextures = DataLoader.getValAtAddress(textureFile, 0, 8); long textureOffset = (int)DataLoader.getValAtAddress(textureFile, (index * 4) + 6, 32); if (textureOffset != 0) { int compressionFlag = (int)DataLoader.getValAtAddress(textureFile, ((index * 4) + 6) + (NoOfTextures * 4), 32); int isCompressed = (compressionFlag >> 1) & 0x01; if (isCompressed == 1) { int datalen = 0; return(Image(DataLoader.unpackUW2(textureFile, textureOffset, ref datalen), 0, 320, 200, "namehere", GameWorldController.instance.palLoader.Palettes[PaletteIndicesUW2[index]], Alpha)); } else { return(Image(textureFile, textureOffset, 320, 200, "name_goes_here", GameWorldController.instance.palLoader.Palettes[PaletteIndicesUW2[index]], Alpha)); } } return(null); }
private static object DoLoad(string file, string ext) { if (ext == "grf") { return(File.OpenRead(file)); } else { using (var br = ReadSync(file)) { if (br == null) { throw new Exception($"Could not load file: {file}"); } switch (ext) { // Images case "jpg": case "jpeg": case "png": return(new RawImage() { data = br.ToArray() }); case "bmp": return(loader.LoadBMP(br)); case "tga": return(TGALoader.LoadTGA(br)); // Text case "txt": case "xml": case "lua": return(Encoding.UTF8.GetString(br.ToArray())); case "spr": SPR spr = SpriteLoader.Load(br); spr.SwitchToRGBA(); spr.Compile(); spr.filename = file; return(spr); case "str": return(EffectLoader.Load(br, Path.GetDirectoryName(file).Replace("\\", "/"))); case "act": return(ActionLoader.Load(br)); // Binary case "gat": return(AltitudeLoader.Load(br)); case "rsw": return(WorldLoader.Load(br)); case "gnd": return(GroundLoader.Load(br)); case "rsm": return(ModelLoader.Load(br)); // Audio case "wav": WAVLoader.WAVFile wav = WAVLoader.OpenWAV(br.ToArray()); AudioClip clip = AudioClip.Create(file, wav.samples, wav.channels, wav.sampleRate, false); clip.SetData(wav.leftChannel, 0); return(clip); case "mp3": case "ogg": break; case "json": return(JObject.Parse(Encoding.UTF8.GetString(br.ToArray()))); default: throw new Exception($"Unsuported file format: {ext} for file {file}"); } } } return(null); }
public static Texture2D LoadTexture(string path) { if (Path.GetExtension(path).ToLower() == ".tga") { return(TGALoader.LoadTGA(path)); } var bmp = new BMPLoader(); bmp.ForceAlphaReadWhenPossible = false; var img = bmp.LoadBMP(path); if (img == null) { throw new Exception("Failed to load: " + path); } var colors = (Color32[])img.imageData.Clone(); var width = img.info.width; var height = img.info.height; //magic pink conversion and transparent color expansion for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var count = 0; var r = 0; var g = 0; var b = 0; if (x + y * width >= colors.Length) { Debug.LogWarning($"For some reason looking out of bounds on color table on texture {path} w{width} h{height} position {x} {y} ({x + y * width}"); } var color = colors[x + y * width]; //Debug.Log(color); if (color.r < 254 || color.g != 0 || color.b < 254) { continue; } //Debug.Log("OHWOW: " + color); for (var y2 = -1; y2 <= 1; y2++) { for (var x2 = -1; x2 <= 1; x2++) { if (y + y2 < 0 || y + y2 >= height) { continue; } if (x + x2 < 0 || x + x2 >= width) { continue; } var color2 = colors[x + x2 + (y + y2) * width]; if (color2.r >= 254 && color2.g == 0 && color2.b >= 254) { continue; } count++; r += color2.r; g += color2.g; b += color2.b; } } if (count > 0) { var r2 = (byte)Mathf.Clamp(r / count, 0, 255); var g2 = (byte)Mathf.Clamp(g / count, 0, 255); var b2 = (byte)Mathf.Clamp(b / count, 0, 255); //Debug.Log($"{x},{y} - change {color} to {r2},{g2},{b2}"); img.imageData[x + y * width] = new Color32(r2, g2, b2, 0); } else { img.imageData[x + y * width] = new Color32(0, 0, 0, 0); } } } return(img.ToTexture2D()); }
private int ReadPageFile(char[] PageFile, int XX, int YY, int spriteIndex, int AuxPalNo, bool LoadMod, string ModPath) { int addptr = 0; int slotbase = (int)DataLoader.getValAtAddress(PageFile, addptr++, 8); int NoOfSlots = (int)DataLoader.getValAtAddress(PageFile, addptr++, 8); int[] SlotIndices = new int[NoOfSlots]; int spriteCounter = 0; int k = 0; string XXo = DecimalToOct(XX.ToString()); string YYo = DecimalToOct(YY.ToString()); for (int i = 0; i < NoOfSlots; i++) { int val = (int)DataLoader.getValAtAddress(PageFile, addptr++, 8); if (val != 255) { SlotIndices[k++] = i; } } int NoOfSegs = (int)DataLoader.getValAtAddress(PageFile, addptr++, 8); for (int i = 0; i < NoOfSegs; i++) { //string[] AnimFiles = new string[8]; string AnimName = PrintAnimName(slotbase + SlotIndices[i]); int index = TranslateAnimToIndex(slotbase + SlotIndices[i]); AnimInfo.animName[index] = AnimName; int ValidCount = 0; for (int j = 0; j < 8; j++) { int val = (int)DataLoader.getValAtAddress(PageFile, addptr++, 8); if (val != 255) { //AnimFiles[j] = "CR" + XX.ToString("d2") + "PAGE_N" + YY.ToString("d2") + "_" + AuxPalNo + "_" + val; AnimInfo.animSequence[index, j] = "CR" + XXo + "PAGE_N" + YYo + "_" + AuxPalNo + "_" + (val).ToString("d4"); AnimInfo.animIndices[index, j] = (val + spriteIndex); ValidCount++; } else { AnimInfo.animIndices[index, j] = -1; } } } //Read in the palette int NoOfPals = (int)DataLoader.getValAtAddress(PageFile, addptr, 8);//Will skip ahead this far. addptr++; char[] auxPalVal = new char[32]; for (int i = 0; i < 32; i++) { auxPalVal[i] = (char)DataLoader.getValAtAddress(PageFile, (addptr) + (AuxPalNo * 32) + i, 8); } //Skip past the palettes addptr = addptr + NoOfPals * 32; int NoOfFrames = (int)DataLoader.getValAtAddress(PageFile, addptr, 8); //AnimInfo.animSprites=new Sprite[NoOfFrames]; addptr = addptr + 2; int addptr_start = addptr;//Bookmark my positiohn int MaxWidth = 0; int MaxHeight = 0; int MaxHotSpotX = 0; int MaxHotSpotY = 0; for (int pass = 0; pass <= 1; pass++) { addptr = addptr_start; if (pass == 0) {//get the max width and height for (int i = 0; i < NoOfFrames; i++) { int frameOffset = (int)DataLoader.getValAtAddress(PageFile, addptr + (i * 2), 16); int BitMapWidth = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 0, 8); int BitMapHeight = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 1, 8); int hotspotx = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 2, 8); int hotspoty = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 3, 8); if (hotspotx > BitMapWidth) { hotspotx = BitMapWidth; } if (hotspoty > BitMapHeight) { hotspoty = BitMapHeight; } if (BitMapWidth > MaxWidth) { MaxWidth = BitMapWidth; } if (BitMapHeight > MaxHeight) { MaxHeight = BitMapHeight; } if (hotspotx > MaxHotSpotX) { MaxHotSpotX = hotspotx; } if (hotspoty > MaxHotSpotY) { MaxHotSpotY = hotspoty; } } } else { //Extract if (MaxHotSpotX * 2 > MaxWidth) { //Try and center the hot spot in the image. MaxWidth = MaxHotSpotX * 2; } char[] outputImg; outputImg = new char[MaxWidth * MaxHeight * 2]; for (int i = 0; i < NoOfFrames; i++) { int frameOffset = (int)DataLoader.getValAtAddress(PageFile, addptr + (i * 2), 16); int BitMapWidth = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 0, 8); int BitMapHeight = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 1, 8); int hotspotx = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 2, 8); int hotspoty = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 3, 8); int compression = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 4, 8); int datalen = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 5, 16); //Adjust the hotspots from the biggest point back to the image corners int cornerX; int cornerY; cornerX = MaxHotSpotX - hotspotx; cornerY = MaxHotSpotY - hotspoty; if (cornerX <= 0) { cornerX = 0; } else { cornerX = cornerX - 1; } if (cornerY <= 0) { cornerY = 0; } bool ModFileIsLoaded = false; if (LoadMod) { if (File.Exists(ModPath + sep + AuxPalNo + sep + i.ToString("d3") + ".tga")) { Texture2D tex = TGALoader.LoadTGA(ModPath + sep + AuxPalNo + sep + i.ToString("d3") + ".tga"); ModFileIsLoaded = true; AnimInfo.animSprites[spriteIndex + i] = Sprite.Create(tex, new Rect(0f, 0f, tex.width, tex.height), new Vector2(0.5f, 0.0f)); } } if (!ModFileIsLoaded) { //Extract the image char[] srcImg; srcImg = new char[BitMapWidth * BitMapHeight * 2]; outputImg = new char[MaxWidth * MaxHeight * 2]; ArtLoader.ua_image_decode_rle(PageFile, srcImg, compression == 6 ? 5 : 4, datalen, BitMapWidth * BitMapHeight, frameOffset + 7, auxPalVal); //*Put the sprite in the a frame of size max width & height cornerY = MaxHeight - cornerY;//y is from the top left corner int ColCounter = 0; int RowCounter = 0; bool ImgStarted = false; for (int y = 0; y < MaxHeight; y++) { for (int x = 0; x < MaxWidth; x++) { if ((cornerX + ColCounter == x) && (MaxHeight - cornerY + RowCounter == y) && (ColCounter < BitMapWidth) && (RowCounter < BitMapHeight)) {//the pixel from the source image is here ImgStarted = true; outputImg[x + (y * MaxWidth)] = srcImg[ColCounter + (RowCounter * BitMapWidth)]; ColCounter++; } else { outputImg[x + (y * MaxWidth)] = (char)0;//alpha } } if (ImgStarted == true) {//New Row on the src image RowCounter++; ColCounter = 0; } } //Set the heights for output BitMapWidth = MaxWidth; BitMapHeight = MaxHeight; //**************************** Texture2D imgData = ArtLoader.Image(outputImg, 0, BitMapWidth, BitMapHeight, "namehere", pal, true, true); CropImageData(ref imgData, pal); AnimInfo.animSprites[spriteIndex + i] = Sprite.Create(imgData, new Rect(0f, 0f, imgData.width, imgData.height), new Vector2(0.5f, 0.0f)); AnimInfo.animSprites[spriteIndex + i].texture.filterMode = FilterMode.Point; spriteCounter++; } } }//endextract } return(spriteCounter); }
private static object DoLoad(string file, string ext) { //string fileWOExt = file.Replace("." + ext, ""); switch (ext) { case "grf": return(File.OpenRead(file)); // Regular images files case "jpg": case "jpeg": case "png": using (var br = ReadSync(file)) { return(new RawImage() { data = br.ToArray() }); } case "bmp": using (var br = ReadSync(file)) return(loader.LoadBMP(br)); case "tga": using (var br = ReadSync(file)) return(TGALoader.LoadTGA(br)); // Texts case "txt": case "xml": case "lua": using (var br = ReadSync(file)) { if (br != null) { return(Encoding.UTF8.GetString(br.ToArray())); } else { return(null); } } case "spr": using (var br = ReadSync(file)) { if (br != null) { SPR spr = SpriteLoader.Load(br); spr.SwitchToRGBA(); spr.Compile(); spr.filename = file; return(spr); } else { return(null); } } case "str": using (var br = ReadSync(file)) { if (br != null) { STR str = EffectLoader.Load(br); return(str); } else { return(null); } } // Binary case "gat": using (var br = ReadSync(file)) return(new Altitude(br)); case "rsw": using (var br = ReadSync(file)) return(WorldLoader.Load(br)); case "gnd": using (var br = ReadSync(file)) return(GroundLoader.Load(br)); case "rsm": using (var br = ReadSync(file)) return(ModelLoader.Load(br)); // Audio case "wav": using (var br = ReadSync(file)) { WAVLoader.WAVFile wav = WAVLoader.OpenWAV(br.ToArray()); AudioClip clip = AudioClip.Create(file, wav.samples, wav.channels, wav.sampleRate, false); clip.SetData(wav.leftChannel, 0); return(clip); } case "mp3": case "ogg": case "act": //return new Action(ReadSync(file)).compile(); Debug.LogWarning("Can't read " + file + "\nLoader for " + ext + " is not implemented"); break; default: throw new System.Exception("Unknown file format: " + file); } return(null); }
/// <summary> /// Loads the image at index. /// </summary> /// <returns>The <see cref="UnityEngine.Texture2D"/>.</returns> /// <param name="index">Index.</param> /// <param name="palToUse">Pal to use.</param> /// If the index is greater than 209 I return a floor texture. public Texture2D LoadImageAt(int index, Palette palToUse) { if (_RES == GAME_UWDEMO) { //Point the UW1 texture files to the demo files TextureSplit = 48; pathTexW_UW1 = pathTexW_UW0; pathTexF_UW1 = pathTexF_UW0; } if (_RES == GAME_UW2) { FloorDim = 64; } switch (_RES) { case GAME_SHOCK: { if (texturesFLoaded == false) { if (!DataLoader.ReadStreamFile(BasePath + pathTex_SS1, out texturebufferT)) { return(base.LoadImageAt(index)); } else { texturesFLoaded = true; } } //Load the chunk requested //For textures this is index + 1000 DataLoader.Chunk art_ark; if (DataLoader.LoadChunk(texturebufferT, index + 1000, out art_ark)) { switch (art_ark.chunkContentType) { case 2: case 17: { long textureOffset = (int)DataLoader.getValAtAddress(art_ark.data, 2 + (0 * 4), 32); int CompressionType = (int)DataLoader.getValAtAddress(art_ark.data, textureOffset + 4, 16); int Width = (int)DataLoader.getValAtAddress(art_ark.data, textureOffset + 8, 16); int Height = (int)DataLoader.getValAtAddress(art_ark.data, textureOffset + 10, 16); if ((Width > 0) && (Height > 0)) { if (CompressionType == 4) { //compressed char[] outputImg; // UncompressBitmap(art_ark+textureOffset+BitMapHeaderSize, outputImg,Height*Width); UncompressBitmap(art_ark.data, textureOffset + BitMapHeaderSize, out outputImg, Height * Width); return(Image(outputImg, 0, Width, Height, "namehere", palToUse, true)); } else { //Uncompressed return(Image(art_ark.data, textureOffset + BitMapHeaderSize, Width, Height, "namehere", palToUse, true)); } } else { return(base.LoadImageAt(index)); } } //break; } } return(base.LoadImageAt(index)); } case GAME_UW2: { if (LoadMod) { if (File.Exists(ModPathW + "\\" + index.ToString("d3") + ".tga")) { return(TGALoader.LoadTGA(ModPathW + "\\" + index.ToString("d3") + ".tga")); } } if (texturesFLoaded == false) { if (!DataLoader.ReadStreamFile(BasePath + pathTex_UW2, out texturebufferT)) { return(base.LoadImageAt(index)); } else { texturesFLoaded = true; } } long textureOffset = DataLoader.getValAtAddress(texturebufferT, ((index) * 4) + 4, 32); return(Image(texturebufferT, textureOffset, FloorDim, FloorDim, "name_goes_here", palToUse, false)); } case GAME_UWDEMO: case GAME_UW1: default: { if (index < TextureSplit) { //Wall textures if (texturesWLoaded == false) { if (!DataLoader.ReadStreamFile(BasePath + pathTexW_UW1, out texturebufferW)) { return(base.LoadImageAt(index)); } else { texturesWLoaded = true; } } if (LoadMod) { if (File.Exists(ModPathW + "\\" + index.ToString("d3") + ".tga")) { return(TGALoader.LoadTGA(ModPathW + "\\" + index.ToString("d3") + ".tga")); } } long textureOffset = DataLoader.getValAtAddress(texturebufferW, (index * 4) + 4, 32); return(Image(texturebufferW, textureOffset, 64, 64, "name_goes_here", palToUse, false)); } else { //Floor textures (to match my list of textures) if (texturesFLoaded == false) { if (!DataLoader.ReadStreamFile(BasePath + pathTexF_UW1, out texturebufferF)) { return(base.LoadImageAt(index)); } else { texturesFLoaded = true; } } if (LoadMod) { if (File.Exists(ModPathF + "\\" + index.ToString("d3") + ".tga")) { return(TGALoader.LoadTGA(ModPathF + "\\" + index.ToString("d3") + ".tga")); } } long textureOffset = DataLoader.getValAtAddress(texturebufferF, ((index - TextureSplit) * 4) + 4, 32); return(Image(texturebufferF, textureOffset, FloorDim, FloorDim, "name_goes_here", palToUse, false)); } } //end switch } }
void ReadFile(BinaryReader reader) { var header = file.Read <WZItemHeader>(reader); if (header.nType == 3) { reader.ReadBytes(44); } if (header.nFaces > 1000 || header.nVertices > 1000) { Debug.LogError("Error Reading ITM FILE!"); return; } List <Vector3> vertices = new List <Vector3>(); List <Vector2> uvs = new List <Vector2>(); //SortedDictionary<int, Vector2> uvs = new SortedDictionary<int, Vector2>(); Dictionary <int, List <int> > subMeshesTriangles = new Dictionary <int, List <int> >(); if (header.nType > 1) { List <D3DWizFaceSmall> LstFaces = new List <D3DWizFaceSmall>(); for (int i = 0; i < header.nVertices; i++) { D3DWizVertexSmall vertex = file.Read <D3DWizVertexSmall>(reader); vertices.Add(new Vector3(vertex.x, vertex.y, vertex.z)); uvs.Add(new Vector2(0, 0)); } for (int i = 0; i < header.nFaces; i++) { D3DWizFaceSmall face = file.Read <D3DWizFaceSmall>(reader); LstFaces.Add(face); } LstFaces = LstFaces.OrderBy(x => x.btMaterial).ToList(); foreach (var face in LstFaces) { if (!subMeshesTriangles.ContainsKey(face.btMaterial)) { subMeshesTriangles.Add(face.btMaterial, new List <int>()); } var shVertex1 = new Vector2(face.ftu1, -face.ftv1); var shVertex2 = new Vector2(face.ftu2, -face.ftv2); var shVertex3 = new Vector2(face.ftu3, -face.ftv3); var InitVector2 = new Vector2(0, 0); var idxVertex1 = 0; var idxVertex2 = 0; var idxVertex3 = 0; if (uvs[face.shVertex1] == InitVector2) { uvs[face.shVertex1] = shVertex1; idxVertex1 = face.shVertex1; } else if (uvs[face.shVertex1] != shVertex1) { vertices.Add(vertices[face.shVertex1]); uvs.Add(shVertex1); idxVertex1 = vertices.Count - 1; } else { idxVertex1 = face.shVertex1; } if (uvs[face.shVertex2] == InitVector2) { uvs[face.shVertex2] = shVertex2; idxVertex2 = face.shVertex2; } else if (uvs[face.shVertex2] != shVertex2) { vertices.Add(vertices[face.shVertex2]); uvs.Add(shVertex2); idxVertex2 = vertices.Count - 1; } else { idxVertex2 = face.shVertex2; } if (uvs[face.shVertex3] == InitVector2) { uvs[face.shVertex3] = shVertex3; idxVertex3 = face.shVertex3; } else if (uvs[face.shVertex3] != shVertex3) { vertices.Add(vertices[face.shVertex3]); uvs.Add(shVertex3); idxVertex3 = vertices.Count - 1; } else { idxVertex3 = face.shVertex3; } subMeshesTriangles[face.btMaterial].AddRange(new List <int>() { idxVertex1, idxVertex2, idxVertex3 }); } } else { List <D3DWizFace> LstFaces = new List <D3DWizFace>(); for (int i = 0; i < header.nVertices; i++) { D3DWizVertex vertex = file.Read <D3DWizVertex>(reader); vertices.Add(new Vector3(vertex.x, vertex.y, vertex.z)); uvs.Add(new Vector2(0, 0)); } for (int i = 0; i < header.nFaces; i++) { D3DWizFace face = file.Read <D3DWizFace>(reader); LstFaces.Add(face); } LstFaces = LstFaces.OrderBy(x => x.nMaterial).ToList(); foreach (var face in LstFaces) { if (!subMeshesTriangles.ContainsKey((int)face.nMaterial)) { subMeshesTriangles.Add((int)face.nMaterial, new List <int>()); } var nVertex1 = new Vector2(face.ftu1, -face.ftv1); var nVertex2 = new Vector2(face.ftu2, -face.ftv2); var nVertex3 = new Vector2(face.ftu3, -face.ftv3); var InitVector2 = new Vector2(0, 0); var idxVertex1 = 0; var idxVertex2 = 0; var idxVertex3 = 0; if (uvs[(int)face.nVertex1] == InitVector2) { uvs[(int)face.nVertex1] = nVertex1; idxVertex1 = (int)face.nVertex1; } else if (uvs[(int)face.nVertex1] != nVertex1) { vertices.Add(vertices[(int)face.nVertex1]); uvs.Add(nVertex1); idxVertex1 = vertices.Count - 1; } else { idxVertex1 = (int)face.nVertex1; } if (uvs[(int)face.nVertex2] == InitVector2) { uvs[(int)face.nVertex2] = nVertex2; idxVertex2 = (int)face.nVertex2; } else if (uvs[(int)face.nVertex2] != nVertex2) { vertices.Add(vertices[(int)face.nVertex2]); uvs.Add(nVertex2); idxVertex2 = vertices.Count - 1; } else { idxVertex2 = (int)face.nVertex2; } if (uvs[(int)face.nVertex3] == InitVector2) { uvs[(int)face.nVertex3] = nVertex3; idxVertex3 = (int)face.nVertex3; } else if (uvs[(int)face.nVertex3] != nVertex3) { vertices.Add(vertices[(int)face.nVertex3]); uvs.Add(nVertex3); idxVertex3 = vertices.Count - 1; } else { idxVertex3 = (int)face.nVertex3; } subMeshesTriangles[(int)face.nMaterial].AddRange(new List <int>() { idxVertex1, idxVertex2, idxVertex3 }); } } var NumberOfMaterials = reader.ReadUInt16(); D3DWizMaterialSmall mat1 = file.Read <D3DWizMaterialSmall>(reader); if (mat1.btType == 4) { var w8Unity = Wizardry8Unity.Instance; for (int i = 1; i < NumberOfMaterials; i++) { var itemMaterial = new Material(Shader.Find("Standard")); D3DWizMaterial mat = file.Read <D3DWizMaterial>(reader); if (mat.TextureFile == "") { Debug.Log("Material TextureFilename Empty: "); Debug.Log(mat.Name); Debug.Log(mat.TextureFile); itemMaterial.SetColor("_Color", new Color(mat.rDiffuse, mat.gDiffuse, mat.bDiffuse, mat.aDiffuse)); // continue; } else { var str = @"ITEMS3D\BITMAPS\" + mat.TextureFile.ToUpper(); var data = w8Unity.ContentReader.DataFileReader.GetFile(str); if (mat.f2 != 1) //IFL FIle { Debug.Log("ifl Texture - Not Animating Yet!"); var firstTGAFile = ""; using (StreamReader file = new StreamReader(new MemoryStream(data))) { string line; while ((line = file.ReadLine()) != null) { firstTGAFile = line; break; } file.Close(); } str = @"ITEMS3D\BITMAPS\" + firstTGAFile.ToUpper(); data = w8Unity.ContentReader.DataFileReader.GetFile(str); } var texture = TGALoader.LoadTGA(data); itemMaterial.mainTexture = texture; } itemMaterial.SetFloat("_SmoothnessTextureChannel", 1); itemMaterial.SetFloat("_Metallic", 0); itemMaterial.SetFloat("_Glossiness", 1); itemMaterial.SetOverrideTag("RenderType", ""); itemMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); itemMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); itemMaterial.SetInt("_ZWrite", 1); itemMaterial.DisableKeyword("_ALPHATEST_ON"); itemMaterial.DisableKeyword("_ALPHABLEND_ON"); itemMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON"); itemMaterial.renderQueue = -1; itemMaterial.SetColor("_EmissionColor", new Color(mat.rEmissive, mat.gEmissive, mat.bEmissive, mat.aEmissive)); itemMaterial.name = mat.Name; this.itemMaterials.Add(itemMaterial); } } else { var w8Unity = Wizardry8Unity.Instance; for (int i = 1; i < NumberOfMaterials; i++) { var itemMaterial = new Material(Shader.Find("Standard")); D3DWizMaterialSmall mat = file.Read <D3DWizMaterialSmall>(reader); if (mat.TextureFile == "") { Debug.Log("Material TextureFilename Empty: "); Debug.Log(mat.Name); Debug.Log(mat.TextureFile); itemMaterial.SetColor("_Color", new Color(mat.rDiffuse, mat.gDiffuse, mat.bDiffuse, mat.aDiffuse)); // continue; } else { var str = @"ITEMS3D\BITMAPS\" + mat.TextureFile.ToUpper(); var data = w8Unity.ContentReader.DataFileReader.GetFile(str); if (mat.f2 != 1) { Debug.LogError("ifl!"); } var texture = TGALoader.LoadTGA(data); itemMaterial.mainTexture = texture; } itemMaterial.SetColor("_EmissionColor", new Color(mat.rEmissive, mat.gEmissive, mat.bEmissive, mat.aEmissive)); itemMaterial.name = mat.Name; this.itemMaterials.Add(itemMaterial); } } itemMesh = new Mesh(); itemMesh.name = this.itemName; itemMesh.vertices = vertices.ToArray();; // vertices.ToArray(); itemMesh.uv = uvs.ToArray();; // vertices.ToArray(); itemMesh.subMeshCount = NumberOfMaterials - 1; foreach (var subm in subMeshesTriangles.Keys) { itemMesh.SetTriangles(subMeshesTriangles[subm], subm - 1); } // itemMesh.RecalculateNormals(); UnityEngine.Debug.Log("finish"); }