Point() public static method

public static Point ( Texture2D tex, int newWidth, int newHeight ) : void
tex UnityEngine.Texture2D
newWidth int
newHeight int
return void
Example #1
0
    /// <summary>
    /// Process analysis result, downscaling and post-processing it, preparing the texture to be written to the grid
    /// </summary>
    /// <param name="analysisResult">Analysis result texture</param>
    /// <returns></returns>
    private Texture2D ProcessAnalysisResult(Texture2D analysisResult)
    {
        //Downscale the analysis result
        TextureScale.Point(analysisResult, 64, 64);

        //string folder = @"D:\GitRepo\PublicParts\PP_AI_Studies\temp_en\helpers\";
        //ImageReadWrite.SaveImage2Path(analysisResult, folder + "p2pdownscaledOutput");

        //Create new texture with the same size as the original grid
        Texture2D resultGridTexture = new Texture2D(Size.x, Size.z);

        //Write result to texture
        for (int i = 0; i < resultGridTexture.width; i++)
        {
            for (int j = 0; j < resultGridTexture.height; j++)
            {
                int x = i;
                int y = analysisResult.height - resultGridTexture.height + j;
                resultGridTexture.SetPixel(i, j, analysisResult.GetPixel(x, y));
            }
        }
        resultGridTexture.Apply();
        //ImageReadWrite.SaveImage2Path(resultGridTexture, folder + "p2pcroppedOutput");

        //Return post-processed texture
        return(PP_ImageProcessing.PostProcessImageFromTexture(resultGridTexture));
    }
Example #2
0
    private void PlaySplashScreen()
    {
        Texture2D currentFrame = Resources.Load <Texture2D>("Textures/Splash/SplashFrame" + splashFrame);

        if (currentFrame != null)
        {
            int newWidth = currentFrame.width, newHeight = currentFrame.height;
            if (Screen.width < Screen.height)
            {
                newWidth  = (int)(Screen.width * 0.25f);
                newHeight = (int)(currentFrame.height / (currentFrame.width / ((float)newWidth)));
            }
            else
            {
                newHeight = (int)(Screen.height * 0.25f);
                newWidth  = (int)(currentFrame.width / (currentFrame.height / ((float)newHeight)));
            }
            TextureScale.Point(currentFrame, newWidth, newHeight);
            GUI.DrawTexture(new Rect(Screen.width / 2f - currentFrame.width / 2f, Screen.height / 2f - currentFrame.height / 2f, currentFrame.width, currentFrame.height), currentFrame);
            if (Time.time - lastFrameChange >= 1 / splashFPS)
            {
                splashFrame++;
                lastFrameChange = Time.time;
            }
        }
        else
        {
            Camera.main.backgroundColor = new Color((243f / 255f), (179f / 255f), (73f / 255f));
            showSplash = false;
        }
    }
Example #3
0
        private void UpdateTexture()
        {
            render.rectTransform.sizeDelta = new Vector2(size * displayMultiplier, size * displayMultiplier);

            Rect tmpRect = new Rect(webCam.width / 2 - rect.width / 2 + rect.x, webCam.height / 2 - rect.height / 2 + rect.y, rect.width, rect.height);

            texture = new Texture2D((int)tmpRect.width, (int)tmpRect.height);

            texture.SetPixels(webCam.GetPixels((int)tmpRect.x, (int)tmpRect.y, (int)tmpRect.width, (int)tmpRect.height));
            //texture.SetPixels(webCam.GetPixels());
            TextureScale.Point(texture, size, size);
            texture.SetPixels(ConvertContrasts(texture.GetPixels()));
            Vector2 centerPos = Center(ref texture) * centerDistance;

            texture.Apply();

            if (rotate)
            {
                SpriteGenerator.Rotate180(ref texture);
            }

            render.texture = texture;

            direction = centerPos;

            displayCenter.localPosition = centerPos;
        }
