Neodroid  0.2.0
Machine Learning Environment Prototyping Tool
ObjectIdSegmenter.cs
Go to the documentation of this file.
1 using System;
2 using System.Collections.Generic;
4 using UnityEngine;
5 
6 namespace droid.Runtime.Utilities.GameObjects.NeodroidCamera.Segmentation {
10  [ExecuteInEditMode]
11  public class ObjectIdSegmenter : Segmenter {
14  Renderer[] _all_renders;
15 
18  MaterialPropertyBlock _block;
19 
20  [SerializeField] Shader segmentation_shader = null;
21  [SerializeField] Camera _camera;
22 
25  public Dictionary<GameObject, Color> ColorsDictGameObject { get; set; } =
26  new Dictionary<GameObject, Color>();
27 
30  public override Dictionary<String, Color> ColorsDict {
31  get {
32  var colors = new Dictionary<String, Color>();
33  foreach (var key_val in this.ColorsDictGameObject) {
34  colors.Add(key_val.Key.GetInstanceID().ToString(), key_val.Value);
35  }
36 
37  return colors;
38  }
39  }
40 
41  // Use this for initialization
44  void Start() { this.Setup(); }
45 
46  void CheckBlock() {
47  if (this._block == null) {
48  this._block = new MaterialPropertyBlock();
49  }
50  }
51 
52  SynthesisUtilities.CapturePass[] _capture_passes = {
53  new SynthesisUtilities.CapturePass {
54  _Name =
55  "_object_id",
56  _ReplacementMode
57  = SynthesisUtilities
58  .ReplacementModes
59  .Object_id_,
60  _SupportsAntialiasing
61  = false
62  }
63  };
64 
67  void Setup() {
68  this._camera = this.GetComponent<Camera>();
69  SynthesisUtilities.SetupCapturePassesReplacementShader(this._camera,
70  this.segmentation_shader,
71  ref this._capture_passes);
72  this.ColorsDictGameObject = new Dictionary<GameObject, Color>();
73  this._all_renders = FindObjectsOfType<Renderer>();
74  this.CheckBlock();
75  foreach (var r in this._all_renders) {
76  r.GetPropertyBlock(this._block);
77  var game_object = r.gameObject;
78  var id = game_object.GetInstanceID();
79  var layer = game_object.layer;
80  var go_tag = game_object.tag;
81 
82  if (!this.ColorsDictGameObject.ContainsKey(game_object)) {
83  this.ColorsDictGameObject.Add(game_object, ColorEncoding.EncodeIdAsColor(id));
84  } else {
85  #if NEODROID_DEBUG
86  if (true) {
87  Debug.LogWarning($"ColorDict Duplicate {game_object}");
88  }
89  #endif
90  }
91 
92  this._block.SetColor(SynthesisUtilities._Shader_ObjectId_Color_Name,
93  ColorEncoding.EncodeIdAsColor(id));
94 /*
95 this._block?.SetInt(SynthesisUtils._Shader_OutputMode_Name,(int) SynthesisUtils.ReplacementModes
96  .Object_id_);
97  */
98  //this._block.SetColor("_CategoryIdColor", ColorEncoding.EncodeLayerAsColor(layer));
99  //this._block.SetColor("_MaterialIdColor", ColorEncoding.EncodeIdAsColor(id));
100  //this._block.SetColor("_CategoryColor", ColorEncoding.EncodeTagHashCodeAsColor(go_tag));
101  r.SetPropertyBlock(this._block);
102  }
103  }
104  }
105 }