/// <summary> /// Find the box that fits in maximumBox and if possible is closest to an idealBox /// </summary> /// <param name="notPackedBoxes">All available boxes</param> /// <param name="idealBox">The ideal box we are looking for</param> /// <param name="maximumBox">The absolute max dimensions that could be packed</param> /// <returns>The box that could be packed</returns> SelectedBox FindBox(List <Box> notPackedBoxes, Point3D idealBox, Point3D maximumBox) { SelectedBox foundBox = null; // Go through all boxes foreach (var box in notPackedBoxes) { // Check all orientations of the box that fit in maximum space foreach (var boxDimensions in box.Dimensions.AllRotations.Where(maximumBox.ContainsDimension)) // Order different from original. was XZY, YXZ, YZX, ZXY, ZYX { var fitsInLayer = boxDimensions.Y <= idealBox.Y; var delta = idealBox.AbsoluteDiff(boxDimensions); // Calculate absolute coordinate differences // If this box is a better fit then remember it if (foundBox == null || foundBox.IsBetterFit(fitsInLayer, delta)) { foundBox = new SelectedBox() { Box = box, PackedDimensions = boxDimensions, DeltaFromIdeal = delta, FitsInLayer = fitsInLayer }; } // If box is cube then checking one box orientation is enough if (box.Dimensions.IsCube) { break; } } } return(foundBox); }