Example #4
0
    /// <summary>
    /// Crea un mipmapping de la textura y la guarda en la BBDD
    /// </summary>
    /// <param name="orig">Textura original</param>
    /// <param name="nombre">Nombre de la imagen original </param>
    /// <param name="ancho">Ancho que debe tener la nueva imagen</param>
    /// <param name="alto">Alto que debe tener la nueva imagen</param>
    private void MipMapping(Texture2D orig, string nombre, int ancho, int alto)
    {
        //hacemos mipmapping
        //comprobamos si alguna de las imagenes mipmapping han sido borradas para restaurarlas
        string nombreaux = nombre;

        while (ancho > 64 && alto > 64)
        {
            nombreaux = nombre + " " + ancho.ToString() + " x " + alto.ToString();

            byte[] data;
            TextureScale.Point(orig, ancho, alto);
            data = orig.EncodeToJPG();

            var p = new Textura
            {
                Nombre  = nombreaux,
                Ancho   = ancho,
                Alto    = alto,
                Image   = data,
                Nmipmap = -1
            };
            _connection.Insert(p);
            alto  = alto / 2;
            ancho = ancho / 2;
        }
    }
    public IEnumerator Save(EdgeTexture EdgeTex)
    {
        yield return(new WaitForEndOfFrame());

        var texRate = (float)EdgeTex.Texture.width / EdgeTex.Texture.height;
        // スクショは画面全体ではなく表示されている書き込み用キャンバスと同サイズにする
        var height     = Screen.height;
        var width      = Mathf.RoundToInt(Screen.height * texRate * EdgeTexture.RESOLUTION_RATE);
        var canvasRate = 1820f / 1920f;
        var left       = (Screen.width * canvasRate - width) * 0.5f;

        // 横長の画像の場合
        var bottom = 0f;

        if (width > Screen.width)
        {
            // 画面幅以上のwidthを画面幅に合わせる
            var applyRate = Screen.width * canvasRate / width;
            width  = Mathf.RoundToInt(applyRate * width);
            height = Mathf.RoundToInt(applyRate * height);
            left   = 0;
            bottom = EdgeTex.RectTransformBottom * 0.5f;
        }

        var tex = new Texture2D(width, height, TextureFormat.RGB24, false);

        tex.name = EdgeTex.Texture.name;
        tex.ReadPixels(new Rect(left, bottom, width, height), 0, 0);
        tex.Apply();

        TextureScale.Point(tex, Mathf.RoundToInt(Screen.height * texRate), height);
        yield return(EdgeTex.StartCoroutine(WriteFile(tex)));
    }
        public override void OnEnter()
        {
            if (texture.IsNone || texture.Value == null)
            {
                Debug.LogWarning("<b>[ResizeTexture]</b><color=#FF9900ff> Empty Input - Please review!</color>", this.Owner);
                Finish();
            }

            if (newTexture.IsNone || newTexture.Value == null)
            {
                Debug.LogWarning("<b>[ResizeTexture]</b><color=#FF9900ff> Empty Output - Please review!</color>", this.Owner);
                Finish();
            }

            texItem = texture.Value as Texture2D;

            switch (filterMode)
            {
            case FilterMode.Point:
                TextureScale.Point(texItem, setWidth.Value, setHeight.Value);
                break;

            case FilterMode.Biliner:
                TextureScale.Bilinear(texItem, setWidth.Value, setHeight.Value);
                break;
            }


            newTexture.Value = texItem;
            texItem          = null;

            Finish();
        }
Example #7
0
    private IEnumerator LoadFileThumbnail(List <ExplorerEntry> entries)
    {
        foreach (var entry in entries)
        {
            var icon = entry.explorerPanelItem.icon;

            if (entry.entryType == EntryType.File && IsImage(entry.extension))
            {
                //NOTE(Simon): Cancel any remaining request, if the previous coroutine was cancelled partway through
                using (var request = UnityWebRequestTexture.GetTexture("file://" + entry.fullPath, false))
                {
                    yield return(request.SendWebRequest());

                    var texture = DownloadHandlerTexture.GetContent(request);
                    var newSize = MathHelper.ScaleRatio(new Vector2(texture.width, texture.height), entry.explorerPanelItem.iconHolder.rect.size);

                    yield return(new WaitForEndOfFrame());

                    TextureScale.Point(texture, (int)newSize.x, (int)newSize.y);

                    icon.texture = texture;
                    icon.color   = Color.white;
                    icon.rectTransform.sizeDelta = newSize;
                }
            }
        }
    }
