Neodroid  0.2.0
Machine Learning Environment Prototyping Tool
MaterialIdSegmenter.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 MaterialIdSegmenter : Segmenter {
14  Renderer[] _all_renders = null;
15 
18  MaterialPropertyBlock _block = null;
19 
20  [SerializeField] Shader segmentation_shader = null;
21  [SerializeField] Camera _camera = null;
22 
25  public Dictionary<Material, Color> ColorsDictGameObject { get; set; } = new Dictionary<Material, Color>();
26 
29  public override Dictionary<String, Color> ColorsDict {
30  get {
31  var colors = new Dictionary<String, Color>();
32  foreach (var key_val in this.ColorsDictGameObject) {
33  if (!colors.ContainsKey(key_val.Key.name)) {
34  colors.Add(key_val.Key.name, key_val.Value);
35  }
36  }
37 
38  return colors;
39  }
40  }
41 
42  // Use this for initialization
45  void Start() { this.Setup(); }
46 
47  void CheckBlock() {
48  if (this._block == null) {
49  this._block = new MaterialPropertyBlock();
50  }
51  }
52 
53  SynthesisUtilities.CapturePass[] _capture_passes = {
54  new SynthesisUtilities.CapturePass {
55  _Name =
56  "_material_id",
57  _ReplacementMode
58  = SynthesisUtilities
59  .ReplacementModes
60  .Material_id_,
61  _SupportsAntialiasing
62  = false
63  }
64  };
65 
68  void Setup() {
69  this._all_renders = FindObjectsOfType<Renderer>();
70 
71  this._camera = this.GetComponent<Camera>();
72  SynthesisUtilities.SetupCapturePassesReplacementShader(this._camera,
73  this.segmentation_shader,
74  ref this._capture_passes);
75 
76  this.ColorsDictGameObject = new Dictionary<Material, Color>();
77  this.CheckBlock();
78  foreach (var r in this._all_renders) {
79  r.GetPropertyBlock(this._block);
80  var sm = r.sharedMaterial;
81  if (sm) {
82  var id = sm.GetInstanceID();
83  var color = ColorEncoding.EncodeIdAsColor(id);
84  if (!this.ColorsDictGameObject.ContainsKey(sm)) {
85  this.ColorsDictGameObject.Add(sm, color);
86  }
87 
88  this._block.SetColor(SynthesisUtilities._Shader_MaterialId_Color_Name, color);
89  r.SetPropertyBlock(this._block);
90  }
91  }
92  }
93  }
94 }