001/** 002 * Copyright (c) 2008-2014 Ardor Labs, Inc. 003 * 004 * This file is part of Ardor3D. 005 * 006 * Ardor3D is free software: you can redistribute it and/or modify it 007 * under the terms of its license which may be found in the accompanying 008 * LICENSE file or at <http://www.ardor3d.com/LICENSE>. 009 */ 010 011package com.ardor3d.bounding; 012 013import java.util.Comparator; 014 015import com.ardor3d.intersection.PrimitiveKey; 016import com.ardor3d.math.Vector3; 017import com.ardor3d.scenegraph.Mesh; 018 019public class TreeComparator implements Comparator<PrimitiveKey> { 020 enum Axis { 021 X, Y, Z; 022 } 023 024 private Axis _axis; 025 026 private Mesh _mesh; 027 028 private Vector3[] _aCompare = null; 029 030 private Vector3[] _bCompare = null; 031 032 public void setAxis(final Axis axis) { 033 _axis = axis; 034 } 035 036 public void setMesh(final Mesh mesh) { 037 _mesh = mesh; 038 } 039 040 @Override 041 public int compare(final PrimitiveKey o1, final PrimitiveKey o2) { 042 043 if (o1.equals(o2)) { 044 return 0; 045 } 046 047 Vector3 centerA = null; 048 Vector3 centerB = null; 049 _aCompare = _mesh.getMeshData().getPrimitiveVertices(o1.getPrimitiveIndex(), o1.getSection(), _aCompare); 050 _bCompare = _mesh.getMeshData().getPrimitiveVertices(o2.getPrimitiveIndex(), o2.getSection(), _bCompare); 051 052 for (int i = 1; i < _aCompare.length; i++) { 053 _aCompare[0].addLocal(_aCompare[i]); 054 } 055 for (int i = 1; i < _bCompare.length; i++) { 056 _bCompare[0].addLocal(_bCompare[i]); 057 } 058 if (_aCompare.length == _bCompare.length) { 059 // don't need average since lists are same size. (3X < 3Y ? X < Y) 060 centerA = _aCompare[0]; 061 centerB = _bCompare[0]; 062 } else { 063 // perform average since we have different size lists 064 centerA = _aCompare[0].divideLocal(_aCompare.length); 065 centerB = _bCompare[0].divideLocal(_bCompare.length); 066 } 067 068 switch (_axis) { 069 case X: 070 if (centerA.getX() < centerB.getX()) { 071 return -1; 072 } 073 if (centerA.getX() > centerB.getX()) { 074 return 1; 075 } 076 return 0; 077 case Y: 078 if (centerA.getY() < centerB.getY()) { 079 return -1; 080 } 081 if (centerA.getY() > centerB.getY()) { 082 return 1; 083 } 084 return 0; 085 case Z: 086 if (centerA.getZ() < centerB.getZ()) { 087 return -1; 088 } 089 if (centerA.getZ() > centerB.getZ()) { 090 return 1; 091 } 092 return 0; 093 default: 094 return 0; 095 } 096 } 097}