Example #8
0
    // 47 Create the method to run predictions on the grid and update
    /// <summary>
    /// Runs the predictioin model on the grid
    /// </summary>
    /// <param name="allLayers">If it should run on all layers. Default is only layer 0</param>
    void PredictAndUpdate(bool allLayers = false)
    {
        // 49 Set the red voxels to empty
        _voxelGrid.ClearReds();

        // 50 Define how many layers will be used based on bool
        int layerCount = 1;

        if (allLayers)
        {
            layerCount = _voxelGrid.GridSize.y;
        }

        // 51 Iterate through all layers, running the model
        for (int i = 0; i < layerCount; i++)
        {
            // 52 Get the image from the grid's layer
            var gridImage = _voxelGrid.ImageFromGrid(layer: i);

            // 53 Resize the image to 256x256
            ImageReadWrite.Resize256(gridImage, Color.grey);

            // 54 Run the inference model on the image
            var image = _pix2pix.Predict(gridImage);

            // 56 Scale the image back to the grid size
            TextureScale.Point(image, _voxelGrid.GridSize.x, _voxelGrid.GridSize.z);

            // 57 Set the layer's voxels' states to the grid
            _voxelGrid.SetStatesFromImage(image, layer: i);
        }
    }
Example #9
0
    void Awake()
    {
        imgPath = PlayerPrefs.GetString("img_path");

        map = ImageLoader.LoadImage(new Vector2(50, 50), imgPath);
        TextureScale.Point(map, (int)mapScale.x, (int)mapScale.y);
    }
Example #10
0
    public IEnumerator ShowPreview(int index)
    {
        var entry = entries[index - inactiveExplorerPanelItems.Count];

        if (entry.entryType == EntryType.File && IsImage(entry.extension))
        {
            texturesToDestroy.Enqueue(previewImage.texture);

            using (var request = UnityWebRequestTexture.GetTexture("file://" + entry.fullPath, false))
            {
                yield return(request.SendWebRequest());

                var texture = DownloadHandlerTexture.GetContent(request);
                var newSize = MathHelper.ScaleRatio(new Vector2(texture.width, texture.height), previewHolder.rect.size);

                TextureScale.Point(texture, (int)newSize.x, (int)newSize.y);

                texturesToDestroy.Enqueue(previewImage.texture);
                previewImage.texture = texture;
                previewImage.color   = Color.white;
                previewImage.rectTransform.sizeDelta = newSize;

                previewHolder.gameObject.SetActive(true);
            }
        }
    }
Example #11
0
        // Token: 0x0600036D RID: 877 RVA: 0x0001E658 File Offset: 0x0001C858
        private static Texture2D Load(string texfile)
        {
            if (!ACCTexturesView.outUtil.Exists(texfile))
            {
                return(null);
            }
            Texture2D texture2D = null;

            LogUtil.Debug(new object[]
            {
                "load tex:",
                texfile
            });
            try
            {
                texture2D = ACCTexturesView.outUtil.LoadTexture(texfile);
                if (texture2D.width <= 1 || texture2D.height <= 1)
                {
                    TextureScale.Point(texture2D, 90, 5);
                }
                else
                {
                    TextureScale.Bilinear(texture2D, 90, 5);
                }
            }
            catch (Exception ex)
            {
                LogUtil.Debug(new object[]
                {
                    ex
                });
            }
            return(texture2D);
        }
