﻿/* * Box3d.cs * * Copyright (C) 2010 Alex Taylor. All Rights Reserved. * */ using System; using OpenTK; namespace Digitalis.LDTools.DOM { public struct Box3d { private Vector3d _p1, _p2; public Vector3d Point1 { get { return _p1; } set { _p1 = value; } } public Vector3d Point2 { get { return _p2; } set { _p2 = value; } } public double X1 { get { return _p1.X; } set { _p1.X = value; } } public double Y1 { get { return _p1.Y; } set { _p1.Y = value; } } public double Z1 { get { return _p1.Z; } set { _p1.Z = value; } } public double X2 { get { return _p2.X; } set { _p2.X = value; } } public double Y2 { get { return _p2.Y; } set { _p2.Y = value; } } public double Z2 { get { return _p2.Z; } set { _p2.Z = value; } } public double SizeX { get { return _p2.X - _p1.X; } set { _p2.X = value - _p1.X; } } public double SizeY { get { return _p2.Y - _p1.Y; } set { _p2.Y = value - _p1.Y; } } public double SizeZ { get { return _p2.Z - _p1.Z; } set { _p2.Z = value - _p1.Z; } } public double Length { get { return (Point2 - Point1).Length; } } public Vector3d Centre { get { return new Vector3d(X1 + SizeX / 2, Y1 + SizeY / 2, Z1 + SizeZ / 2); } set { Vector3d diff = Centre - value; Point1 += diff; Point2 += diff; } } public Box3d(double x1, double y1, double z1, double x2, double y2, double z2) : this(new Vector3d(x1, y1, z1), new Vector3d(x2, y2, z2)) { } public Box3d(Vector3d p1, Vector3d p2) { _p1.X = p1.X < p2.X ? p1.X : p2.X; _p1.Y = p1.Y < p2.Y ? p1.Y : p2.Y; _p1.Z = p1.Z < p2.Z ? p1.Z : p2.Z; _p2.X = p1.X > p2.X ? p1.X : p2.X; _p2.Y = p1.Y > p2.Y ? p1.Y : p2.Y; _p2.Z = p1.Z > p2.Z ? p1.Z : p2.Z; } public void Union(Vector3d point) { Union(ref point); } public void Union(ref Vector3d point) { if (point.X < _p1.X) _p1.X = point.X; if (point.Y < _p1.Y) _p1.Y = point.Y; if (point.Z < _p1.Z) _p1.Z = point.Z; if (point.X > _p2.X) _p2.X = point.X; if (point.Y > _p2.Y) _p2.Y = point.Y; if (point.Z > _p2.Z) _p2.Z = point.Z; } public void Union(Box3d box) { Union(ref box._p1); Union(ref box._p2); } public static void Transform(ref Box3d box, ref Matrix4d transform, out Box3d result) { if (Matrix4d.Identity == transform) { result = box; return; } Vector3d[] vertices = new Vector3d[8]; Vector3d[] results = new Vector3d[8]; vertices[0] = box._p1; vertices[1] = new Vector3d(box.X2, box.Y1, box.Z1); vertices[2] = new Vector3d(box.X2, box.Y2, box.Z1); vertices[3] = new Vector3d(box.X1, box.Y2, box.Z1); vertices[4] = new Vector3d(box.X1, box.Y1, box.Z2); vertices[5] = new Vector3d(box.X2, box.Y1, box.Z2); vertices[6] = box._p2; vertices[7] = new Vector3d(box.X1, box.Y2, box.Z2); for (int n = 0; n < vertices.Length; n++) { Vector3d.TransformPosition(ref vertices[n], ref transform, out results[n]); } result = new Box3d(results[0], results[0]); for (int n = 1; n < results.Length; n++) { result.Union(ref results[n]); } } public override string ToString() { return Point1.ToString() + " " + Point2.ToString(); } } }