arrayTools.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. """Routines for calculating bounding boxes, point in rectangle calculations and
  2. so on.
  3. """
  4. from fontTools.misc.roundTools import otRound
  5. from fontTools.misc.vector import Vector as _Vector
  6. import math
  7. import warnings
  8. def calcBounds(array):
  9. """Calculate the bounding rectangle of a 2D points array.
  10. Args:
  11. array: A sequence of 2D tuples.
  12. Returns:
  13. A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
  14. """
  15. if not array:
  16. return 0, 0, 0, 0
  17. xs = [x for x, y in array]
  18. ys = [y for x, y in array]
  19. return min(xs), min(ys), max(xs), max(ys)
  20. def calcIntBounds(array, round=otRound):
  21. """Calculate the integer bounding rectangle of a 2D points array.
  22. Values are rounded to closest integer towards ``+Infinity`` using the
  23. :func:`fontTools.misc.fixedTools.otRound` function by default, unless
  24. an optional ``round`` function is passed.
  25. Args:
  26. array: A sequence of 2D tuples.
  27. round: A rounding function of type ``f(x: float) -> int``.
  28. Returns:
  29. A four-item tuple of integers representing the bounding rectangle:
  30. ``(xMin, yMin, xMax, yMax)``.
  31. """
  32. return tuple(round(v) for v in calcBounds(array))
  33. def updateBounds(bounds, p, min=min, max=max):
  34. """Add a point to a bounding rectangle.
  35. Args:
  36. bounds: A bounding rectangle expressed as a tuple
  37. ``(xMin, yMin, xMax, yMax), or None``.
  38. p: A 2D tuple representing a point.
  39. min,max: functions to compute the minimum and maximum.
  40. Returns:
  41. The updated bounding rectangle ``(xMin, yMin, xMax, yMax)``.
  42. """
  43. (x, y) = p
  44. if bounds is None:
  45. return x, y, x, y
  46. xMin, yMin, xMax, yMax = bounds
  47. return min(xMin, x), min(yMin, y), max(xMax, x), max(yMax, y)
  48. def pointInRect(p, rect):
  49. """Test if a point is inside a bounding rectangle.
  50. Args:
  51. p: A 2D tuple representing a point.
  52. rect: A bounding rectangle expressed as a tuple
  53. ``(xMin, yMin, xMax, yMax)``.
  54. Returns:
  55. ``True`` if the point is inside the rectangle, ``False`` otherwise.
  56. """
  57. (x, y) = p
  58. xMin, yMin, xMax, yMax = rect
  59. return (xMin <= x <= xMax) and (yMin <= y <= yMax)
  60. def pointsInRect(array, rect):
  61. """Determine which points are inside a bounding rectangle.
  62. Args:
  63. array: A sequence of 2D tuples.
  64. rect: A bounding rectangle expressed as a tuple
  65. ``(xMin, yMin, xMax, yMax)``.
  66. Returns:
  67. A list containing the points inside the rectangle.
  68. """
  69. if len(array) < 1:
  70. return []
  71. xMin, yMin, xMax, yMax = rect
  72. return [(xMin <= x <= xMax) and (yMin <= y <= yMax) for x, y in array]
  73. def vectorLength(vector):
  74. """Calculate the length of the given vector.
  75. Args:
  76. vector: A 2D tuple.
  77. Returns:
  78. The Euclidean length of the vector.
  79. """
  80. x, y = vector
  81. return math.sqrt(x**2 + y**2)
  82. def asInt16(array):
  83. """Round a list of floats to 16-bit signed integers.
  84. Args:
  85. array: List of float values.
  86. Returns:
  87. A list of rounded integers.
  88. """
  89. return [int(math.floor(i + 0.5)) for i in array]
  90. def normRect(rect):
  91. """Normalize a bounding box rectangle.
  92. This function "turns the rectangle the right way up", so that the following
  93. holds::
  94. xMin <= xMax and yMin <= yMax
  95. Args:
  96. rect: A bounding rectangle expressed as a tuple
  97. ``(xMin, yMin, xMax, yMax)``.
  98. Returns:
  99. A normalized bounding rectangle.
  100. """
  101. (xMin, yMin, xMax, yMax) = rect
  102. return min(xMin, xMax), min(yMin, yMax), max(xMin, xMax), max(yMin, yMax)
  103. def scaleRect(rect, x, y):
  104. """Scale a bounding box rectangle.
  105. Args:
  106. rect: A bounding rectangle expressed as a tuple
  107. ``(xMin, yMin, xMax, yMax)``.
  108. x: Factor to scale the rectangle along the X axis.
  109. Y: Factor to scale the rectangle along the Y axis.
  110. Returns:
  111. A scaled bounding rectangle.
  112. """
  113. (xMin, yMin, xMax, yMax) = rect
  114. return xMin * x, yMin * y, xMax * x, yMax * y
  115. def offsetRect(rect, dx, dy):
  116. """Offset a bounding box rectangle.
  117. Args:
  118. rect: A bounding rectangle expressed as a tuple
  119. ``(xMin, yMin, xMax, yMax)``.
  120. dx: Amount to offset the rectangle along the X axis.
  121. dY: Amount to offset the rectangle along the Y axis.
  122. Returns:
  123. An offset bounding rectangle.
  124. """
  125. (xMin, yMin, xMax, yMax) = rect
  126. return xMin + dx, yMin + dy, xMax + dx, yMax + dy
  127. def insetRect(rect, dx, dy):
  128. """Inset a bounding box rectangle on all sides.
  129. Args:
  130. rect: A bounding rectangle expressed as a tuple
  131. ``(xMin, yMin, xMax, yMax)``.
  132. dx: Amount to inset the rectangle along the X axis.
  133. dY: Amount to inset the rectangle along the Y axis.
  134. Returns:
  135. An inset bounding rectangle.
  136. """
  137. (xMin, yMin, xMax, yMax) = rect
  138. return xMin + dx, yMin + dy, xMax - dx, yMax - dy
  139. def sectRect(rect1, rect2):
  140. """Test for rectangle-rectangle intersection.
  141. Args:
  142. rect1: First bounding rectangle, expressed as tuples
  143. ``(xMin, yMin, xMax, yMax)``.
  144. rect2: Second bounding rectangle.
  145. Returns:
  146. A boolean and a rectangle.
  147. If the input rectangles intersect, returns ``True`` and the intersecting
  148. rectangle. Returns ``False`` and ``(0, 0, 0, 0)`` if the input
  149. rectangles don't intersect.
  150. """
  151. (xMin1, yMin1, xMax1, yMax1) = rect1
  152. (xMin2, yMin2, xMax2, yMax2) = rect2
  153. xMin, yMin, xMax, yMax = (
  154. max(xMin1, xMin2),
  155. max(yMin1, yMin2),
  156. min(xMax1, xMax2),
  157. min(yMax1, yMax2),
  158. )
  159. if xMin >= xMax or yMin >= yMax:
  160. return False, (0, 0, 0, 0)
  161. return True, (xMin, yMin, xMax, yMax)
  162. def unionRect(rect1, rect2):
  163. """Determine union of bounding rectangles.
  164. Args:
  165. rect1: First bounding rectangle, expressed as tuples
  166. ``(xMin, yMin, xMax, yMax)``.
  167. rect2: Second bounding rectangle.
  168. Returns:
  169. The smallest rectangle in which both input rectangles are fully
  170. enclosed.
  171. """
  172. (xMin1, yMin1, xMax1, yMax1) = rect1
  173. (xMin2, yMin2, xMax2, yMax2) = rect2
  174. xMin, yMin, xMax, yMax = (
  175. min(xMin1, xMin2),
  176. min(yMin1, yMin2),
  177. max(xMax1, xMax2),
  178. max(yMax1, yMax2),
  179. )
  180. return (xMin, yMin, xMax, yMax)
  181. def rectCenter(rect):
  182. """Determine rectangle center.
  183. Args:
  184. rect: Bounding rectangle, expressed as tuples
  185. ``(xMin, yMin, xMax, yMax)``.
  186. Returns:
  187. A 2D tuple representing the point at the center of the rectangle.
  188. """
  189. (xMin, yMin, xMax, yMax) = rect
  190. return (xMin + xMax) / 2, (yMin + yMax) / 2
  191. def rectArea(rect):
  192. """Determine rectangle area.
  193. Args:
  194. rect: Bounding rectangle, expressed as tuples
  195. ``(xMin, yMin, xMax, yMax)``.
  196. Returns:
  197. The area of the rectangle.
  198. """
  199. (xMin, yMin, xMax, yMax) = rect
  200. return (yMax - yMin) * (xMax - xMin)
  201. def intRect(rect):
  202. """Round a rectangle to integer values.
  203. Guarantees that the resulting rectangle is NOT smaller than the original.
  204. Args:
  205. rect: Bounding rectangle, expressed as tuples
  206. ``(xMin, yMin, xMax, yMax)``.
  207. Returns:
  208. A rounded bounding rectangle.
  209. """
  210. (xMin, yMin, xMax, yMax) = rect
  211. xMin = int(math.floor(xMin))
  212. yMin = int(math.floor(yMin))
  213. xMax = int(math.ceil(xMax))
  214. yMax = int(math.ceil(yMax))
  215. return (xMin, yMin, xMax, yMax)
  216. def quantizeRect(rect, factor=1):
  217. """
  218. >>> bounds = (72.3, -218.4, 1201.3, 919.1)
  219. >>> quantizeRect(bounds)
  220. (72, -219, 1202, 920)
  221. >>> quantizeRect(bounds, factor=10)
  222. (70, -220, 1210, 920)
  223. >>> quantizeRect(bounds, factor=100)
  224. (0, -300, 1300, 1000)
  225. """
  226. if factor < 1:
  227. raise ValueError(f"Expected quantization factor >= 1, found: {factor!r}")
  228. xMin, yMin, xMax, yMax = normRect(rect)
  229. return (
  230. int(math.floor(xMin / factor) * factor),
  231. int(math.floor(yMin / factor) * factor),
  232. int(math.ceil(xMax / factor) * factor),
  233. int(math.ceil(yMax / factor) * factor),
  234. )
  235. class Vector(_Vector):
  236. def __init__(self, *args, **kwargs):
  237. warnings.warn(
  238. "fontTools.misc.arrayTools.Vector has been deprecated, please use "
  239. "fontTools.misc.vector.Vector instead.",
  240. DeprecationWarning,
  241. )
  242. def pairwise(iterable, reverse=False):
  243. """Iterate over current and next items in iterable.
  244. Args:
  245. iterable: An iterable
  246. reverse: If true, iterate in reverse order.
  247. Returns:
  248. A iterable yielding two elements per iteration.
  249. Example:
  250. >>> tuple(pairwise([]))
  251. ()
  252. >>> tuple(pairwise([], reverse=True))
  253. ()
  254. >>> tuple(pairwise([0]))
  255. ((0, 0),)
  256. >>> tuple(pairwise([0], reverse=True))
  257. ((0, 0),)
  258. >>> tuple(pairwise([0, 1]))
  259. ((0, 1), (1, 0))
  260. >>> tuple(pairwise([0, 1], reverse=True))
  261. ((1, 0), (0, 1))
  262. >>> tuple(pairwise([0, 1, 2]))
  263. ((0, 1), (1, 2), (2, 0))
  264. >>> tuple(pairwise([0, 1, 2], reverse=True))
  265. ((2, 1), (1, 0), (0, 2))
  266. >>> tuple(pairwise(['a', 'b', 'c', 'd']))
  267. (('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'))
  268. >>> tuple(pairwise(['a', 'b', 'c', 'd'], reverse=True))
  269. (('d', 'c'), ('c', 'b'), ('b', 'a'), ('a', 'd'))
  270. """
  271. if not iterable:
  272. return
  273. if reverse:
  274. it = reversed(iterable)
  275. else:
  276. it = iter(iterable)
  277. first = next(it, None)
  278. a = first
  279. for b in it:
  280. yield (a, b)
  281. a = b
  282. yield (a, first)
  283. def _test():
  284. """
  285. >>> import math
  286. >>> calcBounds([])
  287. (0, 0, 0, 0)
  288. >>> calcBounds([(0, 40), (0, 100), (50, 50), (80, 10)])
  289. (0, 10, 80, 100)
  290. >>> updateBounds((0, 0, 0, 0), (100, 100))
  291. (0, 0, 100, 100)
  292. >>> pointInRect((50, 50), (0, 0, 100, 100))
  293. True
  294. >>> pointInRect((0, 0), (0, 0, 100, 100))
  295. True
  296. >>> pointInRect((100, 100), (0, 0, 100, 100))
  297. True
  298. >>> not pointInRect((101, 100), (0, 0, 100, 100))
  299. True
  300. >>> list(pointsInRect([(50, 50), (0, 0), (100, 100), (101, 100)], (0, 0, 100, 100)))
  301. [True, True, True, False]
  302. >>> vectorLength((3, 4))
  303. 5.0
  304. >>> vectorLength((1, 1)) == math.sqrt(2)
  305. True
  306. >>> list(asInt16([0, 0.1, 0.5, 0.9]))
  307. [0, 0, 1, 1]
  308. >>> normRect((0, 10, 100, 200))
  309. (0, 10, 100, 200)
  310. >>> normRect((100, 200, 0, 10))
  311. (0, 10, 100, 200)
  312. >>> scaleRect((10, 20, 50, 150), 1.5, 2)
  313. (15.0, 40, 75.0, 300)
  314. >>> offsetRect((10, 20, 30, 40), 5, 6)
  315. (15, 26, 35, 46)
  316. >>> insetRect((10, 20, 50, 60), 5, 10)
  317. (15, 30, 45, 50)
  318. >>> insetRect((10, 20, 50, 60), -5, -10)
  319. (5, 10, 55, 70)
  320. >>> intersects, rect = sectRect((0, 10, 20, 30), (0, 40, 20, 50))
  321. >>> not intersects
  322. True
  323. >>> intersects, rect = sectRect((0, 10, 20, 30), (5, 20, 35, 50))
  324. >>> intersects
  325. 1
  326. >>> rect
  327. (5, 20, 20, 30)
  328. >>> unionRect((0, 10, 20, 30), (0, 40, 20, 50))
  329. (0, 10, 20, 50)
  330. >>> rectCenter((0, 0, 100, 200))
  331. (50.0, 100.0)
  332. >>> rectCenter((0, 0, 100, 199.0))
  333. (50.0, 99.5)
  334. >>> intRect((0.9, 2.9, 3.1, 4.1))
  335. (0, 2, 4, 5)
  336. """
  337. if __name__ == "__main__":
  338. import sys
  339. import doctest
  340. sys.exit(doctest.testmod().failed)