Example #12
0
    private void GetOverlayTextures()
    {
        for (int i = 0; i < overlays.Length; i++)
        {
            if (overlays[i] == null)
            {
                continue;
            }

            string    overlayPath = AssetDatabase.GetAssetPath(overlays[i]);
            byte[]    fileData    = File.ReadAllBytes(overlayPath);
            Texture2D tex         = new Texture2D(2, 2);
            tex.LoadImage(fileData);
            if (tex.height != 128)
            {
                TextureScale.Point(tex, 128, 128);
            }


            //Debug.Log("Processing overlay: " + overlayIcons.Count.ToString());
            overlayIcons.Add(tex);

            //Only uncomment these lines, if you know what you are doing. All overlays will be exported to a folder.
            //byte[] bytes = tex.EncodeToPNG();
            //File.WriteAllBytes(Application.dataPath + "/" + "debug" + "/" + overlays[i].name + ".png", bytes);
        }
    }
    public TextureCrop(Texture2D initialTexture, Rect rect)
    {
        if (initialTexture == null)
        {
            Debug.LogError("Texture passed is null");
            return;
        }
        if (rect.xMin > initialTexture.width || rect.yMin > initialTexture.height || rect.xMax > initialTexture.width || rect.yMax > initialTexture.height)
        {
            int reqWidth = (int)rect.xMax, reqHeight = (int)rect.yMax, newWidth = 0, newHeight = 0;
            if (reqWidth > reqHeight)
            {
                newWidth  = reqWidth;
                newHeight = initialTexture.height * newWidth / initialTexture.width;
            }
            else
            {
                newHeight = reqHeight;
                newWidth  = initialTexture.width * newHeight / initialTexture.height;
            }
            TextureScale.Point(initialTexture, newWidth, newHeight);
        }
        processedTexture = new Texture2D((int)rect.width, (int)rect.height);
        var p = initialTexture.GetPixels((int)rect.xMin, (int)rect.yMin, (int)rect.width, (int)rect.height);

        processedTexture.SetPixels(p);
        processedTexture.Apply();
    }
Example #14
0
        private static Texture2D Load(string texfile)
        {
            if (!outUtil.Exists(texfile))
            {
                return(null);
            }
            Texture2D tex = null;

            LogUtil.Debug("load tex:", texfile);
            try {
                tex = outUtil.LoadTexture(texfile);
                // サイズ変更
                if (tex.width <= 1 || tex.height <= 1)
                {
                    TextureScale.Point(tex, IMG_WIDTH, IMG_HEIGHT);
                }
                else
                {
                    TextureScale.Bilinear(tex, IMG_WIDTH, IMG_HEIGHT);
                }
            } catch (Exception e) {
                LogUtil.Debug(e);
            }
            return(tex);
        }
 void brushScaling()
 {
     //Apply current deform texture resolution
     newTex = Instantiate(deformTexture) as Texture2D;
     TextureScale.Point(newTex, deformTexture.width * (int)area / 10, deformTexture.height * (int)area / 10);
     newTex.Apply();
     craterData = newTex.GetPixels();
 }
Example #16
0
        public Texture2D ResizeTexture(Texture2D tex)
        {
            Texture2D t = tex;

            TextureScale.Point(t, 64, 64);
            t.Apply();
            return(t);
        }
Example #17
0
    /// <summary>
    /// Generate Png file from target object
    /// </summary>
    /// <param name="target">Objets/prefabs and name for target </param>
    /// <param name="pathToSave">Path to save new png file</param>
    /// <returns></returns>
    private bool GenBillboard(Target target, string pathToSave)
    {
        GameObject targetObj = target.obj;

        rawIcon = AssetPreview.GetAssetPreview(targetObj);
        icon    = rawIcon as Texture2D;

        float timeLimit = 0.0f;

        while (!icon && timeLimit < 150)
        {
            timeLimit += Time.deltaTime;
        }
        // Check the icon.
        if (icon == null)
        {
            Debug.LogError("There was an error generating image from " + targetObj.name + "! Are you sure this is an 3D object?");
            return(false);
        }

        if (setAlpha)
        {
            icon = GetFinalAlphaTexture(icon);
        }
        TextureScale.Point(icon, 256, 256); // Used for rescaling the final icon
        byte[] bytes = icon.EncodeToPNG();

        string iconName;

        if (String.IsNullOrWhiteSpace(target.name)) // Check if custom name is applied
        {
            iconName = targetObj.name;
        }
        else
        {
            iconName = target.name;
        }

        //  GameObject.Find("Canvas").GetComponent<IconGeneratorUIExample>().AddImage(icon, iconName); // Used for example, can be removed!

        if (customFolder == "") // Check if custom folder is specified!
        {
            File.WriteAllBytes(pathToSave + "/" + iconName + ".png", bytes);
            Debug.Log("File saved in: " + pathToSave + "/" + iconName + ".png");
        }
        else
        {
            File.WriteAllBytes(pathToSave + "/" + iconName + ".png", bytes);
            Debug.Log("File saved in: " + pathToSave + "/" + iconName + ".png");
        }

        // This will fix the *need to click out of the engine* to see the generated icons bug.
        AssetDatabase.Refresh();

        return(true);
    }
