Skip to content

Instantly share code, notes, and snippets.

@minism
Created October 10, 2021 00:44
Show Gist options
  • Select an option

  • Save minism/6222bc50f4adbef64210ba420f82b6db to your computer and use it in GitHub Desktop.

Select an option

Save minism/6222bc50f4adbef64210ba420f82b6db to your computer and use it in GitHub Desktop.

Revisions

  1. minism created this gist Oct 10, 2021.
    63 changes: 63 additions & 0 deletions MapOutputNodeView.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEditor;
    using UnityEditor.UIElements;
    using UnityEditor.Experimental.GraphView;
    using UnityEngine.UIElements;
    using GraphProcessor;

    [NodeCustomEditor(typeof(MapOutputNode))]
    public class MapOutputNodeView : BaseNodeView {
    protected new MapOutputNode nodeTarget => base.nodeTarget as MapOutputNode;

    private VisualElement previewContainer;
    private Texture2D previewTexture;

    public override void Enable() {
    var node = nodeTarget as MapOutputNode;

    previewContainer = new VisualElement();
    controlsContainer.Add(previewContainer);
    controlsContainer.Add(new Label("Run for preview"));
    nodeTarget.onProcessed += UpdatePreview;
    }

    private void UpdatePreview() {
    if (nodeTarget.output == null || nodeTarget.output.GetLength(0) == 0 || nodeTarget.output.GetLength(1) == 0) {
    return;
    }
    if (previewContainer != null && previewContainer.childCount == 0) {
    CreatePreviewContainer();
    }

    // Update the actual texture.
    var data = nodeTarget.output;
    var width = data.GetLength(0);
    var height = data.GetLength(1);
    previewTexture = new Texture2D(width, height, TextureFormat.RGB24, false);
    for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
    previewTexture.SetPixel(x, y, data[x, y] == 0 ? Color.white : Color.black);
    }
    }
    previewTexture.Apply();
    }

    private void CreatePreviewContainer() {
    previewContainer.Clear();
    var mapTexture = new VisualElement();
    previewContainer.Add(mapTexture);
    mapTexture.Add(new IMGUIContainer(() => {
    var previewRect = GetPreviewRect();
    EditorGUI.DrawPreviewTexture(previewRect, previewTexture);
    }));
    }

    private Rect GetPreviewRect() {
    float width = controlsContainer.contentRect.width;
    float scaleFactor = width / nodeTarget.output.GetLength(0);
    float height = Mathf.Min(width, nodeTarget.output.GetLength(1) * scaleFactor);
    return GUILayoutUtility.GetRect(1, width, 1, height);
    }
    }