Tanoda
BoundsUtils.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Generic;
3using UnityEngine;
4
6{
7 public static class BoundsUtils
8 {
9 public static Bounds CombineBounds(IEnumerable<Renderer> renderers)
10 {
11 Bounds? b = null;
12 foreach (var renderer in renderers)
13 {
14 if (b == null)
15 b = renderer.bounds;
16 else
17 b.Value.Encapsulate(renderer.bounds);
18 }
19
20 if (b == null)
21 throw new ArgumentOutOfRangeException("Need at least one renderer");
22
23 return b.Value;
24 }
25
26 public static Rect BoundsToScreenRect(this Bounds bounds, Camera camera)
27 {
28 var cen = bounds.center;
29 var ext = bounds.extents;
30 var extentPoints = new Vector2[8]
31 {
32 camera.WorldToScreenPoint(new Vector3(cen.x-ext.x, cen.y-ext.y, cen.z-ext.z)),
33 camera.WorldToScreenPoint(new Vector3(cen.x+ext.x, cen.y-ext.y, cen.z-ext.z)),
34 camera.WorldToScreenPoint(new Vector3(cen.x-ext.x, cen.y-ext.y, cen.z+ext.z)),
35 camera.WorldToScreenPoint(new Vector3(cen.x+ext.x, cen.y-ext.y, cen.z+ext.z)),
36 camera.WorldToScreenPoint(new Vector3(cen.x-ext.x, cen.y+ext.y, cen.z-ext.z)),
37 camera.WorldToScreenPoint(new Vector3(cen.x+ext.x, cen.y+ext.y, cen.z-ext.z)),
38 camera.WorldToScreenPoint(new Vector3(cen.x-ext.x, cen.y+ext.y, cen.z+ext.z)),
39 camera.WorldToScreenPoint(new Vector3(cen.x+ext.x, cen.y+ext.y, cen.z+ext.z))
40 };
41
42 var min = extentPoints[0];
43 var max = extentPoints[0];
44 foreach (var v in extentPoints)
45 {
46 min = Vector2.Min(min, v);
47 max = Vector2.Max(max, v);
48 }
49
50 return new Rect(min.x, min.y, max.x - min.x, max.y - min.y);
51 }
52
53 public static Vector2 WorldToGUIPoint(Vector3 world)
54 {
55 var screenPoint = Camera.main.WorldToScreenPoint(world);
56 screenPoint.y = Screen.height - screenPoint.y;
57 return screenPoint;
58 }
59
60 /*public static void VisualizeRenderers(List<Renderer> renderers, int type)
61 {
62 var skins = renderers.Select(x => x as SkinnedMeshRenderer).Where(x => x);
63 foreach (var skin in skins) skin.updateWhenOffscreen = true;
64
65 if ((type & 1) != 0)
66 {
67 var bounds3d = new GizmoDrawer.VectorLineUpdater();
68 bounds3d.VectorLine = new VectorLine("Bounds3D", new List<Vector3>(24), 1f, LineType.Discrete);
69 bounds3d.Draw = () =>
70 {
71 var bounds = CombineBounds(renderers);
72 bounds3d.VectorLine.MakeCube(bounds.center, bounds.size.x, bounds.size.y, bounds.size.z);
73 bounds3d.VectorLine.SetColor(Color.red);
74 bounds3d.VectorLine.Draw();
75 };
76 }
77
78 if ((type & 2) != 0)
79 {
80 var bounds2d = new GizmoDrawer.VectorLineUpdater();
81 bounds2d.VectorLine = new VectorLine("Bounds2D", new List<Vector2>(8), 1f, LineType.Discrete);
82 bounds2d.Draw = () =>
83 {
84 var bounds = CombineBounds(renderers);
85 var rect = BoundsToScreenRect(bounds, Camera.main);
86 bounds2d.VectorLine.MakeRect(rect);
87 bounds2d.VectorLine.SetColor(Color.green);
88 bounds2d.VectorLine.Draw();
89 };
90 }
91 }*/
92 }
93}