Example #18
0
        public static Texture2D FromModel(VOX.Model model, int tileSizePx = 1, bool enableGrid = false)
        {
            Texture2D texture = new Texture2D(16, 16);

            texture.SetPixels(model.materials.Select(mat => mat.color).ToArray());
            TextureScale.Point(texture, tileSizePx * 16, tileSizePx * 16);
            texture.filterMode = FilterMode.Point;
            texture.wrapMode   = TextureWrapMode.Clamp;
            return(texture);
        }
Example #19
0
    public static void DecreaseTextureSize(Texture2D texture, float maxSize)
    {
        if (Mathf.Max(texture.width, texture.height) > maxSize)
        {
            float ratio = Mathf.Max(texture.width, texture.height) / maxSize;
            int   decreasedWidth = (int)(texture.width / ratio), decreasedHeight = (int)(texture.height / ratio);

            TextureScale.Point(texture, decreasedWidth, decreasedHeight);
        }
    }
Example #20
0
        private Texture2D RenderTextureToTexture2D(RenderTexture texture)
        {
            Texture2D texture2D = new Texture2D(texture.width, texture.height);

            RenderTexture.active = texture;
            texture2D.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0);
            TextureScale.Point(texture2D, 300, 200);

            return(texture2D);
        }
    private Texture2D combineTextures(Generate_Terrain map, int width, int height)
    {
        Texture2D ret = new Texture2D(width, height, TextureFormat.ARGB32, true);

        Texture2D [,] texs = new Texture2D[map.terrains_width, map.terrains_height];
        for (int i = 0; i < map.terrains_width; i++)
        {
            for (int j = 0; j < map.terrains_height; j++)
            {
                texs[i, j] = new Texture2D(256, 256, TextureFormat.RGB24, true);
            }
        }



        int piece_width  = width / map.terrains_width;
        int piece_height = height / map.terrains_height;

        //Scale down each texture to the wanted size
        for (int i = 0; i < map.terrains_width; i++)
        {
            for (int j = 0; j < map.terrains_height; j++)
            {
                try {
                    //Graphics.CopyTexture(map.terrains[i, j].GetComponent<Terrain>().terrainData.splatPrototypes[0].texture, texs[i, j]);
                    texs[i, j].LoadRawTextureData(map.terrains[i, j].GetComponent <Terrain>().terrainData.splatPrototypes[0].texture.GetRawTextureData());
                    TextureScale.Point(texs[i, j], piece_width, piece_height);
                }
                catch (System.Exception e)
                {
                    Debug.LogError(map.terrains[i, j].GetComponent <Terrain>().terrainData.splatPrototypes[0].texture.height);
                    Debug.LogError(map.terrains[i, j].GetComponent <Terrain>().terrainData.splatPrototypes[0].texture.width);
                    Debug.LogError(map.terrains[i, j].GetComponent <Terrain>().terrainData.splatPrototypes[0].texture.format);
                    Debug.LogError(e.Message);
                }
            }
        }

        for (int i = 0; i < map.terrains_width; i++)
        {
            for (int j = 0; j < map.terrains_height; j++)
            {
                for (int k = 0; k < piece_width; k++)
                {
                    for (int q = 0; q < piece_height; q++)
                    {
                        ret.SetPixel((i * piece_width) + k, (j * piece_height) + q, (texs[i, j].GetPixel(k, q)));
                    }
                }
            }
        }
        ret.Apply();
        return(ret);
    }
