public static Texture2D MakePixel(Color color) { Texture2D tex = new Texture2D(1, 1, TextureFormat.RGBA32, false); tex.SetPixel(0, 0, color); tex.Apply(); return tex; }
// Loads a texture public static Texture2D LoadTexture(string path, bool compress, bool upload, bool unreadable) { Texture2D map = null; path = Directory.GetCurrentDirectory() + "/GameData/" + path; if (File.Exists(path)) { bool uncaught = true; try { if (path.ToLower().EndsWith(".dds")) { // Borrowed from stock KSP 1.0 DDS loader (hi Mike!) // Also borrowed the extra bits from Sarbian. BinaryReader binaryReader = new BinaryReader(File.OpenRead(path)); uint num = binaryReader.ReadUInt32(); if (num == DDSHeaders.DDSValues.uintMagic) { DDSHeaders.DDSHeader dDSHeader = new DDSHeaders.DDSHeader(binaryReader); if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10) { new DDSHeaders.DDSHeaderDX10(binaryReader); } bool alpha = (dDSHeader.dwFlags & 0x00000002) != 0; bool fourcc = (dDSHeader.dwFlags & 0x00000004) != 0; bool rgb = (dDSHeader.dwFlags & 0x00000040) != 0; bool alphapixel = (dDSHeader.dwFlags & 0x00000001) != 0; bool luminance = (dDSHeader.dwFlags & 0x00020000) != 0; bool rgb888 = dDSHeader.ddspf.dwRBitMask == 0x000000ff && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x00ff0000; //bool bgr888 = dDSHeader.ddspf.dwRBitMask == 0x00ff0000 && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x000000ff; bool rgb565 = dDSHeader.ddspf.dwRBitMask == 0x0000F800 && dDSHeader.ddspf.dwGBitMask == 0x000007E0 && dDSHeader.ddspf.dwBBitMask == 0x0000001F; bool argb4444 = dDSHeader.ddspf.dwABitMask == 0x0000f000 && dDSHeader.ddspf.dwRBitMask == 0x00000f00 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x0000000f; bool rbga4444 = dDSHeader.ddspf.dwABitMask == 0x0000000f && dDSHeader.ddspf.dwRBitMask == 0x0000f000 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x00000f00; bool mipmap = (dDSHeader.dwCaps & DDSHeaders.DDSPixelFormatCaps.MIPMAP) != (DDSHeaders.DDSPixelFormatCaps)0u; bool isNormalMap = ((dDSHeader.ddspf.dwFlags & 524288u) != 0u || (dDSHeader.ddspf.dwFlags & 2147483648u) != 0u); if (fourcc) { if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT1) { map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT1, mipmap); map.LoadRawTextureData(LoadRestOfReader(binaryReader)); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT3) { map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap); map.LoadRawTextureData(LoadRestOfReader(binaryReader)); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT5) { map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT5, mipmap); map.LoadRawTextureData(LoadRestOfReader(binaryReader)); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT2) { Debug.Log("[Kopernicus]: DXT2 not supported" + path); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT4) { Debug.Log("[Kopernicus]: DXT4 not supported: " + path); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10) { Debug.Log("[Kopernicus]: DX10 dds not supported: " + path); } else fourcc = false; } if (!fourcc) { TextureFormat textureFormat = TextureFormat.ARGB32; bool ok = true; if (rgb && (rgb888 /*|| bgr888*/)) { // RGB or RGBA format textureFormat = alphapixel ? TextureFormat.RGBA32 : TextureFormat.RGB24; } else if (rgb && rgb565) { // Nvidia texconv B5G6R5_UNORM textureFormat = TextureFormat.RGB565; } else if (rgb && alphapixel && argb4444) { // Nvidia texconv B4G4R4A4_UNORM textureFormat = TextureFormat.ARGB4444; } else if (rgb && alphapixel && rbga4444) { textureFormat = TextureFormat.RGBA4444; } else if (!rgb && alpha != luminance) { // A8 format or Luminance 8 textureFormat = TextureFormat.Alpha8; } else { ok = false; Debug.Log("[Kopernicus]: Only DXT1, DXT5, A8, RGB24, RGBA32, RGB565, ARGB4444 and RGBA4444 are supported"); } if (ok) { map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap); map.LoadRawTextureData(LoadRestOfReader(binaryReader)); } } if (map != null) if (upload) map.Apply(false, unreadable); } else Debug.Log("[Kopernicus]: Bad DDS header."); } else { map = new Texture2D(2, 2); byte[] data = LoadWholeFile(path); if (data == null) throw new Exception("LoadWholeFile failed"); map.LoadImage(data); if (compress) map.Compress(true); if (upload) map.Apply(false, unreadable); } } catch (Exception ex) { uncaught = false; Debug.Log("[Kopernicus]: failed to load " + path + " with exception " + ex.Message); } if (map == null && uncaught) { Debug.Log("[Kopernicus]: failed to load " + path); } map.name = path.Remove(0, (KSPUtil.ApplicationRootPath + "GameData/").Length); } else Debug.Log("[Kopernicus]: texture does not exist! " + path); return map; }
private void OnGUI() { if (Selection.activeGameObject == null) { return; } var selection = Selection.activeGameObject.GetComponent <VoxelMap> (); if (selection != null) { //窗口在屏幕中的位置,GUI定位与窗口没有直接关系 Rect viewPort = new Rect(0, 0, position.width - 5, position.height - 5); //内容物的尺寸,长度是两个偏移加上图片大小和说明大小 var contentSize = new Rect(0, 0, columnWidth + offset * 2 + imgSize, (imgSize + offset) * selection.allBlocks.Count); //开始滚动GUI scrollPosition = GUI.BeginScrollView(viewPort, scrollPosition, contentSize); for (int i = 0; i < selection.allBlocks.Count; i++) { if (selection.allBlocks [i].m_gameobject == null) { EditorGUILayout.HelpBox("你缺少对GameObject(序号 " + i + ")的赋值\nyou loss the reference of gameobject " + i, MessageType.Warning); continue; } //绘制缩略图 EditorGUI.DrawPreviewTexture(new Rect(offset, i * (imgSize + offset), imgSize, imgSize), AssetPreview.GetAssetPreview(selection.allBlocks [i].m_gameobject)); GUILayout.BeginArea(new Rect(offset * 2 + imgSize, i * (imgSize + offset), columnWidth, imgSize)); EditorGUILayout.BeginHorizontal(); EditorGUILayout.ObjectField( selection.allBlocks [i].m_name + " " + selection.allBlocks [i].BlockType, selection.allBlocks [i].m_gameobject, typeof(GameObject), false ); selection.allBlocks [i].m_tag = EditorGUILayout.TagField(selection.allBlocks [i].m_tag); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("当前方块类型:" + selection.allBlocks [i].BlockType); blockType = (BlockType)EditorGUILayout.EnumPopup("重新选择方块类型:", blockType); if (GUILayout.Button("确定修改")) { selection.allBlocks [i].BlockType = blockType; Debug.Log("change block" + selection.allBlocks [i].m_name + " type to " + selection.allBlocks [i].BlockType); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("请注意,重新打开Unity会导致类型失效,请重新手动确保当前方块类型正确"); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); //获取单一方块的网格数据 Vector3 blockSize = selection.allBlocks [i].m_gameobject.GetComponentInChildren <MeshFilter> ().sharedMesh.bounds.size; EditorGUILayout.LabelField("Size : " + blockSize.x.ToString() + " x " + blockSize.y.ToString() + " x " + blockSize.z.ToString()); EditorGUILayout.EndHorizontal(); GUILayout.EndArea(); } //绘制颜色 Texture2D boxTex = new Texture2D(1, 1); boxTex.SetPixel(0, 0, new Color(0, 0.5f, 1f, 0.4f)); boxTex.Apply(); //加入自定义皮肤 var style = new GUIStyle(GUI.skin.customStyles [0]); style.normal.background = boxTex; //绘制被选中的显示 if (selection.blockID != -1) { GUI.Box(new Rect(imgSize + offset * 2, selection.blockID * (imgSize + offset), columnWidth, imgSize + offset), "", style); } //鼠标点击确定选中的方块ID Event cEvent = Event.current; Vector2 mousePos = new Vector2(cEvent.mousePosition.x, cEvent.mousePosition.y); if (cEvent.type == EventType.MouseDown && cEvent.button == 0) { int order = (int)Mathf.Floor(mousePos.y / (imgSize + offset)); if (order <= selection.allBlocks.Count) { selection.blockID = order; } else { selection.blockID = -1; } Debug.Log("selection.blockID : " + selection.blockID); Repaint(); } GUI.EndScrollView(); } }
unsafe List <(Texture2D, int)> LoadAnimation(string loadPath) { List <ValueTuple <Texture2D, int> > ret = new List <ValueTuple <Texture2D, int> >(); TextAsset textasset = Resources.Load <TextAsset>(loadPath); byte[] bytes = textasset.bytes; WebPAnimDecoderOptions option = new WebPAnimDecoderOptions { use_threads = 1, color_mode = WEBP_CSP_MODE.MODE_RGBA }; Demux.WebPAnimDecoderOptionsInit(ref option); fixed(byte *p = bytes) { IntPtr ptr = (IntPtr)p; WebPData webpdata = new WebPData { bytes = ptr, size = new UIntPtr((uint)bytes.Length) }; IntPtr dec = Demux.WebPAnimDecoderNew(ref webpdata, ref option); WebPAnimInfo anim_info = new WebPAnimInfo(); Demux.WebPAnimDecoderGetInfo(dec, ref anim_info); Debug.LogWarning($"{anim_info.frame_count} {anim_info.canvas_width}/{anim_info.canvas_height}"); int size = anim_info.canvas_width * 4 * anim_info.canvas_height; IntPtr unmanagedPointer = new IntPtr(); int timestamp = 0; for (int i = 0; i < anim_info.frame_count; ++i) { int result = Demux.WebPAnimDecoderGetNext(dec, ref unmanagedPointer, ref timestamp); int lWidth = anim_info.canvas_width; int lHeight = anim_info.canvas_height; bool lMipmaps = false; bool lLinear = false; Texture2D texture = new Texture2D(lWidth, lHeight, TextureFormat.RGBA32, lMipmaps, lLinear); texture.LoadRawTextureData(unmanagedPointer, size); {// Flip updown. // ref: https://github.com/netpyoung/unity.webp/issues/18 // ref: https://github.com/webmproject/libwebp/blob/master/src/demux/anim_decode.c#L309 Color[] pixels = texture.GetPixels(); Color[] pixelsFlipped = new Color[pixels.Length]; for (int y = 0; y < anim_info.canvas_height; y++) { Array.Copy(pixels, y * anim_info.canvas_width, pixelsFlipped, (anim_info.canvas_height - y - 1) * anim_info.canvas_width, anim_info.canvas_width); } texture.SetPixels(pixelsFlipped); } texture.Apply(); ret.Add((texture, timestamp)); } Demux.WebPAnimDecoderReset(dec); Demux.WebPAnimDecoderDelete(dec); } return(ret); }
void createGraph() { Vector3 rgb; if (currentRecords.Count > 0) { rgb = hsb2rgb(currentRecords [0].color); } else { rgb = new Vector3(1f, 1f, 1f); } Vector3 center = new Vector3(0f, 1f, 0f); GameObject c = createSphere("center_node", center, transform); c.GetComponent <Renderer> ().material.color = new Color(rgb.x, rgb.y, rgb.z, 1f); c.transform.localScale *= 2f; HashSet <string> names = new HashSet <string> (); foreach (Ingredient i in currentIngredients) { names.Add(i.name); } Vector3[] points = pointsOnSphere(workspace.GetComponent <Data> ().ingredients.Count); int counter = 0; foreach (Ingredient i in workspace.GetComponent <Data> ().ingredients) { if (names.Contains(i.name)) { continue; } HashSet <Ingredient> cur_copy = new HashSet <Ingredient> (currentIngredients); cur_copy.Add(i); if (dict [cur_copy].Count > 0) { Experiment e = dict [cur_copy] [0]; Vector3 rand = Random.insideUnitSphere.normalized; rand = points [counter] * radius; counter++; Vector3 pos = rand * 0.8f + center; GameObject node; if (i.tool) { node = createCube(i.name, pos, c.transform); } else { node = createSphere(i.name, pos, c.transform); } GameObject label = createLabel(i.name, pos, c.transform, dict [cur_copy].Count); node.tag = "Node"; GameObject edge = createEdge("edge_to_" + e.experiment_id, center, pos, c.transform); edge.GetComponent <Renderer> ().material.color = Color.green; Texture2D texture = new Texture2D(dict [cur_copy].Count, 1, TextureFormat.ARGB32, false); for (int j = 0; j < dict [cur_copy].Count; j++) { Experiment ex = dict [cur_copy] [j]; rgb = hsb2rgb(ex.color); Data d = GameObject.Find("Workspace").GetComponent <Data> (); Color eColor = Color.white; if (d.cleanedActivityToColor.ContainsKey(d.cleanActivity(ex.activity))) { eColor = d.cleanedActivityToColor [d.cleanActivity(ex.activity)]; } print(eColor.r + ", " + eColor.g + ", " + eColor.b); texture.SetPixel(j, 0, eColor); } texture.Apply(); node.GetComponent <Renderer> ().material.mainTexture = texture; } } foreach (Ingredient i in currentIngredients) { HashSet <Ingredient> cur_copy = new HashSet <Ingredient> (currentIngredients); cur_copy.Remove(i); if (dict [cur_copy].Count > 0) { Experiment e = dict [cur_copy] [0]; Vector3 rand = Random.insideUnitSphere.normalized; rand = points [counter] * radius; counter++; Vector3 pos = rand * 0.8f + center; GameObject node; if (i.tool) { node = createCube(i.name, pos, c.transform); } else { node = createSphere(i.name, pos, c.transform); } node.tag = "R_Node"; GameObject label = createLabel(i.name, pos, c.transform, dict [cur_copy].Count); GameObject edge = createEdge("edge_to_" + e.experiment_id, center, pos, c.transform); edge.GetComponent <Renderer> ().material.color = Color.red; Texture2D texture = new Texture2D(dict [cur_copy].Count, 1, TextureFormat.ARGB32, false); for (int j = 0; j < dict [cur_copy].Count; j++) { Experiment ex = dict [cur_copy] [j]; rgb = hsb2rgb(ex.color); Data d = GameObject.Find("Workspace").GetComponent <Data> (); Color eColor = Color.white; if (d.cleanedActivityToColor.ContainsKey(d.cleanActivity(ex.activity))) { eColor = d.cleanedActivityToColor [d.cleanActivity(ex.activity)]; } print(eColor.r + ", " + eColor.g + ", " + eColor.b); texture.SetPixel(j, 0, eColor); } texture.Apply(); node.GetComponent <Renderer> ().material.mainTexture = texture; } } GetComponent <GraphEventHandler> ().newGraph(); }
void Update() { // Read the FFT spectrum = GetComponent<AudioSource>().GetSpectrumData(1024, 0, FFTWindow.BlackmanHarris); var average = 0f; for (int i = 0; i < spectrum.Length; i++) { average += spectrum[i]; } average /= spectrum.Length; intensityAverage[intensityIndex++ % intensityAverage.Length] = average; var a = 0f; for (int i = 0; i < intensityAverage.Length; i++) { var hertz = (1f / 1024f) * (44100f / 2f); a = Mathf.Max(a, intensityAverage[i] * Mathf.Log(hertz, 2)); } a /= intensityAverage.Length; a *= 100000f; if (isRecording) { if (a < Off) { isRecording = false; if(frame - frameStart > 8) { print("end, total frames: " + (frame - frameStart) ); RunNeuralNetwork(); } } } else { if (a > On) { isRecording = true; frameStart = frame; // print("start"); for (int i = 0; i < RawData.Length; i++) { RawData[i] = 0; } writeToRaw = 0; } } frame++; if (isRecording) { x++; for (int y = 0; y < texture.height; y++) { float added = 0; for (int i = 0; i < (1024 / Vertical); i++) { added += spectrum[y * (1024 / Vertical) + i]; } added /= (1024 / Vertical); float db = added * 100; // float db = spectrum[y] * 100; var r = db * 10; var g = Mathf.Max(0, db * 10 - 1); var b = Mathf.Max(0, db * 10 - 2); Color color = new Color(r, g, b); texture.SetPixel(x, y, color); if (writeToRaw < RawData.Length) { RawData[writeToRaw] = added * 1000; } writeToRaw++; // if (isRecording && frame < Horizontal) // { // for (int i = 0; i < Vertical; i++) // { // RawData[frame * Vertical + i] = spectrum[i] * 100; // } // } } } // if (isRecording) // { // x++; // for (int y = 0; y < texture.height; y++) // { // float db = spectrum[y] * 100; // var r = db * 10; // var g = Mathf.Max(0, db * 10 - 1); // var b = Mathf.Max(0, db * 10 - 2); // Color color = new Color(r, g, b); // texture.SetPixel(x, y, color); // } // } texture.Apply(); }
public override void drawRight(TextureEditGUI gui) { if (BitmapDecalCache.Instance.monoSheets.Count == 0) return; Color contentColor = GUI.contentColor; GUI.backgroundColor = Global.BackgroundColor; _scrollPos = GUILayout.BeginScrollView(_scrollPos, GUI.skin.box, GUILayout.MinWidth(250), GUILayout.ExpandHeight(true)); GUILayout.Label("Decal Sheets"); GUILayout.Space(3); int oldSelectedSheet = _selectedSheet; for (int i = 0; i < BitmapDecalCache.Instance.monoSheets.Count; ++i) { if (i == _selectedSheet) GUI.contentColor = Global.SelectedColor; else GUI.contentColor = Global.NotSelectedColor; if (GUILayout.Button(BitmapDecalCache.Instance.monoSheets[i].displayName, GUILayout.ExpandWidth(true))) _selectedSheet = i; } if (_selectedSheet != oldSelectedSheet) { if (_textures != null) { for (int i = 0; i < _textures.Count; ++i) { UnityEngine.Object.Destroy(_textures[i]); } _textures = null; } if (_selectedDecal >= BitmapDecalCache.Instance.monoSheets[_selectedSheet].decals.Count) _selectedDecal = 0; } GUILayout.Space(10); GUILayout.Label("Decals"); GUILayout.Space(3); if (_textures == null) { _textures = new List<Texture2D>(); for (int i = 0; i < BitmapDecalCache.Instance.monoSheets[_selectedSheet].decals.Count; ++i) { Image image = new Image(BitmapDecalCache.Instance.monoSheets[_selectedSheet].decals[i].image); image.recolor(Global.Black32, Global.White32, false, false); Texture2D texture = new Texture2D(image.width, image.height, TextureFormat.ARGB32, false); texture.SetPixels32(image.pixels); texture.Apply(); _textures.Add(texture); } } int oldSelectedDecal = _selectedDecal; int x = 0; GUILayout.BeginHorizontal(); for (int i = 0; i < _textures.Count; ++i) { if (i == _selectedDecal) { GUI.backgroundColor = Color.yellow; if (GUILayout.Button(_textures[i], GUILayout.Width(_textures[i].width + 4), GUILayout.Height(_textures[i].height + 4))) _selectedDecal = i; GUI.backgroundColor = Global.BackgroundColor; } else { if (GUILayout.Button(_textures[i], GUILayout.Width(_textures[i].width + 4), GUILayout.Height(_textures[i].height + 4))) _selectedDecal = i; } x += _textures[i].width + 5; if (i < (_textures.Count - 1)) { if (x > 0 && (x + _textures[i+1].width) > 200) { GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); x = 0; } } } GUILayout.EndHorizontal(); GUILayout.EndScrollView(); GUI.contentColor = contentColor; if (oldSelectedSheet != _selectedSheet || oldSelectedDecal != _selectedDecal) { _imBitmapMonoDecal._url = BitmapDecalCache.Instance.monoSheets[_selectedSheet].decals[_selectedDecal].url; gui.setRemakePreview(); } }
public static Texture2D GenerateTextureFromHeightMap(TerrainHeightMap heightMap) { Texture2D tex = new Texture2D(TerrainChunkObject.TERRAIN_CHUNK_TEXTURE_RESOLUTION_SIZE, TerrainChunkObject.TERRAIN_CHUNK_TEXTURE_RESOLUTION_SIZE); tex.filterMode = FilterMode.Point; for (int x = 0; x < tex.width; x++) { for (int y = 0; y < tex.height; y++) { Color c = new Color(); if (heightMap.GetFloat(x, y) > heightMap.highestFloat * 0.8f) { c = Color.white; } else if (heightMap.GetFloat(x, y) > heightMap.highestFloat * 0.65f) { c = new Color(0.65f, 0.65f, 0.65f); } else if (heightMap.GetFloat(x, y) < heightMap.highestFloat * 0.45f) { c = Color.blue; } else { c = Color.green; } c *= heightMap.GetFloat(x, y) / heightMap.totalStrength; tex.SetPixel(x, y, c); } } tex.Apply(); return tex; }
public void OnGUI() { if (wallpaper == null) { wallpaper = new Texture2D(1, 1, TextureFormat.RGBA32, false); wallpaper.SetPixel(0, 0, new Color(0.25f, 0.25f, 0.4f));//dark StrataCullerBlue wallpaper.Apply(); } GUI.DrawTexture(new Rect(0, 0, position.width, position.height), wallpaper, ScaleMode.StretchToFill); _overallWidth = position.width - 1; GUI.color = Color.white; //_masterScrollPos = GUILayout.BeginScrollView(_masterScrollPos); //search filter row GUILayout.BeginHorizontal(GUI.skin.GetStyle("Box"), GUILayout.Width(_overallWidth - 20)); { GUILayout.Label("Options:"); GUILayout.Space(1); if (_sortPartialNames != GUILayout.Toggle(_sortPartialNames, "Exclude Namespace when Sorting")) { _sortPartialNames = !_sortPartialNames; RefreshMonoAssembliesList(); } GUILayout.Space(1); if (_sortDescending != GUILayout.Toggle(_sortDescending, "Sort Descending")) { _sortDescending = !_sortDescending; RefreshMonoAssembliesList(); } } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(GUILayout.Width(_overallWidth * .6f)); { GUI.skin.label.alignment = TextAnchor.MiddleRight; GUILayout.Label("Filter:"); GUI.skin.label.alignment = TextAnchor.MiddleLeft; filter = GUILayout.TextField(filter); } GUILayout.EndHorizontal(); GUI.color = Color.white; _masterScrollPos = GUILayout.BeginScrollView(_masterScrollPos); { GUILayout.BeginVertical(GUI.skin.GetStyle("Box"), GUILayout.Width(_overallWidth - 10)); { _showSceneUI = EditorGUILayout.Foldout(_showSceneUI, "Components in Active Scenes"); if (_showSceneUI) { DoSceneMonoUI(); } } GUILayout.EndVertical(); GUI.color = _rhubarb; GUILayout.BeginVertical(GUI.skin.GetStyle("Box"), GUILayout.Width(_overallWidth - 10)); { _showProjectUI = EditorGUILayout.Foldout(_showProjectUI, "MonoBehaviours in Project"); if (_showProjectUI) { DoProjectMonoUI(); } } GUILayout.EndVertical(); GUI.color = _paleCyan; GUILayout.BeginVertical(GUI.skin.GetStyle("Box"), GUILayout.Width(_overallWidth - 10)); { _showAssembliesUI = EditorGUILayout.Foldout(_showAssembliesUI, "MonoBehaviours in Assemblies"); if (_showAssembliesUI) { DoAssembliesUI(); } } GUILayout.EndVertical(); GUI.color = _paleGreen; GUILayout.BeginVertical(GUI.skin.GetStyle("Box"), GUILayout.Width(_overallWidth - 10)); { _showAssets = EditorGUILayout.Foldout(_showAssets, "Assets in Project"); if (_showAssets) { DoAssetsUI(); } } GUILayout.EndVertical(); } GUILayout.EndScrollView(); }
public static bool LoadTexture2DLutFromPhotoshopData(byte[] data, LUTSettings settings, ref Texture2D texture) { int columns = settings.Columns; int rows = settings.Rows; int size = settings.Size; var decryptedBytes = data.AsEnumerable(); //byte imageType = decryptedBytes.Take(1).First(); decryptedBytes = decryptedBytes.Skip(1); var tempbytes = decryptedBytes.Take(4).Reverse().ToArray(); decryptedBytes = decryptedBytes.Skip(4); int imageWidth = BitConverter.ToInt32(tempbytes, 0); tempbytes = decryptedBytes.Take(4).Reverse().ToArray(); decryptedBytes = decryptedBytes.Skip(4); int imageHeight = BitConverter.ToInt32(tempbytes, 0); //tempbytes = decryptedBytes.Take(4).Reverse().ToArray(); decryptedBytes = decryptedBytes.Skip(4); //int rowBytes = BitConverter.ToInt32(tempbytes, 0); //byte colorMode = decryptedBytes.Take(1).First(); decryptedBytes = decryptedBytes.Skip(1); //byte channelCount = decryptedBytes.Take(1).First(); decryptedBytes = decryptedBytes.Skip(1); //byte bitsChannel = decryptedBytes.Take(1).First(); decryptedBytes = decryptedBytes.Skip(1); var imageData = new Color[imageWidth, imageHeight]; var bytesarray = decryptedBytes.ToArray(); for (int i = 0, k = 0; i < imageHeight; i++) { for (int j = 0; j < imageWidth; j++) { imageData[j, i] = new Color(bytesarray[k++] / 255f, bytesarray[k++] / 255f, bytesarray[k++] / 255f, 1f); } } var lutTexture = new Texture2D(size * size, size, TextureFormat.ARGB32, false); var lutData = new Color[size * size * size]; for (int h = 0, i = 0; h < size; h++) { for (int r = 0; r < rows; r++) { for (int w = 0; w < size * columns; w++) { lutData[i++] = imageData[w, h + r * size]; } } } lutTexture.SetPixels(lutData); lutTexture.Apply(); if (texture != null) { Texture2D.DestroyImmediate(texture); } texture = lutTexture; return(true); }
public void ApplyMarkedPixelChanges() { drawable_texture.SetPixels32(cur_colors); drawable_texture.Apply(); }
// The actual window code goes here private void OnGUI() { // Set custom textures: Texture2D redBackground = new Texture2D(deleteConBtnSize, deleteConBtnSize); for (int i = 0; i < deleteConBtnSize; i++) { for (int j = 0; j < deleteConBtnSize; j++) { redBackground.SetPixel(j, i, new Color((180 + (2 * i)) / 255f, 0, 0)); } } redBackground.Apply(); Texture2D greenBackground = new Texture2D(deleteConBtnSize, deleteConBtnSize); for (int i = 0; i < deleteConBtnSize; i++) { for (int j = 0; j < deleteConBtnSize; j++) { greenBackground.SetPixel(j, i, new Color(0, (170 + (2 * i)) / 255f, 0)); } } greenBackground.Apply(); // Set styles for the delete node connection button deleteConnectionButton.fontSize = 13; deleteConnectionButton.alignment = TextAnchor.MiddleCenter; deleteConnectionButton.normal.textColor = Color.white; deleteConnectionButton.normal.background = redBackground; deleteConnectionButton.border = new RectOffset(10, 10, 10, 10); // Set styles for start button GUIStyle startNode = new GUIStyle { fontSize = 13, alignment = TextAnchor.MiddleCenter }; startNode.normal.textColor = Color.white; startNode.normal.background = greenBackground; startNode.border = new RectOffset(5, 5, 5, 5); // Set styles for the end button GUIStyle endNode = new GUIStyle { fontSize = 13, alignment = TextAnchor.MiddleCenter }; endNode.normal.textColor = Color.white; endNode.normal.background = redBackground; // Lock sizes of window this.minSize = new Vector2(MIN_WIDTH, MIN_HEIGHT); this.maxSize = new Vector2(MAX_WIDTH, MAX_HEIGHT); Vector2 backgroundSize = new Vector2(position.width * 0.95f, position.height * 0.75f); // Draw editor title GUILayout.Label("Dialog Editor", EditorStyles.boldLabel); if (this.selectedCharacter != null) { GUILayout.Label("Editing dialog for " + this.selectedCharacter.name, EditorStyles.centeredGreyMiniLabel); } // Draw the dialog tree background Rect backgroundRect = new Rect(backgroundPosition.x, backgroundPosition.y, backgroundSize.x, backgroundSize.y); EditorGUI.DrawRect(backgroundRect, new Color(0.6f, 0.6f, 0.6f)); // Add a new dialog node on button click GUIStyle newNodeButton = new GUIStyle { fontSize = 20, alignment = TextAnchor.UpperCenter, fontStyle = FontStyle.Bold }; if (GUI.Button(new Rect(position.width * 0.92f, 10, 30, 30), "+", newNodeButton)) { DialogNode content = new DialogNode("Write the dialog prompt here."); Vector2 nodePosition = new Vector2(Random.Range(backgroundPosition.x, backgroundSize.x - nodeWidth / 2), Random.Range(backgroundPosition.y, backgroundSize.y - nodeHeight / 2)); nodes.Add(new WindowDialogNode(nodePosition, content)); } if (selectedNodeIndex != -1 && selectedNodeIndex != START_NODE_INDEX && selectedNodeIndex != END_NODE_INDEX) { if (GUI.Button(new Rect(position.width * 0.86f, 10, 30, 30), "X", deleteConnectionButton)) { RemoveNodeAtIndex(selectedNodeIndex); } } // If no nodes have been added to the graph, add a start node and end node if (this.nodes.Count == 0) { // Add the green start node: DialogNode startContent = new DialogNode("Start Node"); Vector2 startNodePosition = new Vector2(Random.Range(backgroundPosition.x, backgroundSize.x - nodeWidth / 2), Random.Range(backgroundPosition.y, backgroundSize.y - nodeHeight / 2)); nodes.Add(new WindowDialogNode(startNodePosition, startContent)); // Add a red end node: DialogNode endContent = new DialogNode("End Node"); Vector2 endNodePosition = new Vector2(Random.Range(backgroundPosition.x, backgroundSize.x - nodeWidth / 2), Random.Range(backgroundPosition.y, backgroundSize.y - nodeHeight / 2)); nodes.Add(new WindowDialogNode(endNodePosition, endContent)); } //Draw all the nodes in the graph, including the arrows represeting the traversable paths of dialog. BeginWindows(); for (int i = 0; i < nodes.Count; i++) { // If the node is not a start node or the end node, we still need to set its Rect if (i == START_NODE_INDEX) // Index 0 of nodes is always the start node { nodes[START_NODE_INDEX].Rect = GUI.Window(START_NODE_INDEX, nodes[START_NODE_INDEX].Rect, DrawNodeWindow, "Start", startNode); } else if (i == END_NODE_INDEX) // Index 1 of nodes is always the end node { nodes[END_NODE_INDEX].Rect = GUI.Window(END_NODE_INDEX, nodes[END_NODE_INDEX].Rect, DrawNodeWindow, "End", endNode); } else // Every index greater than 1 holds all the dialog nodes { nodes[i].Rect = GUI.Window(i, nodes[i].Rect, DrawNodeWindow, "Node " + (i - 1)); } // Handles graph interaction. Also draws connections between nodes Event current = Event.current; if (nodes[i].Rect.Contains(current.mousePosition)) { // If node is right-clicked, start creating a connection to a new node if (current.type == EventType.ContextClick) { // If flag is true, then the user is trying to form the tail of the node connection if (draggingNodeLink) { // If this connection has not already been formed, then form it bool canCreateConnection = true; for (int j = 0; j < nodes[draggingFromIndex].content.responses.Count; j++) { if (nodes[draggingFromIndex].content.responses[j].nextSentence == i) { canCreateConnection = false; break; } } if (canCreateConnection) { DialogResponse response = new DialogResponse("Write a response to the prompt here.", i); nodes[draggingFromIndex].content.responses.Add(response); } draggingNodeLink = false; } // If the flag is false, then the user is trying to start with the head (beginning) of the connection else { int numResponses = nodes[START_NODE_INDEX].content.responses.Count; // Don't allow dialog paths to be created originating from the end node if (i != END_NODE_INDEX) { draggingFromIndex = i; draggingNodeLink = true; } } current.Use(); } // If you left click on a node, display the node's info at the bottom of the gui else if (current.type == EventType.Layout) { selectedNodeIndex = i; } } // Draw connections to neighbouring nodes Handles.color = Color.cyan; Vector2 currentNodePosition2d = nodes[i].Rect.position; Vector3 currentNodePosition = new Vector3(currentNodePosition2d.x + WindowDialogNode.width / 2, currentNodePosition2d.y + WindowDialogNode.height / 2, 0); if (nodes[i].content != null) { for (int j = 0; j < nodes[i].content.responses.Count; j++) { // Get the index for the target node from the nextSentence variable of the j-th response of this node int targetNodeIndex = nodes[i].content.responses[j].nextSentence; Vector2 targetNodePosition2d = nodes[targetNodeIndex].Rect.position; Vector3 targetNodePosition = new Vector3(targetNodePosition2d.x + WindowDialogNode.width / 2, targetNodePosition2d.y + WindowDialogNode.height / 2, 0); Handles.DrawLine(currentNodePosition, targetNodePosition); // Draw the arrow head: Vector3 dirUnitVector = (targetNodePosition - currentNodePosition).normalized; Vector3 perpendicularDirUnitVector = new Vector3(-dirUnitVector.y, dirUnitVector.x, 0).normalized; Vector3 triangleHeight = dirUnitVector * arrowheadHeight; targetNodePosition = 0.5f * (targetNodePosition + currentNodePosition); Vector3 triangleBase = new Vector3(targetNodePosition.x - triangleHeight.x, targetNodePosition.y - triangleHeight.y, 0); Vector3[] vertices = { targetNodePosition, new Vector3(triangleBase.x + ((arrowheadHeight / 2) * perpendicularDirUnitVector.x),triangleBase.y + ((arrowheadHeight / 2) * perpendicularDirUnitVector.y), 0), new Vector3(triangleBase.x - ((arrowheadHeight / 2) * perpendicularDirUnitVector.x),triangleBase.y - ((arrowheadHeight / 2) * perpendicularDirUnitVector.y), 0), }; Handles.color = Color.cyan; Handles.DrawAAConvexPolygon(vertices); } } } EndWindows(); // Draws a line from selected node to the cursor position when creating a new node connection in the graph if (draggingNodeLink) { Vector2 mousePos = Event.current.mousePosition; Vector2 nodePos = nodes[draggingFromIndex].Rect.position; Handles.color = Color.blue; Handles.DrawLine(new Vector3(mousePos.x, mousePos.y, 0), new Vector3(nodePos.x + WindowDialogNode.width / 2, nodePos.y + WindowDialogNode.height / 2, 0)); Repaint(); } // End node connection attempt if second left click not over a node Event secondEvent = Event.current; if (secondEvent.type == EventType.ContextClick) { draggingNodeLink = false; secondEvent.Use(); } // If a node is selected in the graph, display its contents at the bottom of the gui window. if (selectedNodeIndex != -1) { DisplayNodeInfo(); } // Label to say which node is currently highlighted in the dialog graph GUI.Label(new Rect(660, position.height * 0.86f, 100, 70), "Selected Node:"); GUI.Label(new Rect(660, position.height * 0.89f, 100, 70), selectedNodeIndex == -1 ? "No node selected." : selectedNodeIndex == 0 ? "Start Node" : selectedNodeIndex == 1 ? "End Node" : "Node " + (selectedNodeIndex - 1)); // Save the updated dialog graph: if (this.selectedCharacter != null) { this.selectedCharacter.UpdateDialogGraph(this.nodes); } } // end OnGUI method
//TODO (Polish): Use a struct public static Texture2D RenderShaderMap(Material targetMaterial, int intersectionStyle, int waveStyle, int heightmapStyle, bool useCompression = false, Texture2D customIntersectionTex = null, Texture2D customHeightmapTex = null) { StylizedWaterResources r = StylizedWaterResources.Instance; //Set compression setting TexturePacker.useCompression = useCompression; //Intersection Texture2D intersectionTex; if (customIntersectionTex) { intersectionTex = customIntersectionTex; } else { intersectionTex = r.intersectionStyles[intersectionStyle]; } //Foam Texture2D foamTex; //When a custom normal map is used, force the usage of the intersection texture for foam if (waveStyle == r.waveStyles.Length) { foamTex = Texture2D.blackTexture; } else { foamTex = r.waveStyles[waveStyle]; } //Heightmap Texture2D heightmapTex; if (customHeightmapTex) { heightmapTex = customHeightmapTex; } else { heightmapTex = r.heightmapStyles[heightmapStyle]; } Texture2D shadermap = new Texture2D(SHADERMAP_RESOLUTION, SHADERMAP_RESOLUTION, TextureFormat.RGB24, true) { name = "_shadermap", //Prefix and suffix to be appended upon saving anisoLevel = 2, filterMode = FilterMode.Bilinear, wrapMode = TextureWrapMode.Repeat }; RenderTexture rt = new RenderTexture(shadermap.width, shadermap.width, 0); RenderTexture.active = rt; //Constants ShaderMapRenderMat.SetTexture("_RedInput", foamTex); ShaderMapRenderMat.SetTexture("_GreenInput", heightmapTex); ShaderMapRenderMat.SetTexture("_BlueInput", intersectionTex); //ShaderMapRenderMat.SetTexture("_AlphaInput", null); //Pack textures on GPU Graphics.Blit(null, rt, ShaderMapRenderMat); //Copy result into texture shadermap.ReadPixels(new Rect(0, 0, shadermap.width, shadermap.height), 0, 0); shadermap.Apply(); //Cleanup RenderTexture.active = null; shadermap = SaveAndGetTexture(targetMaterial, shadermap); return(shadermap); }
void UpdateUserMap() { // copy over the maps Marshal.Copy(NiteWrapper.GetUsersLabelMap(), usersLabelMap, 0, usersMapSize); Marshal.Copy(NiteWrapper.GetUsersDepthMap(), usersDepthMap, 0, usersMapSize); // we will be flipping the texture as we convert label map to color array int flipIndex, i; int numOfPoints = 0; Array.Clear(usersHistogramMap, 0, usersHistogramMap.Length); // calculate cumulative histogram for depth for (i = 0; i < usersMapSize; i++) { // only calculate for depth that contains users if (usersLabelMap[i] != 0) { usersHistogramMap[usersDepthMap[i]]++; numOfPoints++; } } if (numOfPoints > 0) { for (i = 1; i < usersHistogramMap.Length; i++) { usersHistogramMap[i] += usersHistogramMap[i - 1]; } for (i = 0; i < usersHistogramMap.Length; i++) { usersHistogramMap[i] = 1.0f - (usersHistogramMap[i] / numOfPoints); } } // create the actual users texture based on label map and depth histogram for (i = 0; i < usersMapSize; i++) { flipIndex = usersMapSize - i - 1; if (usersLabelMap[i] == 0) { usersMapColors[flipIndex] = Color.clear; } else { // create a blending color based on the depth histogram Color c = new Color(usersHistogramMap[usersDepthMap[i]], usersHistogramMap[usersDepthMap[i]], usersHistogramMap[usersDepthMap[i]], 0.9f); switch (usersLabelMap[i] % 4) { case 0: usersMapColors[flipIndex] = Color.red * c; break; case 1: usersMapColors[flipIndex] = Color.green * c; break; case 2: usersMapColors[flipIndex] = Color.blue * c; break; case 3: usersMapColors[flipIndex] = Color.magenta * c; break; } } } usersLblTex.SetPixels(usersMapColors); usersLblTex.Apply(); }
public static void RefreshTexture(ManeuverParameters[,] nodes, Texture2D texture) { Gradient colours = new Gradient(); var colourKeys = new GradientColorKey[6]; colourKeys[0].color = new Color(0.25f, 0.25f, 1.0f); colourKeys[0].time = 0.0f; colourKeys[1].color = new Color(0.5f, 0.5f, 1.0f); colourKeys[1].time = 0.01f; colourKeys[2].color = new Color(0.5f, 1.0f, 1.0f); colourKeys[2].time = 0.25f; colourKeys[3].color = new Color(0.5f, 1.0f, 0.5f); colourKeys[3].time = 0.5f; colourKeys[4].color = new Color(1.0f, 1.0f, 0.5f); colourKeys[4].time = 0.75f; colourKeys[5].color = new Color(1.0f, 0.5f, 0.5f); colourKeys[5].time = 1.0f; var alphaKeys = new GradientAlphaKey[2]; alphaKeys[0].alpha = 1.0f; alphaKeys[0].time = 0.0f; alphaKeys[1].alpha = 1.0f; alphaKeys[1].time = 1.0f; colours.SetKeys(colourKeys, alphaKeys); int width = nodes.GetLength(0); int height = nodes.GetLength(1); double DVminsqr = double.MaxValue; double DVmaxsqr = double.MinValue; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (nodes[i, j] != null) { double DVsqr = nodes[i, j].dV.sqrMagnitude; if (DVsqr < DVminsqr) { DVminsqr = DVsqr; } DVmaxsqr = Math.Max(DVmaxsqr, nodes[i, j].dV.sqrMagnitude); } } } double logDVminsqr = Math.Log(DVminsqr); double logDVmaxsqr = Math.Min(Math.Log(DVmaxsqr), logDVminsqr + 4); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (nodes[i, j] == null) { texture.SetPixel(i, j, colours.Evaluate(1)); } else { double lambda = (Math.Log(nodes[i, j].dV.sqrMagnitude) - logDVminsqr) / (logDVmaxsqr - logDVminsqr); texture.SetPixel(i, j, colours.Evaluate((float)lambda)); } } } texture.Apply(); #if DEBUG string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); System.IO.File.WriteAllBytes(dir + "/Porkchop.png", texture.EncodeToPNG()); #endif }
public static Texture2D GenerateHSVTexture(int width, int height) { var list = GenerateHsvSpectrum(); float interval = 1; if (list.Count > height) { interval = (float)list.Count / height; } var texture = new Texture2D(width, height); int ySize = Mathf.Max(1, (int)(1f / (list.Count / interval) * height)); int colorH = 0; Color color = Color.white; for (float cnt = 0; cnt < list.Count; cnt += interval) { color = list[(int)cnt]; Color[] colors = new Color[width * ySize]; for (int i = 0; i < width * ySize; i++) { colors[i] = color; } if (colorH < height) { texture.SetPixels(0, colorH, width, ySize, colors); } colorH += ySize; } texture.Apply(); return texture; }
/// <summary> /// 获取图片 /// </summary> public bool Get(string key, out Texture2D tex) { _pool.TryGetValue(key, out tex); tex?.Apply(); return(tex != null); }
void OnGUI() { if (Selection.activeGameObject == null) { return; } //var selection = Selection.activeGameObject.GetComponent<TileMap> (); var selection = ((GameObject)Selection.activeGameObject).GetComponent <TileMap> (); if (selection != null) { var texture2D = selection.texture2D; if (texture2D != null) { //1 With original size //GUI.DrawTexture(new Rect(0, 0 , texture2D.width, texture2D.height), texture2D); //2 With Scale dropdown resizing zoom scale = (Scale)EditorGUILayout.EnumPopup("Zoom", scale); var newScale = ((int)scale) + 1; //first value is 0 + 1 = 1 var newTextureSize = new Vector2(texture2D.width, texture2D.height) * newScale; //Dropdown to be in the middle of windows var offset = new Vector2(10, 25); //Add Scroll Bar //Size of the window var viewPort = new Rect(0, 0, position.width - 5, position.height - 5); //Object that we are showing in the windows var contentSize = new Rect(0, 0, newTextureSize.x + offset.x, newTextureSize.y + offset.y); scrollPosition = GUI.BeginScrollView(viewPort, scrollPosition, contentSize); GUI.DrawTexture(new Rect(offset.x, offset.y, newTextureSize.x, newTextureSize.y), texture2D); //It ends to GUI.EndScrollView(); at the end //highlight the tile in the picker var tile = selection.tileSize * newScale; //For padding tile.x += selection.tilePadding.x * newScale; tile.y += selection.tilePadding.y * newScale; var grid = new Vector2(newTextureSize.x / tile.x, newTextureSize.y / tile.y); var selectionPos = new Vector2(tile.x * currentSelection.x + offset.x, tile.y * currentSelection.y + offset.y); //Style the texture box var boxTex = new Texture2D(1, 1); boxTex.SetPixel(0, 0, new Color(0, 0.5f, 1f, 0.4f)); boxTex.Apply(); var style = new GUIStyle(GUI.skin.customStyles[0]); style.normal.background = boxTex; GUI.Box(new Rect(selectionPos.x, selectionPos.y, tile.x, tile.y), "", style); //Moving the slected box var cEvent = Event.current; Vector2 mousePos = new Vector2(cEvent.mousePosition.x, cEvent.mousePosition.y); if (cEvent.type == EventType.MouseDown && cEvent.button == 0) { currentSelection.x = Mathf.Floor((mousePos.x + scrollPosition.x) / tile.x); currentSelection.y = Mathf.Floor((mousePos.y + scrollPosition.y) / tile.y); if (currentSelection.x > grid.x - 1) { currentSelection.x = grid.x - 1; } if (currentSelection.y > grid.y - 1) { currentSelection.y = grid.y - 1; } selection.tileID = (int)(currentSelection.x + (currentSelection.y * grid.x) + 1); Repaint(); } GUI.EndScrollView(); } } }
// Returns a texture for a given sprite, if the sprite is a region sprite, a new texture is returned public Texture2D GetTextureForSprite(int spriteId) { var param = spriteCollectionProxy.textureParams[spriteId]; if (spriteId != cachedSpriteId) { ClearTextureCache(); cachedSpriteId = spriteId; } if (param.extractRegion) { if (cachedSpriteTexture == null) { var tex = param.texture; cachedSpriteTexture = new Texture2D(param.regionW, param.regionH); for (int y = 0; y < param.regionH; ++y) { for (int x = 0; x < param.regionW; ++x) { cachedSpriteTexture.SetPixel(x, y, tex.GetPixel(param.regionX + x, param.regionY + y)); } } cachedSpriteTexture.Apply(); } return cachedSpriteTexture; } else { return param.texture; } }
public static int MINIMUM_THRESHOLD = 100; //!< Minimum threshold. /// Minimum alpha a point must have to be rendered at all. /*! <summary> * Creates a Heatmap image given a set of world points. * </summary> * <remarks> * This method accepts a series of world points, and returns a transparent overlay of the heatmap. Usually you will want to pair this call with CreateRenderPlane() to actually view the heatmap. * </remarks> * <param name="worldPoints">An array of Vector3 points to be translated into heatmap points.</param> * <param name="cam">The camera to render from. If passed a null value, CreateHeatmap() attempts to use Camera.main.</param> * <param name="radius">Raidus in pixels that each point should create. Larger radii produce denser heatmaps, and vice-versa.</param> * <returns>Returns a new Texture2D containing a transparent overlay of the heatmap.</returns> */ public static Texture2D CreateHeatmap(Vector3[] worldPoints, Camera cam, int radius) { if (cam == null) { if (Camera.main == null) { Debug.LogWarning("No camera found. Returning an empty texture."); return(new Texture2D(0, 0)); } else { cam = Camera.main; } } // Create new texture // Texture2D map = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false); Texture2D map = new Texture2D((int)cam.pixelWidth, (int)cam.pixelHeight, TextureFormat.ARGB32, false); // Set texture to alpha-fied state map.SetPixels(Heatmap.ColorArray(new Color(1f, 1f, 1f, 0f), map.width * map.height), 0); // Convert world to screen points Vector2[] points = new Vector2[worldPoints.Length]; for (int i = 0; i < worldPoints.Length; i++) { points[i] = cam.WorldToScreenPoint(worldPoints[i]); } /*** Generate Grayscale Values ***/ { int x2; // the offset x val in img coordinates int y2; // the offset y val in img coordinates (0,0) - (maxX, maxY) float pointAlpha = .9f; // The alpha that the darkest pixel will be in a poitn. Color color = new Color(1f, 1f, 1f, pointAlpha); int lineWidth = 1; //(int)(radius * .05f); Dictionary <Vector2, Color> pixelAlpha = new Dictionary <Vector2, Color>(); for (int i = 0; i < points.Length; i++) // generate alpha add for each point and a specified circumference { pixelAlpha.Clear(); for (int r = 0; r < radius; r += lineWidth) // draw and fill them circles { for (int angle = 0; angle < 360; angle++) { x2 = (int)(r * Mathf.Cos(angle)) + (int)points[i].x; y2 = (int)(r * Mathf.Sin(angle)) + (int)points[i].y; // This could be sped up for (int y = y2; y > y2 - lineWidth; y--) { for (int x = x2; x < x2 + lineWidth; x++) { Vector2 coord = new Vector2(x, y); if (pixelAlpha.ContainsKey(coord)) { pixelAlpha[coord] = color; } else { pixelAlpha.Add(new Vector2(x, y), color); } } } } color = new Color(color.r, color.g, color.b, color.a - (pointAlpha / ((float)radius / lineWidth))); } // Since the radial fill code overwrites it's own pixels, make sure to only add finalized alpha to // old values. foreach (KeyValuePair <Vector2, Color> keyval in pixelAlpha) { Vector2 coord = keyval.Key; Color previousColor = map.GetPixel((int)coord.x, (int)coord.y); Color newColor = keyval.Value; map.SetPixel((int)coord.x, (int)coord.y, new Color(newColor.r, newColor.b, newColor.g, newColor.a + previousColor.a)); } // Reset color for next point color = new Color(color.r, color.g, color.b, pointAlpha); } } map.Apply(); map.SetPixels(Colorize(map.GetPixels(0)), 0); map.Apply(); return(map); }
/// <summary> /// Dessine l'interface des options du personnage. /// </summary> private void DrawCharacter() { this.smoothAparition += Time.deltaTime; this.skin.textField.alignment = TextAnchor.MiddleCenter; this.playerName = GUI.TextField(new Rect(this.posX, this.posY + this.spacing * 6.2f, this.width, this.height), this.RemoveSpecialCharacter(this.playerName, "abcdefghijklmnopqrstuvwxyz123456789-_", false), 15, this.skin.textField); bool firstLaunch = PlayerPrefs.GetString("PlayerName", "") == ""; if (this.playerName != "" && GUI.Button(new Rect(this.posX, this.posY + this.spacing * 7f, this.width / (firstLaunch ? 1f : 2.1f), this.height), TextDatabase.Validate.GetText(), this.skin.GetStyle("button"))) { this.characterShown = false; this.firstScene.OnChar = false; PlayerPrefs.SetString("PlayerName", this.playerName); PlayerPrefs.SetString("Skin", Skin.Save(this.skinCharacter)); this.firstScene.PlayButtonSound(); } if (!firstLaunch && GUI.Button(new Rect(this.posX + this.width / 1.9f, this.posY + this.spacing * 7, this.width / 2.1f, this.height), TextDatabase.Back.GetText(), this.skin.GetStyle("button"))) { this.characterShown = false; this.firstScene.OnChar = false; this.optionShown = true; this.playerName = PlayerPrefs.GetString("PlayerName", ""); this.firstScene.PlayButtonSound(); } if (GUI.RepeatButton(new Rect(this.posX + this.width - this.width / 4, this.posY + this.spacing * 4.8f, this.width / 4, this.width / 6), "", this.skin.GetStyle("right_arrow"))) this.character.transform.Rotate(Vector3.up, -5); if (GUI.RepeatButton(new Rect(this.posX, this.posY + this.spacing * 4.8f, this.width / 4, this.width / 6), "", this.skin.GetStyle("left_arrow"))) this.character.transform.Rotate(Vector3.up, +5); #region Category if (GUI.Button(new Rect(this.posX, this.posY - this.spacing * 1.5f, this.width / 5, this.width / 5), Resources.Load<Texture2D>("Sprites/Cosmetics/HatIcon"), skin.GetStyle("Square"))) { if (this.categoryCloth == CategoryCloth.Hat) this.categoryCloth = CategoryCloth.None; else { this.categoryCloth = CategoryCloth.Hat; this.smoothAparition = 0; } } if (GUI.Button(new Rect(this.posX, this.posY, this.width / 5, this.width / 5), Resources.Load<Texture2D>("Sprites/Cosmetics/BeardIcon"), skin.GetStyle("Square"))) { if (this.categoryCloth == CategoryCloth.Beard) this.categoryCloth = CategoryCloth.None; else { this.smoothAparition = 0; this.categoryCloth = CategoryCloth.Beard; } } if (GUI.Button(new Rect(this.posX, this.posY + this.spacing * 1.5f, this.width / 5, this.width / 5), Resources.Load<Texture2D>("Sprites/Cosmetics/BodyIcon"), skin.GetStyle("Square"))) { if (this.categoryCloth == CategoryCloth.Body) this.categoryCloth = CategoryCloth.None; else { this.smoothAparition = 0; this.categoryCloth = CategoryCloth.Body; } } if (GUI.Button(new Rect(this.posX + this.width - this.width / 5, this.posY, this.width / 5, this.width / 5), Resources.Load<Texture2D>("Sprites/Cosmetics/EyeIcon"), skin.GetStyle("Square"))) { if (this.categoryCloth == CategoryCloth.Eyes) this.categoryCloth = CategoryCloth.None; else { this.smoothAparition = 0; this.categoryCloth = CategoryCloth.Eyes; } } if (GUI.Button(new Rect(this.posX + this.width - this.width / 5, this.posY - this.spacing * 1.5f, this.width / 5, this.width / 5), Resources.Load<Texture2D>("Sprites/Cosmetics/HairIcon"), skin.GetStyle("Square"))) { if (this.categoryCloth == CategoryCloth.Hair) this.categoryCloth = CategoryCloth.None; else { this.smoothAparition = 0; this.categoryCloth = CategoryCloth.Hair; } } if (GUI.Button(new Rect(this.posX, this.posY + this.spacing * 3f, this.width / 5, this.width / 5), Resources.Load<Texture2D>("Sprites/Cosmetics/GlovesIcon"), skin.GetStyle("Square"))) { if (this.categoryCloth == CategoryCloth.Gloves) this.categoryCloth = CategoryCloth.None; else { this.smoothAparition = 0; this.categoryCloth = CategoryCloth.Gloves; } } if (GUI.Button(new Rect(this.posX + this.width - this.width / 5, this.posY + this.spacing * 1.5f, this.width / 5, this.width / 5), Resources.Load<Texture2D>("Sprites/Cosmetics/TshirtIcon"), skin.GetStyle("Square"))) { if (this.categoryCloth == CategoryCloth.TShirt) this.categoryCloth = CategoryCloth.None; else { this.smoothAparition = 0; this.categoryCloth = CategoryCloth.TShirt; } } if (GUI.Button(new Rect(this.posX + this.width - this.width / 5, this.posY + this.spacing * 3f, this.width / 5, this.width / 5), Resources.Load<Texture2D>("Sprites/Cosmetics/PantIcon"), skin.GetStyle("Square"))) { if (this.categoryCloth == CategoryCloth.Pant) this.categoryCloth = CategoryCloth.None; else { this.categoryCloth = CategoryCloth.Pant; this.smoothAparition = 0; } } if (GUI.Button(new Rect(this.posX + this.width + this.width / 5, this.posY - this.spacing * 1.5f, this.width / 5, this.width / 5), Resources.Load<Texture2D>("Sprites/Cosmetics/RandomIcon"), skin.GetStyle("Square"))) { this.categoryCloth = CategoryCloth.None; this.skinCharacter = Skin.RandomSkin(); this.skinCharacter.Apply(this.character); } if (GUI.Button(new Rect(this.posX + this.width + this.width / 5f, this.posY, this.width / 5, this.width / 5), Resources.Load<Texture2D>("Sprites/Cosmetics/Reset"), skin.GetStyle("Square"))) { try { this.categoryCloth = CategoryCloth.None; this.skinCharacter = Skin.Load(PlayerPrefs.GetString("Skin", "")); this.skinCharacter.Apply(this.character); } catch { } } switch (this.categoryCloth) { case CategoryCloth.Hair: case CategoryCloth.Eyes: case CategoryCloth.Beard: case CategoryCloth.Hat: this.firstScene.CameraAim(1); break; case CategoryCloth.Gloves: this.firstScene.CameraAim(2); break; default: this.firstScene.CameraAim(0); break; } #endregion Text tooltip = null; Texture2D fill = new Texture2D(this.width / 3, this.width / 3); switch (this.categoryCloth) { #region Hat case (CategoryCloth.Hat): int y = 0; int x = 0; Rect rect = new Rect(Screen.width / 25f, this.posY - this.spacing * 1.5f, Screen.height / 11, Screen.height / 11); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/NoneIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Hat.TypeHat.None; } rect.x += (Screen.width / 40 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/HatIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Hat.TypeHat.TopHat; } rect.x += (Screen.width / 40 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/StrawHatIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Hat.TypeHat.StrawHat; } rect.x += (Screen.width / 40 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/CowBoyIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Hat.TypeHat.CowBoy; } foreach (Hat h in Clothing.Hats) if (this.typeCloth == (int)h.GetTypeHat) { x = this.typeCloth; Color fillcolor = h.Color; fillcolor.a = Mathf.Clamp01(this.smoothAparition - y * TransitionDelay); for (int i = 0; i < this.width / 3; i++) for (int j = 0; j < this.width / 3; j++) fill.SetPixel(i, j, fillcolor); fill.Apply(); rect = new Rect((Screen.width / 40 + Screen.width / 20) * x + Screen.width / 25f, y * (Screen.height / 10) + Screen.height / 2.6f, Screen.height / 11, Screen.height / 11); if (rect.Contains(Event.current.mousePosition)) tooltip = h.Description; if (this.smoothAparition > y * TransitionDelay && GUI.Button(rect, fill, skin.GetStyle("Square"))) { this.skinCharacter.Hat = h; this.skinCharacter.Apply(this.character); } y += 1; } break; #endregion #region Beard case (CategoryCloth.Beard): y = 0; x = 0; rect = new Rect(Screen.width / 25f, this.posY - this.spacing * 1.5f, Screen.height / 11, Screen.height / 11); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/NoneIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Beard.TypeBeard.None; } rect.x += (Screen.width / 50 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/BeardIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Beard.TypeBeard.Beard; } rect.x += (Screen.width / 50 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/BeardOnlyIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Beard.TypeBeard.BeardOnly; } rect.x += (Screen.width / 50 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/BeardIcon 1"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Beard.TypeBeard.BeardMoustachSplit; } rect.x += (Screen.width / 50 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/MustacheIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Beard.TypeBeard.Moustach; } foreach (Beard b in Clothing.Beards) if (this.typeCloth == (int)b.GetTypeBeard) { x = this.typeCloth; Color fillcolor = b.Color; fillcolor.a = Mathf.Clamp01(this.smoothAparition - y * TransitionDelay); for (int i = 0; i < this.width / 3; i++) for (int j = 0; j < this.width / 3; j++) fill.SetPixel(i, j, fillcolor); fill.Apply(); rect = new Rect((Screen.width / 50 + Screen.width / 20) * x + Screen.width / 25f, y * (Screen.height / 10) + Screen.height / 2.6f, Screen.height / 11, Screen.height / 11); if (rect.Contains(Event.current.mousePosition)) tooltip = b.Description; if (this.smoothAparition > y * TransitionDelay && GUI.Button(rect, fill, skin.GetStyle("Square"))) { this.skinCharacter.Beard = b; this.skinCharacter.Apply(this.character); } y += 1; } break; #endregion #region Body case (CategoryCloth.Body): y = 0; x = 0; foreach (Body b in Clothing.Bodies) { Color fillcolor = b.Color; fillcolor.a = Mathf.Clamp01(this.smoothAparition - (x + y * 3) * TransitionDelay); for (int i = 0; i < this.width / 3; i++) for (int j = 0; j < this.width / 3; j++) fill.SetPixel(i, j, fillcolor); fill.Apply(); rect = new Rect((Screen.width / 40 + Screen.width / 20) * x + Screen.width / 25f, y * (10 + Screen.height / 10) + Screen.height / 2.25f, Screen.height / 11, Screen.height / 11); if (rect.Contains(Event.current.mousePosition)) tooltip = b.Description; if (this.smoothAparition > (x + y * 3) * TransitionDelay && GUI.Button(rect, fill, skin.GetStyle("Square"))) { this.skinCharacter.Body = b; this.skinCharacter.Apply(this.character); } x = (x + 1) % 3; if (x == 0) y++; } break; #endregion #region Hair case (CategoryCloth.Hair): y = 0; x = 0; rect = new Rect(Screen.width / 25f, this.posY - this.spacing * 1.5f, Screen.height / 11, Screen.height / 11); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/NoneIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Hair.TypeHair.None; } rect.x += (Screen.width / 50 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/HairIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Hair.TypeHair.Normal; } rect.x += (Screen.width / 50 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/PunkHair"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Hair.TypeHair.Crete; } rect.x += (Screen.width / 50 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/LongHair"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Hair.TypeHair.LongHair; } rect.x += (Screen.width / 50 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/WickHair"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Hair.TypeHair.Meche; } foreach (Hair h in Clothing.Hairs) { if (this.typeCloth == (int)h.GetTypeHair) { x = this.typeCloth; Color fillcolor = h.Color; fillcolor.a = Mathf.Clamp01(this.smoothAparition - y * TransitionDelay); for (int i = 0; i < this.width / 3; i++) for (int j = 0; j < this.width / 3; j++) fill.SetPixel(i, j, fillcolor); fill.Apply(); rect = new Rect((Screen.width / 50 + Screen.width / 20) * x + Screen.width / 25f, y * (Screen.height / 10) + Screen.height / 2.6f, Screen.height / 11, Screen.height / 11); if (rect.Contains(Event.current.mousePosition)) tooltip = h.Description; if (this.smoothAparition > y * TransitionDelay && GUI.Button(rect, fill, skin.GetStyle("Square"))) { this.skinCharacter.Hair = h; this.skinCharacter.Apply(this.character); } y += 1; } } break; #endregion #region Gloves case (CategoryCloth.Gloves): y = 0; x = 0; foreach (Gloves g in Clothing.Gloves) { Color fillcolor = g.Color; fillcolor.a = Mathf.Clamp01(this.smoothAparition - (x + y * 3) * TransitionDelay); for (int i = 0; i < this.width / 3; i++) for (int j = 0; j < this.width / 3; j++) fill.SetPixel(i, j, fillcolor); fill.Apply(); rect = new Rect((Screen.width / 40 + Screen.width / 20) * x + Screen.width / 25f, y * (10 + Screen.height / 10) + Screen.height / 2.25f, Screen.height / 11, Screen.height / 11); if (rect.Contains(Event.current.mousePosition)) tooltip = g.Description; if (this.smoothAparition > (x + y * 3) * TransitionDelay && GUI.Button(rect, fill, skin.GetStyle("Square"))) { this.skinCharacter.Gloves = g; this.skinCharacter.Apply(this.character); } x = (x + 1) % 3; if (x == 0) y++; } break; #endregion #region Eyes case (CategoryCloth.Eyes): y = 0; x = 0; foreach (Eyes e in Clothing.Eyes) { Color fillcolor = e.Color; fillcolor.a = Mathf.Clamp01(this.smoothAparition - (x + y * 3) * TransitionDelay); for (int i = 0; i < this.width / 3; i++) for (int j = 0; j < this.width / 3; j++) fill.SetPixel(i, j, fillcolor); fill.Apply(); rect = new Rect((Screen.width / 40 + Screen.width / 20) * x + Screen.width / 25f, y * (10 + Screen.height / 10) + Screen.height / 2.25f, Screen.height / 11, Screen.height / 11); if (rect.Contains(Event.current.mousePosition)) tooltip = e.Description; if (this.smoothAparition > (x + y * 3) * TransitionDelay && GUI.Button(rect, fill, skin.GetStyle("Square"))) { this.skinCharacter.Eyes = e; this.skinCharacter.Apply(this.character); } x = (x + 1) % 3; if (x == 0) y++; } break; #endregion #region Pant case (CategoryCloth.Pant): y = 0; x = 0; rect = new Rect(Screen.width / 25f, this.posY - this.spacing * 1.5f, Screen.height / 11, Screen.height / 11); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/Overalls"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Pant.TypePant.Overalls; } rect.x += (Screen.width / 50 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/PantIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Pant.TypePant.Pant; } foreach (Pant p in Clothing.Pants) if (this.typeCloth == (int)p.GetTypePant) { x = this.typeCloth; Color fillcolor = p.Color; fillcolor.a = Mathf.Clamp01(this.smoothAparition - y * TransitionDelay); for (int i = 0; i < this.width / 3; i++) for (int j = 0; j < this.width / 3; j++) fill.SetPixel(i, j, fillcolor); fill.Apply(); rect = new Rect((Screen.width / 50 + Screen.width / 20) * x + Screen.width / 25f, y * (Screen.height / 10) + Screen.height / 2.6f, Screen.height / 11, Screen.height / 11); if (rect.Contains(Event.current.mousePosition)) tooltip = p.Description; if (this.smoothAparition > y * TransitionDelay && GUI.Button(rect, fill, skin.GetStyle("Square"))) { this.skinCharacter.Pant = p; this.skinCharacter.Apply(this.character); } y += 1; } break; #endregion #region TShirt case (CategoryCloth.TShirt): y = 0; x = 0; rect = new Rect(Screen.width / 25f, this.posY - this.spacing * 1.5f, Screen.height / 11, Screen.height / 11); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/NoneIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Tshirt.TypeTshirt.None; } rect.x += (Screen.width / 50 + Screen.width / 20); if (GUI.Button(rect, Resources.Load<Texture2D>("Sprites/Cosmetics/TshirtIcon"), skin.GetStyle("Square"))) { this.smoothAparition = 0; typeCloth = (int)Tshirt.TypeTshirt.TShirt; } foreach (Tshirt t in Clothing.Tshirts) if (this.typeCloth == (int)t.GetTypeTshirt) { x = this.typeCloth; Color fillcolor = t.Color; fillcolor.a = Mathf.Clamp01(this.smoothAparition - y * TransitionDelay); for (int i = 0; i < this.width / 3; i++) for (int j = 0; j < this.width / 3; j++) fill.SetPixel(i, j, fillcolor); fill.Apply(); rect = new Rect((Screen.width / 50 + Screen.width / 20) * x + Screen.width / 25f, y * (Screen.height / 10) + Screen.height / 2.6f, Screen.height / 11, Screen.height / 11); if (rect.Contains(Event.current.mousePosition)) tooltip = t.Description; if (this.smoothAparition > y * TransitionDelay && GUI.Button(rect, fill, skin.GetStyle("Square"))) { this.skinCharacter.Tshirt = t; this.skinCharacter.Apply(this.character); } y += 1; } break; #endregion default: break; } if (tooltip != null) GUI.Box(new Rect(Event.current.mousePosition.x - Screen.width / 20, Event.current.mousePosition.y + Screen.height / 20, 100, 35 + 20 * (tooltip.GetText().Length / 15 + 1)), tooltip.GetText(), this.skin.GetStyle("Skin")); DestroyImmediate(fill); }
private void PaintAttribute(AttrAsset attrAsset) { if (ATTR_BAR_BACK_BCK == null || ATTR_BAR_BACK_BRD == null) { ATTR_BAR_BACK_BCK = new Texture2D(1, 1, TextureFormat.ARGB32, false); ATTR_BAR_BACK_BCK.SetPixel(0, 0, new Color(0, 0, 0, 0.1f)); ATTR_BAR_BACK_BCK.Apply(); ATTR_BAR_BACK_BRD = new Texture2D(1, 1, TextureFormat.ARGB32, false); ATTR_BAR_BACK_BRD.SetPixel(0, 0, new Color(0, 0, 0, 0.65f)); ATTR_BAR_BACK_BRD.Apply(); } if (ATTR_BAR_PROGRESS == null) { ATTR_BAR_PROGRESS = new Texture2D(1, 1, TextureFormat.ARGB32, false); ATTR_BAR_PROGRESS.SetPixel(0, 0, Color.white); ATTR_BAR_PROGRESS.Apply(); } Rect rect = GUILayoutUtility.GetRect( EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth, EditorGUIUtility.singleLineHeight ); Rect rectLabel = new Rect( rect.x, rect.y, EditorGUIUtility.labelWidth, rect.height ); Rect rectBg = new Rect( rect.x + EditorGUIUtility.labelWidth, rect.y, rect.width - EditorGUIUtility.labelWidth, rect.height ); Rect rectPr = rectBg; GUIContent gcLabel = GUIContent.none; string attrName = attrAsset.attribute.shortName; switch (EditorApplication.isPlaying) { case false: rectPr = new Rect( rectBg.x + 1f, rect.y + 1f, (rectBg.width - 2f) * attrAsset.attribute.percent, rect.height - 2f ); gcLabel = new GUIContent(string.Format( PR_FMT_ED, attrName, attrAsset.attribute.percent * 100f )); break; case true: float curValue = instance.GetAttrValue(attrAsset.attribute.uniqueName); float maxValue = instance.GetAttrMaxValue(attrAsset.attribute.uniqueName); rectPr = new Rect( rectBg.x + 1f, rect.y + 1f, (rectBg.width - 2f) * (curValue / maxValue), rect.height - 2f ); gcLabel = new GUIContent(string.Format( PR_FMT_RN, attrName, curValue, maxValue )); break; } EditorGUI.LabelField(rectLabel, gcLabel, STYLE_LABEL); Color progrColor = attrAsset.attribute.color; GUI.DrawTexture(rectBg, ATTR_BAR_BACK_BCK, ScaleMode.StretchToFill, true, 0, Color.white, 0f, 0f); GUI.DrawTexture(rectBg, ATTR_BAR_BACK_BRD, ScaleMode.StretchToFill, true, 0, Color.white, 1f, 0f); GUI.DrawTexture(rectPr, ATTR_BAR_PROGRESS, ScaleMode.StretchToFill, true, 0, progrColor, 0f, 0f); }
private void DeformTerrain(Sprite explosionSprite, PolygonCollider2D explosionCollider) { Transform explosionTransform = explosionCollider.transform; Texture2D explosionTexture = explosionSprite.texture; SetSpriteData(explosionTransform, explosionSprite, out float explosionPixelWidth, out float explosionPixelHeight, out Vector2 explosionTextureStartPosition); Sprite terrainSprite = terrainRenderer.sprite; Texture2D terrainTexture = terrainSprite.texture; SetSpriteData(transform, terrainSprite, out float terrainPixelWidth, out float terrainPixelHeight, out Vector2 terrainTextureStartPosition); Color pixel; Vector2 pixelInWorldCoordinates = new Vector2(); Vector2Int terrainTextureCoordinates = new Vector2Int(); Color transparent = new Color(0, 0, 0, 0); for (int y = 0; y < explosionTexture.height; ++y) { for (int x = 0; x < explosionTexture.width; ++x) { pixel = explosionTexture.GetPixel(x, y); if (pixel.a == 0) { continue; } TextureToWorldCoordinates( ref pixelInWorldCoordinates, x, y, explosionPixelWidth, explosionPixelHeight, explosionTextureStartPosition); WorldToTextureCoordinates( ref terrainTextureCoordinates, pixelInWorldCoordinates, terrainPixelWidth, terrainPixelHeight, terrainTextureStartPosition); terrainTexture.SetPixel( terrainTextureCoordinates.x, terrainTextureCoordinates.y, transparent); } } terrainTexture.Apply(); Rect rect = new Rect(0, 0, terrainTexture.width, terrainTexture.height); Vector2 pivot = new Vector2(0.5f, 0.5f); terrainTexture.filterMode = FilterMode.Point; terrainTexture.wrapMode = TextureWrapMode.Clamp; Sprite sprite = Sprite.Create(terrainTexture, rect, pivot); terrainRenderer.sprite = sprite; mountainColliderGenerator.RegenerateCollider(); }
static public void BuildLight(BakeryLightMesh obj, int SAMPLES, Vector3[] corners, string outName = "lights.bin") { if (!allowOverwrite && lightSaved.ContainsKey(outName)) { return; } lightSaved[outName] = true; var folder = ftBuildGraphics.scenePath;//Directory.GetParent(Application.dataPath).FullName + "/frender"; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var f = new BinaryWriter(File.Open(folder + "/" + outName, FileMode.Create)); if (ftRenderLightmap.clientMode) { ftClient.serverFileList.Add(outName); } f.Write(1); Mesh mesh = null; var tform = obj.transform; Vector3[] verts; Vector2[] uv = null; int[] indices; int tris; if (corners == null) { mesh = obj.GetComponent <MeshFilter>().sharedMesh; verts = mesh.vertices; indices = mesh.triangles; tris = indices.Length / 3; if (obj.texture != null) { uv = mesh.uv; } } else { verts = corners; indices = new int[6]; indices[0] = 2; indices[1] = 1; indices[2] = 0; indices[3] = 0; indices[4] = 3; indices[5] = 2; tris = 2; if (obj.texture != null) { uv = new Vector2[4]; uv[0] = new Vector2(0, 0); uv[1] = new Vector2(0, 1); uv[2] = new Vector2(1, 1); uv[3] = new Vector2(1, 0); } } float[] area = new float[tris]; #if (OPTIMIZEDAREA || OPTIMIZEDAREA2) #else float minArea = float.MaxValue; float maxArea = -float.MaxValue; #endif float totalWorldArea = 0; //Vector2[] uv = null; int downsampleRes = 0; float[] pixels = null; string texName = ""; if (obj.texture != null) { //uv = mesh.uv; var tex = obj.texture; // Save original texture to RGBA32F DDS int existingTexHash; if (!tex2hash.TryGetValue(tex, out existingTexHash)) { existingTexHash = -1; } if (existingTexHash < 0) { int texHash = tex.GetHashCode(); tex2hash[tex] = texHash; existingTexHash = texHash; } texName = "areatex_" + existingTexHash + ".dds"; ftBuildGraphics.InitShaders(); ftBuildGraphics.SaveCookie(tex.GetNativeTexturePtr(), folder + "/" + texName ); GL.IssuePluginEvent(4); if (ftRenderLightmap.clientMode) { ftClient.serverFileList.Add(texName); } // Get downsampled (via mips) texture downsampleRes = (int)Mathf.Sqrt(SAMPLES); if (downsampleRes == 0) { downsampleRes = 1; } var downsampleRT = new RenderTexture(downsampleRes, downsampleRes, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear); var downsampleTex = new Texture2D(downsampleRes, downsampleRes, TextureFormat.RGBAFloat, false, true); Graphics.Blit(tex, downsampleRT); Graphics.SetRenderTarget(downsampleRT); downsampleTex.ReadPixels(new Rect(0, 0, downsampleRes, downsampleRes), 0, 0, false); downsampleTex.Apply(); var bytes = downsampleTex.GetRawTextureData(); pixels = new float[bytes.Length / 4]; System.Buffer.BlockCopy(bytes, 0, pixels, 0, bytes.Length); } for (int j = 0; j < tris; j++) { var v1 = verts[indices[j * 3]]; var v2 = verts[indices[j * 3 + 1]]; var v3 = verts[indices[j * 3 + 2]]; if (corners == null) { v1 = tform.TransformPoint(v1); v2 = tform.TransformPoint(v2); v3 = tform.TransformPoint(v3); } #if (OPTIMIZEDAREA || OPTIMIZEDAREA2) area[j] = Vector3.Cross(v2 - v1, v3 - v1).magnitude; if (area[j] > 0) { totalWorldArea += area[j]; } #else area[j] = Vector3.Cross(v2 - v1, v3 - v1).magnitude; if (area[j] > 0) { totalWorldArea += area[j]; } if (area[j] > 0) { minArea = Mathf.Min(minArea, area[j]); maxArea = Mathf.Max(maxArea, area[j]); } #endif } #if OPTIMIZEDAREA2 // New 2 var randomTriIndices = new int[SAMPLES]; float invTotalArea = 1.0f / (totalWorldArea * 0.5f); float sumWeights = 0.0f; for (int j = 0; j < tris; j++) { area[j] *= invTotalArea * 0.5f; sumWeights += area[j]; } float sampleWidth = sumWeights / SAMPLES; int outputSampleIx = -1; float weightSoFar = -Random.value * sampleWidth; for (int i = 0; i < SAMPLES; i++) { float sampleDist = i * sampleWidth; while (sampleDist >= weightSoFar && outputSampleIx + 1 < tris) { weightSoFar += area[++outputSampleIx]; } randomTriIndices[i] = outputSampleIx; } #elif OPTIMIZEDAREA // New // Collect indices to triangles var triIndices = new int[tris]; float invTotalArea = 1.0f / (totalWorldArea * 0.5f); for (int j = 0; j < tris; j++) { area[j] *= invTotalArea * 0.5f; triIndices[j] = j; } // Sort triangle indices by area (probability) // Smaller -> Larger System.Array.Sort(triIndices, delegate(int a, int b) { return(area[a].CompareTo(area[b])); }); // Put triangle indices into a BSP tree based on area int start = 0; int end = triIndices.Length - 1; //var bspLayers = new List<int[]>(); // tri index array per depth level var bspRoot = BuildProbabilityBSP(triIndices, area, start, end, 0, 0.0f, 1.0f); #else // Legacy if (maxArea / minArea > 65535) { minArea = maxArea / 65535; } float invMinArea = 1.0f / minArea; for (int j = 0; j < tris; j++) { area[j] *= invMinArea; area[j] = Mathf.Round(area[j]); } int skipped = 0; var uniformTriList = new List <int>(); for (int j = 0; j < tris; j++) { var tarea = area[j]; if (tarea > 0 && tarea < 65536) { for (int k = 0; k < tarea; k++) { uniformTriList.Add(j); } } else { skipped++; } } if (skipped > 0) { Debug.LogError("Skipped " + skipped + " invalid triangles out of " + tris + " on LightMesh " + obj.name + " (area is too big?)"); } #endif f.Write(obj.samples2); f.Write(SAMPLES); Vector3 trinormal; for (int sample = 0; sample < SAMPLES; sample++) { #if OPTIMIZEDAREA2 int tri = randomTriIndices[sample]; #elif OPTIMIZEDAREA int tri = GetRandomTriFromBSP(bspRoot, Random.value); //Debug.LogError(tri); #else int rndTri = Random.Range(0, uniformTriList.Count); int tri = uniformTriList.Count > 0 ? uniformTriList[rndTri] : 0; #endif var rndA = Random.value; var rndB = Random.value; var rndC = Random.value; var A = verts[indices[tri * 3]]; var B = verts[indices[tri * 3 + 1]]; var C = verts[indices[tri * 3 + 2]]; var point = (1.0f - Mathf.Sqrt(rndA)) * A + (Mathf.Sqrt(rndA) * (1.0f - rndB)) * B + (Mathf.Sqrt(rndA) * rndB) * C; if (corners == null) { point = tform.TransformPoint(point); } trinormal = Vector3.Cross(A - B, B - C).normalized; if (corners == null) { trinormal = tform.TransformDirection(trinormal); } point += trinormal * 0.001f; f.Write(point.x); f.Write(point.y); f.Write(point.z); f.Write(trinormal.x); f.Write(trinormal.y); f.Write(trinormal.z); if (obj.texture != null) { var tA = uv[indices[tri * 3]]; var tB = uv[indices[tri * 3 + 1]]; var tC = uv[indices[tri * 3 + 2]]; var tpoint = (1.0f - Mathf.Sqrt(rndA)) * tA + (Mathf.Sqrt(rndA) * (1.0f - rndB)) * tB + (Mathf.Sqrt(rndA) * rndB) * tC; int tx = (int)(tpoint.x * (downsampleRes - 1)); int ty = (int)(tpoint.y * (downsampleRes - 1)); int pixelIndex = ty * downsampleRes + tx; if (pixelIndex * 4 + 2 < pixels.Length) { float cr = pixels[pixelIndex * 4]; float cg = pixels[pixelIndex * 4 + 1]; float cb = pixels[pixelIndex * 4 + 2]; f.Write(cr); f.Write(cg); f.Write(cb); } else { f.Write(0.0f); f.Write(0.0f); f.Write(0.0f); } } //var g = GameObject.CreatePrimitive(PrimitiveType.Sphere); //g.transform.position = point; //g.transform.localScale = new Vector3(0.01f, 0.01f, 0.01f); } f.Write(obj.cutoff); f.Write(totalWorldArea * 0.5f); #if SRGBCONVERT f.Write(obj.color.linear.r * obj.intensity); f.Write(obj.color.linear.g * obj.intensity); f.Write(obj.color.linear.b * obj.intensity); #else f.Write(obj.color.r * obj.intensity); f.Write(obj.color.g * obj.intensity); f.Write(obj.color.b * obj.intensity); #endif f.Write(obj.lmid); if (obj.texture != null) { f.Write(texName); } f.Close(); }
/// <summary> /// Compares an image to a 'reference' image to see if it looks correct. /// </summary> /// <param name="expected">What the image is supposed to look like.</param> /// <param name="actual">What the image actually looks like.</param> /// <param name="settings">Optional settings that control how the comparison is performed. Can be null, in which case the images are required to be exactly identical.</param> public static void AreEqual(Texture2D expected, Texture2D actual, ImageComparisonSettings settings = null) { if (actual == null) { throw new ArgumentNullException("actual"); } #if UNITY_EDITOR var imagesWritten = new HashSet <string>(); var dirName = Path.Combine("Assets/ActualImages", string.Format("{0}/{1}/{2}", UseGraphicsTestCasesAttribute.ColorSpace, UseGraphicsTestCasesAttribute.Platform, UseGraphicsTestCasesAttribute.GraphicsDevice)); Directory.CreateDirectory(dirName); #endif try { Assert.That(expected, Is.Not.Null, "No reference image was provided."); Assert.That(actual.width, Is.EqualTo(expected.width), "The expected image had width {0}px, but the actual image had width {1}px.", expected.width, actual.width); Assert.That(actual.height, Is.EqualTo(expected.height), "The expected image had height {0}px, but the actual image had height {1}px.", expected.height, actual.height); Assert.That(actual.format, Is.EqualTo(expected.format), "The expected image had format {0} but the actual image had format {1}.", expected.format, actual.format); using (var expectedPixels = new NativeArray <Color32>(expected.GetPixels32(0), Allocator.TempJob)) using (var actualPixels = new NativeArray <Color32>(actual.GetPixels32(0), Allocator.TempJob)) using (var diffPixels = new NativeArray <Color32>(expectedPixels.Length, Allocator.TempJob)) using (var sumOverThreshold = new NativeArray <float>(Mathf.CeilToInt(expectedPixels.Length / (float)k_BatchSize), Allocator.TempJob)) { if (settings == null) { settings = new ImageComparisonSettings(); } new ComputeDiffJob { expected = expectedPixels, actual = actualPixels, diff = diffPixels, sumOverThreshold = sumOverThreshold, pixelThreshold = settings.PerPixelCorrectnessThreshold }.Schedule(expectedPixels.Length, k_BatchSize).Complete(); float averageDeltaE = sumOverThreshold.Sum() / (expected.width * expected.height); try { Assert.That(averageDeltaE, Is.LessThanOrEqualTo(settings.AverageCorrectnessThreshold)); } catch (AssertionException) { var diffImage = new Texture2D(expected.width, expected.height, TextureFormat.RGB24, false); var diffPixelsArray = new Color32[expected.width * expected.height]; diffPixels.CopyTo(diffPixelsArray); diffImage.SetPixels32(diffPixelsArray, 0); diffImage.Apply(false); #if UNITY_EDITOR if (sDontWriteToLog) { var bytes = diffImage.EncodeToPNG(); var path = Path.Combine(dirName, TestContext.CurrentContext.Test.Name + ".diff.png"); File.WriteAllBytes(path, bytes); imagesWritten.Add(path); } else #endif TestContext.CurrentContext.Test.Properties.Set("DiffImage", Convert.ToBase64String(diffImage.EncodeToPNG())); throw; } } } catch (AssertionException) { #if UNITY_EDITOR if (sDontWriteToLog) { var bytes = actual.EncodeToPNG(); var path = Path.Combine(dirName, TestContext.CurrentContext.Test.Name + ".png"); File.WriteAllBytes(path, bytes); imagesWritten.Add(path); AssetDatabase.Refresh(); UnityEditor.TestTools.Graphics.Utils.SetupReferenceImageImportSettings(imagesWritten); } else #endif TestContext.CurrentContext.Test.Properties.Set("Image", Convert.ToBase64String(actual.EncodeToPNG())); throw; } }
private Texture2D _GenerateProceduralTexture() { Texture2D proceduralTexture = new Texture2D(textureWidth, textureWidth); // The interval between circles float circleInterval = textureWidth / 4.0f; // The radius of circles float radius = textureWidth / 10.0f; // The blur factor float edgeBlur = 1.0f / blurFactor; //正常来说应该是图层叠加算法的。。。,我用另一种算法来试下 for (int w = 0; w < textureWidth; w++) { for (int h = 0; h < textureWidth; h++) { proceduralTexture.SetPixel(w, h, backgroundColor); } } Color pixel = backgroundColor; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { float circleCenterX = circleInterval * (i + 1); float circleCenterY = circleInterval * (j + 1); for (int w = Mathf.FloorToInt(circleCenterX - radius); w < Mathf.CeilToInt(circleCenterX + radius); w++) { for (int h = Mathf.FloorToInt(circleCenterY - radius); h < Mathf.CeilToInt(circleCenterY + radius); h++) { float dist = Vector2.Distance(new Vector2(w, h), new Vector2(circleCenterX, circleCenterY)) - radius; Color color; if (dist > 0) { color = pixel; } else { } color = _MixColor(circleColor, backgroundColor, Mathf.SmoothStep(0f, 1.0f, dist * edgeBlur)); proceduralTexture.SetPixel(w, h, color); } } } } /* * for (int w = 0; w < textureWidth; w++) { * for (int h = 0; h < textureWidth; h++) { * // Initalize the pixel with background color * Color pixel = backgroundColor; * * // Draw nine circles one by one * for (int i = 0; i < 3; i++) { * for (int j = 0; j < 3; j++) { * // Compute the center of current circle * Vector2 circleCenter = new Vector2(circleInterval * (i + 1), circleInterval * (j + 1)); * * // Compute the distance between the pixel and the center * float dist = Vector2.Distance(new Vector2(w, h), circleCenter) - radius; * * // Blur the edge of the circle * Color color = _MixColor(circleColor, new Color(pixel.r, pixel.g, pixel.b, 0.0f), Mathf.SmoothStep(0f, 1.0f, dist * edgeBlur)); * * // Mix the current color with the previous color * pixel = _MixColor(pixel, color, color.a); * } * } * * proceduralTexture.SetPixel(w, h, pixel); * } * } */ proceduralTexture.Apply(); return(proceduralTexture); }
public static Texture2D BuildPreviewTexture(int width, int height, Sprite sprite, Material spriteRendererMaterial, bool isPolygon) { if (!ShaderUtil.hardwareSupportsRectRenderTexture) { return((Texture2D)null); } float width1 = sprite.rect.width; float height1 = sprite.rect.height; Texture2D spriteTexture = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(sprite, false); if (!isPolygon) { PreviewHelpers.AdjustWidthAndHeightForStaticPreview((int)width1, (int)height1, ref width, ref height); } SavedRenderTargetState renderTargetState = new SavedRenderTargetState(); RenderTexture temporary = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Default); RenderTexture.active = temporary; GL.sRGBWrite = QualitySettings.activeColorSpace == ColorSpace.Linear; GL.Clear(true, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)); Texture texture = (Texture)null; Vector4 vector = new Vector4(0.0f, 0.0f, 0.0f, 0.0f); bool flag1 = false; bool flag2 = false; if ((Object)spriteRendererMaterial != (Object)null) { flag1 = spriteRendererMaterial.HasProperty("_MainTex"); flag2 = spriteRendererMaterial.HasProperty("_MainTex_TexelSize"); } Material material = (Material)null; if ((Object)spriteRendererMaterial != (Object)null) { if (flag1) { texture = spriteRendererMaterial.GetTexture("_MainTex"); spriteRendererMaterial.SetTexture("_MainTex", (Texture)spriteTexture); } if (flag2) { vector = spriteRendererMaterial.GetVector("_MainTex_TexelSize"); spriteRendererMaterial.SetVector("_MainTex_TexelSize", TextureUtil.GetTexelSizeVector((Texture)spriteTexture)); } spriteRendererMaterial.SetPass(0); } else { material = new Material(Shader.Find("Hidden/BlitCopy")); material.mainTexture = (Texture)spriteTexture; material.mainTextureScale = Vector2.one; material.mainTextureOffset = Vector2.zero; material.SetPass(0); } float num1 = sprite.rect.width / sprite.bounds.size.x; Vector2[] vertices = sprite.vertices; Vector2[] uv = sprite.uv; ushort[] triangles = sprite.triangles; Vector2 pivot = sprite.pivot; GL.PushMatrix(); GL.LoadOrtho(); GL.Color(new Color(1f, 1f, 1f, 1f)); GL.Begin(4); for (int index = 0; index < triangles.Length; ++index) { ushort num2 = triangles[index]; Vector2 vector2_1 = vertices[(int)num2]; Vector2 vector2_2 = uv[(int)num2]; GL.TexCoord(new Vector3(vector2_2.x, vector2_2.y, 0.0f)); GL.Vertex3((vector2_1.x * num1 + pivot.x) / width1, (vector2_1.y * num1 + pivot.y) / height1, 0.0f); } GL.End(); GL.PopMatrix(); GL.sRGBWrite = false; if ((Object)spriteRendererMaterial != (Object)null) { if (flag1) { spriteRendererMaterial.SetTexture("_MainTex", texture); } if (flag2) { spriteRendererMaterial.SetVector("_MainTex_TexelSize", vector); } } Texture2D texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false); texture2D.hideFlags = HideFlags.HideAndDontSave; texture2D.ReadPixels(new Rect(0.0f, 0.0f, (float)width, (float)height), 0, 0); texture2D.Apply(); RenderTexture.ReleaseTemporary(temporary); renderTargetState.Restore(); if ((Object)material != (Object)null) { Object.DestroyImmediate((Object)material); } return(texture2D); }
public void Refresh() { CreateGrid(); CreateTexture(); Quaternion q = Quaternion.Euler(rotation); Quaternion qInv = Quaternion.Inverse(q); Vector3 point00 = q * new Vector3(-0.5f, -0.5f) + offset; Vector3 point10 = q * new Vector3(0.5f, -0.5f) + offset; Vector3 point01 = q * new Vector3(-0.5f, 0.5f) + offset; Vector3 point11 = q * new Vector3(0.5f, 0.5f) + offset; NoiseMethod method = Noise.noiseMethods[(int)type][dimensions - 1]; float stepSize = 1f / resolution; float amplitude = damping ? (strength / frequency) * (1f / dampingIntensity) : strength; for (int v = 0, y = 0; y <= resolution; y++) { Vector3 point0 = Vector3.Lerp(point00, point01, y * stepSize); Vector3 point1 = Vector3.Lerp(point10, point11, y * stepSize); for (int x = 0; x <= resolution; x++, v++) { Vector3 point = Vector3.Lerp(point0, point1, x * stepSize); NoiseSample sample = Noise.Sum(method, point, frequency, octaves, lacunarity, persistence); sample *= 0.5f; sample *= amplitude; vertices[v].y = sample.value; } } mesh.vertices = vertices; mesh.RecalculateNormals(); float textureStepSize = 1f / textureResolution; for (int v = 0, y = 0; y <= textureResolution; y++) { Vector3 point0 = Vector3.Lerp(point00, point01, y * textureStepSize); Vector3 point1 = Vector3.Lerp(point10, point11, y * textureStepSize); for (int x = 0; x <= textureResolution; x++, v++) { Vector3 point = Vector3.Lerp(point0, point1, x * textureStepSize); NoiseSample sample = Noise.Sum(method, point, frequency, octaves, lacunarity, persistence); sample = type == NoiseMethodType.Value ? (sample - 0.5f) : (sample * 0.5f); if (coloringForStrength) { texture.SetPixel(x, y, coloring.Evaluate(sample.value + 0.5f)); } else { texture.SetPixel(x, y, coloring.Evaluate((sample.value * amplitude) + 0.5f)); } } } texture.Apply(); }
public Texture2D Export(Gradient gradient, int radius) { //float[,] map = new float[width, height]; ////Write texture //var tex = new Texture2D(width, height); //for (int x = 0; x < width; x++) //{ // for (int y = 0; y < height; y++) // { // Color c = Color.white; // float d = Mathf.Sqrt(x * x + y * y); // float alpha = Mathf.Min(Mathf.Max(d - radius, 0), 1); // if (alpha != 0) // { // c = gradient.Evaluate(alpha); // } // else // { // c.a = 0f; // } // tex.SetPixel(x, y, c); // } //} //tex.Apply(); //return tex; //float[,] map = new float[width, height]; //for (int x = 0; x < width; x++) //{ // for (int y = 0; y < height; y++) // { // float value = (float)data[x, y] / hightestValue; // map[x, y] += value; // for (int i = 0; i < radius; i++) // { // float nValue = (value / radius) * i; // if (x - i >= 0) // map[x - i, y] += nValue; // if (x + i < width) // map[x + i, y] += nValue; // if (y - i >= 0) // map[x, y - i] += nValue; // if (y + i < height) // map[x, y + i] += nValue; // if (x - i >= 0 && y + i < height) // map[x - i, y + i] += nValue; // if (x + i < width && y + i < height) // map[x + i, y + i] += nValue; // if (x - i >= 0 && y - i >= 0) // map[x - i, y - i] += nValue; // if (x + i < width && y - i >= 0) // map[x + i, y - i] += nValue; // } // } //} //float[,] map = new float[width, height]; //for (int x = 0; x < width; x++) //{ // for (int y = 0; y < height; y++) // { // float value = (float)data[x, y] / hightestValue; // for (int x2 = 0; x2 < width; x2++) // { // for (int y2 = 0; y2 < height; y2++) // { // float dx = x2 - x; // float dy = y2 - y; // float d = Mathf.Sqrt(dx * dx + dy * dy); // float nValue = value * Mathf.Min(Mathf.Max((radius - d) / radius, 0), 1); // map[x2, y2] += nValue; // } // } // } //} float[,] map = new float[width, height]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { float value = (float)data[x, y] / hightestValue; int sx = (x - radius) > 0 ? (x - radius) : 0; int ex = (x + radius) < (width - 1) ? (x + radius) : (width - 1); int sy = (y - radius) > 0 ? (y - radius) : 0; int ey = (y + radius) < (height - 1) ? (y + radius) : (height - 1); for (int x2 = sx; x2 < ex; x2++) { for (int y2 = sy; y2 < ey; y2++) { float dx = x2 - x; float dy = y2 - y; float d = Mathf.Sqrt(dx * dx + dy * dy); float nValue = value * Mathf.Min(Mathf.Max((radius - d) / radius, 0), 1); map[x2, y2] += nValue; } } } } //Write texture var tex = new Texture2D(width, height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { Color c = gradient.Evaluate(map[x, y]); tex.SetPixel(x, y, c); } } tex.Apply(); return(tex); }
static public Texture2D CreateTexture2DFromTilemap(STETilemap tilemap) { MakeTextureReadable(tilemap.Tileset.AtlasTexture); int tilePxSizeX = (int)tilemap.Tileset.TilePxSize.x; int tilePxSizeY = (int)tilemap.Tileset.TilePxSize.y; Texture2D output = new Texture2D(tilemap.GridWidth * tilePxSizeX, tilemap.GridHeight * tilePxSizeY, TextureFormat.ARGB32, false); output.filterMode = FilterMode.Point; output.SetPixels32(new Color32[output.width * output.height]); output.Apply(); System.Action <STETilemap, int, int, uint> action = (STETilemap source, int gridX, int gridY, uint tileData) => { gridX -= source.MinGridX; gridY -= source.MinGridY; Tile tile = tilemap.Tileset.GetTile(Tileset.GetTileIdFromTileData(tileData)); if (tile != null) { Texture2D atlasTexture = tilemap.Tileset.AtlasTexture; int tx = Mathf.RoundToInt(tile.uv.x * atlasTexture.width); int ty = Mathf.RoundToInt(tile.uv.y * atlasTexture.height); int tw = tilePxSizeX; int th = tilePxSizeY; Sprite prefabSprite = null; if (tile.prefabData.prefab) { SpriteRenderer spriteRenderer = tile.prefabData.prefab.GetComponent <SpriteRenderer>(); if (spriteRenderer && spriteRenderer.sprite) { prefabSprite = spriteRenderer.sprite; MakeTextureReadable(spriteRenderer.sprite.texture); atlasTexture = spriteRenderer.sprite.texture; tx = Mathf.RoundToInt(spriteRenderer.sprite.textureRect.x); ty = Mathf.RoundToInt(spriteRenderer.sprite.textureRect.y); tw = Mathf.RoundToInt(spriteRenderer.sprite.textureRect.width); th = Mathf.RoundToInt(spriteRenderer.sprite.textureRect.height); } } bool flipH = (tileData & Tileset.k_TileFlag_FlipH) != 0; bool flipV = (tileData & Tileset.k_TileFlag_FlipV) != 0; bool rot90 = (tileData & Tileset.k_TileFlag_Rot90) != 0; Color[] srcTileColors = atlasTexture.GetPixels(tx, ty, tw, th); if (flipH) { Color[] tempArr = new Color[0]; for (int i = 0; i < th; ++i) { tempArr = tempArr.Concat(srcTileColors.Skip(tw * i).Take(tw).Reverse()).ToArray(); } srcTileColors = tempArr; } if (flipV) { Color[] tempArr = new Color[0]; for (int i = th - 1; i >= 0; --i) { tempArr = tempArr.Concat(srcTileColors.Skip(tw * i).Take(tw)).ToArray(); } srcTileColors = tempArr; } if (rot90) { Color[] tempArr = new Color[tw * th]; for (int x = tw - 1, i = 0; x >= 0; --x) { for (int y = 0; y < th; ++y, ++i) { tempArr[i] = srcTileColors[y * tw + x]; } } srcTileColors = tempArr; int temp = tw; tw = th; th = temp; } if (prefabSprite) { Vector2 tileSize = prefabSprite.textureRect.size; Vector2 pivot = prefabSprite.pivot - prefabSprite.textureRectOffset; if (flipV) { pivot.y = -pivot.y + prefabSprite.textureRect.height; } if (flipH) { pivot.x = -pivot.x + prefabSprite.textureRect.width; } if (rot90) { pivot = new Vector2(pivot.y, tileSize.x - pivot.x); tileSize.x = prefabSprite.textureRect.size.y; tileSize.y = prefabSprite.textureRect.size.x; } Vector2 offset = pivot - tilemap.Tileset.TilePxSize / 2;// sprite.pivot + sprite.textureRect.position - sprite.textureRectOffset; BlitPixels(output, gridX * tilePxSizeX - Mathf.RoundToInt(offset.x), gridY * tilePxSizeY - Mathf.RoundToInt(offset.y), Mathf.RoundToInt(tileSize.x), Mathf.RoundToInt(tileSize.y), srcTileColors); } else { output.SetPixels(gridX * tilePxSizeX, gridY * tilePxSizeY, tw, th, srcTileColors); } } }; TilemapUtils.IterateTilemapWithAction(tilemap, action); output.Apply(); return(output); }
// Update is called once per frame void Update() { if (!_inceptionGraph.Imported) { _displayMessage = String.Format("Downloading Inception model files, {0} % of file {1}...", _inceptionGraph.DownloadProgress * 100, _inceptionGraph.DownloadFileName); } else if (_liveCameraView) { if (webcamTexture != null && webcamTexture.didUpdateThisFrame) { #region convert the webcam texture to RGBA bytes if (data == null || (data.Length != webcamTexture.width * webcamTexture.height)) { data = new Color32[webcamTexture.width * webcamTexture.height]; } webcamTexture.GetPixels32(data); if (bytes == null || bytes.Length != data.Length * 4) { bytes = new byte[data.Length * 4]; } GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned); Marshal.Copy(handle.AddrOfPinnedObject(), bytes, 0, bytes.Length); handle.Free(); #endregion #region convert the RGBA bytes to texture2D if (resultTexture == null || resultTexture.width != webcamTexture.width || resultTexture.height != webcamTexture.height) { resultTexture = new Texture2D(webcamTexture.width, webcamTexture.height, TextureFormat.RGBA32, false); } resultTexture.LoadRawTextureData(bytes); resultTexture.Apply(); #endregion if (!_textureResized) { ResizeTexture(resultTexture); _textureResized = true; } transform.rotation = baseRotation * Quaternion.AngleAxis(webcamTexture.videoRotationAngle, Vector3.up); RecognizeAndUpdateText(resultTexture); RenderTexture(resultTexture); //count++; } //DisplayText.text = _displayMessage; } else if (!_staticViewRendered) { UnityEngine.Debug.Log("Reading texture for recognition"); Texture2D texture = Resources.Load <Texture2D>("space_shuttle"); UnityEngine.Debug.Log("Starting recognition"); RecognizeAndUpdateText(texture); UnityEngine.Debug.Log("Rendering result"); RenderTexture(texture); ResizeTexture(texture); /* * Image image = this.GetComponent<Image>(); * image.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)); * var transform = image.rectTransform; * transform.sizeDelta = new Vector2(texture.width, texture.height); * transform.position = new Vector3(-texture.width / 2, -texture.height / 2); * transform.anchoredPosition = new Vector2(0, 0); //this.GetComponent<Image>().pixelInset = new Rect(-texture.width / 2, -texture.height / 2, texture.width, texture.height); */ _staticViewRendered = true; //DisplayText.text = _displayMessage; } DisplayText.text = _displayMessage; }
//Redundant public Texture2D GenerateNoiseTexture() { Texture2D noise = new Texture2D(size, size); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { float xCoord = (float)x / size * scale + offset.x; float yCoord = (float)y / size * scale + offset.y; float noiseValue = Noise(xCoord, yCoord); float fade = 1f; Color newColor = new Color(noiseValue * fade, noiseValue * fade, noiseValue * fade); noise.SetPixel(x, y, newColor); } } for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { float finalFade = 1f; int inc = 0; float getAverageNeighbours = 1f; if (x > size - edgeFadeRadius || x < edgeFadeRadius || y > size - edgeFadeRadius || y < edgeFadeRadius) { float fadeUp = 1f; float fadeRight = 1f; if (right && x > size - edgeFadeRadius) { fadeRight = Mathf.Lerp(0, 1, ((float)size - x) / (edgeFadeRadius)); } else if (left && x < edgeFadeRadius) { fadeRight = Mathf.Lerp(0, 1, ((float)x) / (edgeFadeRadius)); } if (up && y > size - edgeFadeRadius) { fadeUp = Mathf.Lerp(0, 1, ((float)size - y) / (edgeFadeRadius)); } else if (down && y < edgeFadeRadius) { fadeUp = Mathf.Lerp(0, 1, ((float)y) / (edgeFadeRadius)); } finalFade = fadeRight * fadeUp; } /* * for (int cX = x-neighbourBlend; cX < x+1+neighbourBlend; cX++) * { * for (int cY = y - neighbourBlend; cY < y + neighbourBlend + 1; cY++) * { * if (cX == x || cY == y) * continue; * * if (cX > size - 1 || cY > size - 1 || cX < 0 || cY < 0) * continue; * * inc++; * getAverageNeighbours += noise.GetPixel(cX, cY).r; * * } * getAverageNeighbours /= inc; * }*/ float v = noise.GetPixel(x, y).r *finalFade *getAverageNeighbours; Color newColor = new Color(v, v, v); noise.SetPixel(x, y, newColor); } } noise.Apply(); return(noise); }
public static Texture2D GenerateColorTexture(Color mainColor, Texture2D texture) { int width = texture.width; int height = texture.height; var hsvColor = ConvertRgbToHsv((int)(mainColor.r * 255), (int)(mainColor.g * 255), (int)(mainColor.b * 255)); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { var adjustedColor = hsvColor; adjustedColor.V = (float)y / height; adjustedColor.S = (float)x / width; var color = ConvertHsvToRgb(adjustedColor.H, adjustedColor.S, adjustedColor.V); texture.SetPixel(x, y, color); } } texture.Apply(); return texture; }
//Later blend to match the neighbours, so I need a neighbour manager to know what the left, right, up etc. actually is //My having this sepration of the terrains but still being able to connec them I think it is powerful. private void Blend(Texture2D noise) { Parallel.For(0, size, x => { for (int y = 0; y < size; y++) { float finalFade = 1f; int inc = 0; float getAverageNeighbours = 1f; if (x > size - edgeFadeRadius || x < edgeFadeRadius || y > size - edgeFadeRadius || y < edgeFadeRadius) { float fadeUp = 1f; float fadeRight = 1f; if (right && x > size - edgeFadeRadius) { fadeRight = Mathf.Lerp(0, 1, ((float)size - x) / (edgeFadeRadius)); } else if (left && x < edgeFadeRadius) { fadeRight = Mathf.Lerp(0, 1, ((float)x) / (edgeFadeRadius)); } if (up && y > size - edgeFadeRadius) { fadeUp = Mathf.Lerp(0, 1, ((float)size - y) / (edgeFadeRadius)); } else if (down && y < edgeFadeRadius) { fadeUp = Mathf.Lerp(0, 1, ((float)y) / (edgeFadeRadius)); } finalFade = fadeRight * fadeUp; } /* * for (int cX = x-neighbourBlend; cX < x+1+neighbourBlend; cX++) * { * for (int cY = y - neighbourBlend; cY < y + neighbourBlend + 1; cY++) * { * if (cX == x || cY == y) * continue; * * if (cX > size - 1 || cY > size - 1 || cX < 0 || cY < 0) * continue; * * inc++; * getAverageNeighbours += noise.GetPixel(cX, cY).r; * * } * getAverageNeighbours /= inc; * }*/ float v = Mathf.SmoothStep(0, vals[x * size + y], finalFade); vals[x * size + y] = v; } }); noise.Apply(); }
public Styles() { Texture2D textured = new Texture2D(4, 4); Color[] colors = new Color[] { Color.white, Color.white, Color.white, Color.white, Color.white, Color.clear, Color.clear, Color.white, Color.white, Color.clear, Color.clear, Color.white, Color.white, Color.white, Color.white, Color.white }; textured.SetPixels(colors); textured.filterMode = UnityEngine.FilterMode.Point; textured.Apply(); textured.hideFlags = HideFlags.HideAndDontSave; this.frame.normal.background = textured; this.frame.border = new RectOffset(2, 2, 2, 2); this.label.alignment = TextAnchor.LowerCenter; if (EditorGUIUtility.isProSkin) { this.tableHeaderColor = new Color(0.18f, 0.18f, 0.18f, 1f); this.tableLineColor = new Color(1f, 1f, 1f, 0.3f); this.parentColor = new Color(0.4f, 0.4f, 0.4f, 1f); this.selfColor = new Color(0.6f, 0.6f, 0.6f, 1f); this.simpleAnchorColor = new Color(0.7f, 0.3f, 0.3f, 1f); this.stretchAnchorColor = new Color(0f, 0.6f, 0.8f, 1f); this.anchorCornerColor = new Color(0.8f, 0.6f, 0f, 1f); this.pivotColor = new Color(0f, 0.6f, 0.8f, 1f); } else { this.tableHeaderColor = new Color(0.8f, 0.8f, 0.8f, 1f); this.tableLineColor = new Color(0f, 0f, 0f, 0.5f); this.parentColor = new Color(0.55f, 0.55f, 0.55f, 1f); this.selfColor = new Color(0.2f, 0.2f, 0.2f, 1f); this.simpleAnchorColor = new Color(0.8f, 0.3f, 0.3f, 1f); this.stretchAnchorColor = new Color(0.2f, 0.5f, 0.9f, 1f); this.anchorCornerColor = new Color(0.6f, 0.4f, 0f, 1f); this.pivotColor = new Color(0.2f, 0.5f, 0.9f, 1f); } }
private static IEnumerator TakephotoIE(Image im) { float sheight, swidth; int capx = 0; int capy = 0; int capwidth = 0; int capheight = 0; //sheight = Screen.currentResolution.height; //swidth = Screen.currentResolution.width; sheight = ca.rect.height; swidth = ca.rect.width; Vector3 v3 = Camera.main.WorldToScreenPoint(im.transform.position); //Debug.Log(v3); //Debug.Log(im.rectTransform.rect.position); //Debug.Log(im.rectTransform.rect.yMax); float rate = Mathf.Min(Screen.width / swidth, Screen.height / sheight); capwidth = (int)(im.rectTransform.rect.width * 1.0f / swidth * Screen.width); capheight = (int)(im.rectTransform.rect.height * 1.0f / sheight * Screen.height); //capwidth = (int)(im.rectTransform.rect.width * 1.0f * rate); //capheight = (int)(im.rectTransform.rect.height * 1.0f * rate); capx = (int)(v3.x - capwidth * im.rectTransform.pivot.x); capy = (int)(v3.y - capheight * im.rectTransform.pivot.y); //Debug.Log("capwidth" + capwidth); //Debug.Log("capheight" + capheight); //Debug.Log("capx" + capx); //Debug.Log("capy" + capy); //Debug.Log("sheight" + sheight); //Debug.Log("swidth" + swidth); //Debug.Log("Screen.width" + Screen.width); //Debug.Log("Screen.height" + Screen.height); if (capwidth + capx > Screen.width) { Debug.Log("1"); capwidth = Screen.width - capx; } else if (capx < 0) { Debug.Log("2"); capwidth = Screen.width + capx < 0 ? 0 : Screen.width + capx; } if (capheight + capy > Screen.height) { Debug.Log("3"); capheight = Screen.height - capy; } else if (capy < 0) { Debug.Log("4"); capheight = Screen.height + capy < 0 ? 0 : Screen.height + capy; } yield return(new WaitForEndOfFrame()); Texture2D t; t = new Texture2D(capwidth, capheight, TextureFormat.RGB24, false); //需要正确设置好图片保存格式 t.ReadPixels(new Rect(capx, capy, capwidth, capheight), 0, 0, false); //按照设定区域读取像素;注意是以左下角为原点读取 t.Compress(false); t.Apply(); //二进制转换,保存到手机 byte[] byt = t.EncodeToPNG(); string filepath = XGamePath.SavePath("temp.png");// + "/" + "temp.png"; if (File.Exists(filepath)) { File.Delete(filepath); } FileStream fs = File.Create(filepath); fs.Write(byt, 0, byt.Length); fs.Close(); fs.Dispose(); co = null; #if !UNITY_EDITOR && UNITY_IOS _SavePhoto(filepath); #endif }
public static Texture2D GetThumbnailTexture(tk2dSpriteCollectionData gen, int spriteId) { // If we already have a cached texture which matches the requirements, use that foreach (var thumb in thumbnailCache) { if (thumb.cachedTexture != null && thumb.cachedSpriteCollection == gen && thumb.cachedSpriteId == spriteId) return thumb.cachedTexture; } // Generate a texture var param = gen.spriteDefinitions[spriteId]; if (param.sourceTextureGUID == null || param.sourceTextureGUID.Length != 0) { string assetPath = AssetDatabase.GUIDToAssetPath(param.sourceTextureGUID); if (assetPath.Length > 0) { Texture2D tex = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)) as Texture2D; if (tex != null) { SCGE.SpriteThumbnailCache thumbnail = new SCGE.SpriteThumbnailCache(); if (param.extractRegion) { Texture2D localTex = new Texture2D(param.regionW, param.regionH); for (int y = 0; y < param.regionH; ++y) { for (int x = 0; x < param.regionW; ++x) { localTex.SetPixel(x, y, tex.GetPixel(param.regionX + x, param.regionY + y)); } } localTex.Apply(); thumbnail.cachedTexture = localTex; } else { thumbnail.cachedTexture = tex; } // Prime cache for next time thumbnail.cachedSpriteCollection = gen; thumbnail.cachedSpriteId = spriteId; thumbnailCache.Add(thumbnail); return thumbnail.cachedTexture; } } } // Failed to get thumbnail if (blankTexture == null) { int w = 64, h = 64; blankTexture = new Texture2D(w, h); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { blankTexture.SetPixel(x, y, Color.magenta); } } blankTexture.Apply(); } SCGE.SpriteThumbnailCache blankThumbnail = new SCGE.SpriteThumbnailCache(); blankThumbnail.cachedTexture = blankTexture; blankThumbnail.cachedSpriteCollection = gen; blankThumbnail.cachedSpriteId = spriteId; thumbnailCache.Add(blankThumbnail); return blankTexture; }
/// <summary> /// Update the visual text label. /// </summary> protected void UpdateLabel() { if (label != null) { if (mDoInit) { Init(); } bool selected = isSelected; string fullText = value; bool isEmpty = string.IsNullOrEmpty(fullText); label.color = (isEmpty && !selected) ? mDefaultColor : activeTextColor; string processed; if (isEmpty) { processed = selected ? "" : mDefaultText; RestoreLabelPivot(); } else { if (inputType == InputType.Password) { processed = ""; for (int i = 0, imax = fullText.Length; i < imax; ++i) { processed += "*"; } } else { processed = fullText; } // Start with text leading up to the selection int selPos = selected ? Mathf.Min(processed.Length, cursorPosition) : 0; string left = processed.Substring(0, selPos); // Append the composition string and the cursor character if (selected) { left += Input.compositionString; } // Append the text from the selection onwards processed = left + processed.Substring(selPos, processed.Length - selPos); // Clamped content needs to be adjusted further if (selected && label.overflowMethod == UILabel.Overflow.ClampContent) { // Determine what will actually fit into the given line int offset = label.CalculateOffsetToFit(processed); if (offset == 0) { mDrawStart = 0; RestoreLabelPivot(); } else if (selPos < mDrawStart) { mDrawStart = selPos; SetPivotToLeft(); } else if (offset < mDrawStart) { mDrawStart = offset; SetPivotToLeft(); } else { offset = label.CalculateOffsetToFit(processed.Substring(0, selPos)); if (offset > mDrawStart) { mDrawStart = offset; SetPivotToRight(); } } // If necessary, trim the front if (mDrawStart != 0) { processed = processed.Substring(mDrawStart, processed.Length - mDrawStart); } } else { mDrawStart = 0; RestoreLabelPivot(); } } label.text = processed; #if !MOBILE if (selected) { int start = mSelectionStart - mDrawStart; int end = mSelectionEnd - mDrawStart; // Blank texture used by selection and caret if (mBlankTex == null) { mBlankTex = new Texture2D(2, 2, TextureFormat.ARGB32, false); for (int y = 0; y < 2; ++y) { for (int x = 0; x < 2; ++x) { mBlankTex.SetPixel(x, y, Color.white); } } mBlankTex.Apply(); } // Create the selection highlight if (start != end) { if (mHighlight == null) { mHighlight = NGUITools.AddWidget <UITexture>(label.cachedGameObject); mHighlight.name = "Input Highlight"; mHighlight.mainTexture = mBlankTex; mHighlight.fillGeometry = false; mHighlight.pivot = label.pivot; mHighlight.SetAnchor(label.cachedTransform); } else { mHighlight.pivot = label.pivot; mHighlight.MarkAsChanged(); } } // Create the caret if (mCaret == null) { mCaret = NGUITools.AddWidget <UITexture>(label.cachedGameObject); mCaret.name = "Input Caret"; mCaret.mainTexture = mBlankTex; mCaret.fillGeometry = false; mCaret.pivot = label.pivot; mCaret.SetAnchor(label.cachedTransform); } else { mCaret.pivot = label.pivot; mCaret.MarkAsChanged(); mCaret.enabled = true; } // Fill the selection if (start != end) { label.PrintOverlay(start, end, mCaret.geometry, mHighlight.geometry, caretColor, selectionColor); mHighlight.enabled = mHighlight.geometry.hasVertices; } else { label.PrintOverlay(start, end, mCaret.geometry, null, caretColor, selectionColor); if (mHighlight != null) { mHighlight.enabled = false; } } // Reset the blinking time mNextBlink = RealTime.time + 0.5f; } else { Cleanup(); } #endif } }
// GIF exporting coroutine: preprocess the image data then send it to native code (mobile) or a worker thread (other platforms) to export GIF file. static IEnumerator CRExportGif(AnimatedClip clip, string filename, int loop, int quality, System.Threading.ThreadPriority threadPriority, Action <AnimatedClip, float> exportProgressCallback, Action <AnimatedClip, string> exportCompletedCallback) { // The encoder don't want loop to be < -1 if (loop < -1) { loop = -1; } // Compute the NeuQuant sample factor from the inverse of the quality value. // Note that NeuQuant prefers values in range [1,30] so we'll also scale the factor to that range. int sampleFac = Mathf.RoundToInt(Mathf.Lerp(30, 1, (float)(Mathf.Clamp(quality, 1, 100)) / 100)); // Construct filepath string folder; #if UNITY_EDITOR folder = Application.dataPath; // Assets folder #else folder = Application.persistentDataPath; #endif string filepath = System.IO.Path.Combine(folder, filename + ".gif"); // Construct a new export task var exportTask = new GifExportTask(); exportTask.taskId = curExportId++; // assign this task a unique id exportTask.clip = clip; exportTask.imageData = null; exportTask.filepath = filepath; exportTask.loop = loop; exportTask.sampleFac = sampleFac; exportTask.exportProgressCallback = exportProgressCallback; exportTask.exportCompletedCallback = exportCompletedCallback; exportTask.workerPriority = threadPriority; exportTask.isExporting = true; exportTask.isDone = false; exportTask.progress = 0; // Add task to the list with its unique id key gifExportTasks.Add(exportTask.taskId, exportTask); yield return(null); // Create a temporary texture to read RenderTexture data Texture2D temp = new Texture2D(clip.Width, clip.Height, TextureFormat.RGB24, false); temp.hideFlags = HideFlags.HideAndDontSave; temp.wrapMode = TextureWrapMode.Clamp; temp.filterMode = FilterMode.Bilinear; temp.anisoLevel = 0; // On iOS and Android, the GIF encoding is done in native code. // In Unity editor (and other platforms), we use Moments encoder for testing purpose. #if UNITY_EDITOR || (!UNITY_IOS && !UNITY_ANDROID) // Converts to GIF frames List <GifFrame> frames = new List <GifFrame>(clip.Frames.Length); for (int i = 0; i < clip.Frames.Length; i++) { if (clip.Frames[i] is RenderTexture) { RenderTexture source = clip.Frames[i] as RenderTexture; RenderTexture.active = source; temp.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0); temp.Apply(); RenderTexture.active = null; } else if (clip.Frames[i] is Texture2D) { temp = clip.Frames[i] as Texture2D; } else { Debug.LogError("AnimatedClip contains an unrecognized texture. Aborting..."); yield break; } GifFrame frame = new GifFrame() { Width = temp.width, Height = temp.height, Data = temp.GetPixels32() }; frames.Add(frame); OnGifPreProcessing(exportTask.taskId, (float)i / clip.Frames.Length); yield return(null); } // Setup a worker thread and let it do its magic GifEncoder encoder = new GifEncoder(loop, sampleFac); encoder.SetDelay(Mathf.RoundToInt(1000f / clip.FramePerSecond)); Worker worker = new Worker( exportTask.taskId, threadPriority, frames, encoder, filepath, OnGifExportProgress, OnGifExportCompleted); worker.Start(); #else // Allocate an array to hold the serialized image data exportTask.imageData = new Color32[clip.Frames.Length][]; // Construct the serialized image data, note that texture data is layered down-top, so flip it for (int i = 0; i < clip.Frames.Length; i++) { if (clip.Frames[i] is RenderTexture) { RenderTexture source = clip.Frames[i] as RenderTexture; RenderTexture.active = source; temp.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0); temp.Apply(); RenderTexture.active = null; } else if (clip.Frames[i] is Texture2D) { temp = clip.Frames[i] as Texture2D; } else { Debug.LogError("AnimatedClip contains an unrecognized texture. Aborting..."); yield break; } // Get the frame's pixel data exportTask.imageData[i] = temp.GetPixels32(); // Call the preprocessing handler directly float progress = (float)i / clip.Frames.Length; OnGifPreProcessing(exportTask.taskId, progress); yield return(null); } #if UNITY_IOS iOSNativeGif.ExportGif(exportTask); #elif UNITY_ANDROID AndroidNativeGif.ExportGif(exportTask); #endif #endif // UNITY_EDITOR || (!UNITY_IOS && !UNITY_ANDROID) // Dispose the temporary texture Destroy(temp); }
public static void UpdateSplatMap() { splatmap.Apply(); }
private Texture2D CreateDummyTexture(int width, int height) { Texture2D texture2D = new Texture2D(width, height); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { Color color = (x & y) <= 0 ? Color.gray : Color.white; texture2D.SetPixel(x, y, color); } } texture2D.Apply(); return texture2D; }
private Texture2D CreateDummyTexture(int width, int height) { Texture2D texture2D = new Texture2D(width, height); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Color color = ((j & i) <= 0) ? Color.gray : Color.white; texture2D.SetPixel(j, i, color); } } texture2D.Apply(); return texture2D; }