Example #22
0
        void SaveThumbnail(Texture2D screen, string filepath)
        {
            int       h      = DataUtility.GetRelatedHeight(Tags.ThumbnailWidth);
            Texture2D newTex = Instantiate(screen);

            TextureScale.Point(newTex, Tags.ThumbnailWidth, h);
            byte[] thumbbytes = newTex.EncodeToPNG();
            File.WriteAllBytes(DataUtility.GetScreenThumbnailPath() + filepath, thumbbytes);
            Destroy(screen);
            AddThumbnail(filepath, newTex);
        }
    /*
     * width = (0 + right.localposition + right.width / 2) * 2
     * height = (0 + up.localposition + up.height / 2) * 2
     * x = 0 - width/2
     * y = 0 - height/2
     * ta-dah
     */

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Texture2D[] grayTextures = new Texture2D[crosshairImages.Length]; // off the start its used as storage

            Rect   crosshairRect = GetCrosshairRect();
            Rect[] lineRects     = new Rect[crosshairImages.Length];

            for (int i = 0; i < lineRects.Length; i++)
            {
                lineRects[i] = crosshairImages[i].GetPixelAdjustedRect();
            }

            // for this loop so we don't need to waste memory on another texture array
            for (int i = 0; i < grayTextures.Length; i++)
            {
                Texture2D tex = crosshairImages[i].texture as Texture2D;
                int       width = 3, height = 3;

                grayTextures[i] = new Texture2D(width, height);

                if (tex == null)
                {
                    Color[] pixels = new Color[width * height];

                    for (int j = 0; j < pixels.Length; j++)
                    {
                        pixels[i] = Color.white;
                    }

                    grayTextures[i].SetPixels(pixels); // Yeee?
                }
                else
                {
                    grayTextures[i].SetPixels(tex.GetPixels());
                }

                grayTextures[i].Apply();
            }

            // then again here, it gets grayified
            for (int i = 0; i < grayTextures.Length; i++)
            {
                var grayscale = CreateGrayscaleTexture(grayTextures[i]);
                TextureScale.Point(grayscale.Item1, cursWidth, cursHeight);

                grayTextures[i] = grayscale.Item1;
            }

            TryMergeTextures(grayTextures);
        }
    }
Example #24
0
 public void UpdateDaneshWithContent(object content)
 {
     if (contentVisualiser != null)
     {
         SetupOutputCanvas();
         GeneratorOutput = (Texture2D)contentVisualiser.Invoke(generator, new object[] { content, GeneratorOutput });
         // GeneratorOutput.Resize(500,500);
         TextureScale.Point(GeneratorOutput, 500, 500);
         GeneratorOutput.Apply();
         DisplayTexture(GeneratorOutput);
         Repaint();
     }
 }
Example #25
0
    public static Texture2D GetTexture2DFromPngFile(string path)
    {
        byte[] img = File.ReadAllBytes(path);

        int width  = 1024;
        int height = 512;

        Texture2D texture = new Texture2D(width, height);

        texture.LoadImage(img);
        TextureScale.Point(texture, width / 2, height / 2);
        return(texture);
    }
Example #26
0
    void SaveTextureToFile(Texture2D texture, string filename, int factor)
    {
        Texture2D copyText = new Texture2D((int)size.x, (int)size.y * factor, TextureFormat.RGB24, false);

        Graphics.CopyTexture(texture, copyText);
        TextureScale.Point(copyText, TEXTUREWIDTH, TEXTUREHEIGHT * factor);        //scale it up
        try {
            System.IO.File.WriteAllBytes(filename, copyText.EncodeToPNG());
            Debug.Log("Saved file succesfully!");
        } catch (System.Exception ex) {
            Debug.Log("Problem saving file: " + ex);
        }
    }
        /// <summary>
        /// Loads texture 2D stored at path in a resources and scales it.
        /// </summary>
        /// <returns>The asset at path if it can be found otherwise returns null.</returns>
        /// <param name="path">Pathname of the target asset.</param>
        public static Texture2D LoadScaledTexture2D(string path)
        {
            DebugEx.VerboseFormat("AssetUtils.LoadScaledTexture2D(path = {0})", path);

            Texture2D res = LoadResource <Texture2D>(path);

            if (res != null && Utils.canvasScale != 1f)
            {
                TextureScale.Point(res, (int)(res.width * Utils.canvasScale), (int)(res.height * Utils.canvasScale));
            }

            return(res);
        }
Example #28
0
 private void ApplyModifications()
 {
     if (settings.Resize)
     {
         TextureScale.Point(data.texture, settings.textureSize, settings.textureSize);
     }
     if (settings.GrayScale)
     {
         data.texture.SetPixels(ConvertContrasts(data.texture.GetPixels()));
     }
     data.texture.filterMode = FilterMode.Point;
     data.texture.Apply();
 }
    /// <summary>
    /// Generates a texture from the grid, resized properly internally.
    /// </summary>
    /// <param name="grid">The source <see cref="VoxelGrid"/></param>
    /// <returns>The result <see cref="Texture2D"/></returns>
    public static Texture2D TextureFromGrid256(VoxelGrid grid)
    {
        //string folder = @"D:\GitRepo\PublicParts\PP_AI_Studies\temp_en";
        var textureFormat = TextureFormat.RGB24;

        Vector2Int size      = new Vector2Int(grid.Size.x, grid.Size.z);
        Texture2D  gridImage = new Texture2D(size.x, size.y, textureFormat, true, true);

        for (int i = 0; i < gridImage.width; i++)
        {
            for (int j = 0; j < gridImage.height; j++)
            {
                var   voxel = grid.Voxels[i, 0, j];
                Color c     = !voxel.IsActive || voxel.IsOccupied ? Color.black : Color.white;
                gridImage.SetPixel(i, j, c);
            }
        }
        gridImage.Apply();
        //ImageReadWrite.SaveImage2Path(gridImage, folder + @"\helpers\firstOutput");

        //Construct the resulting resized image
        //Scale image up, multiplying by 4
        TextureScale.Point(gridImage, gridImage.width * 4, gridImage.height * 4);
        //Texture2D resultImage = new Texture2D(256, 256, textureFormat, true, true);
        Texture2D resultImage = new Texture2D(256, 256);

        //Set all pixels to gray
        Color[] grayPixels = new Color[256 * 256];
        var     gray       = Color.gray;

        for (int i = 0; i < grayPixels.Length; i++)
        {
            grayPixels[i] = gray;
        }
        resultImage.SetPixels(grayPixels);
        resultImage.Apply();

        //Write grid image on result image
        for (int i = 0; i < gridImage.width; i++)
        {
            for (int j = 0; j < gridImage.height; j++)
            {
                int x = i;
                int y = resultImage.height - gridImage.height + j;
                resultImage.SetPixel(x, y, gridImage.GetPixel(i, j));
            }
        }
        resultImage.Apply();

        return(resultImage);
    }
Example #30
0
    public void CreateTexArray()
    {
        int startNum = startnum;

        for (int k = 0; k < 5; k++)
        {
            Texture2DArray textureArray = new Texture2DArray(width, height, depth[k] + 2, TextureFormat.RGB24, false);

            string fullPath = directory + "/" + filePattern;
            byte[] textureData;

            Color[] black_solidColor = new Color[width * height];
            for (int i = 0; i < width * height; i++)
            {
                black_solidColor[i] = Color.black;
            }

            textureArray.SetPixels(black_solidColor, 0);

            for (int i = 1, j = startNum; i <= depth[k]; i++, j += 1)
            {
                string file = string.Format(fullPath, j);

                Texture2D tex2D;

                if (File.Exists(file))
                {
                    textureData = File.ReadAllBytes(file);
                    tex2D       = new Texture2D(originalWidth, originalHeight);
                    tex2D.LoadImage(textureData);
                    TextureScale.Point(tex2D, width, height);
                    //Debug.Log("Loaded : " + file);
                    textureArray.SetPixels(tex2D.GetPixels(), i);
                }
                else
                {
                    Debug.LogError("Failer : " + file);
                }
            }
            textureArray.SetPixels(black_solidColor, depth[k] + 1);

            textureArray.Apply();

            // CHANGEME: Path where you want to save the texture array. It must end in .asset extension for Unity to recognise it.
            string result = resultPath + "Segment_" + "1" + (4 - k) + "1" + ".asset";
            AssetDatabase.CreateAsset(textureArray, result);
            Debug.Log("Saved asset to " + fullPath);

            startNum += depth[k];
        }
    }