bezierTools.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  1. # -*- coding: utf-8 -*-
  2. """fontTools.misc.bezierTools.py -- tools for working with Bezier path segments.
  3. """
  4. from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
  5. from fontTools.misc.transform import Identity
  6. import math
  7. from collections import namedtuple
  8. try:
  9. import cython
  10. COMPILED = cython.compiled
  11. except (AttributeError, ImportError):
  12. # if cython not installed, use mock module with no-op decorators and types
  13. from fontTools.misc import cython
  14. COMPILED = False
  15. Intersection = namedtuple("Intersection", ["pt", "t1", "t2"])
  16. __all__ = [
  17. "approximateCubicArcLength",
  18. "approximateCubicArcLengthC",
  19. "approximateQuadraticArcLength",
  20. "approximateQuadraticArcLengthC",
  21. "calcCubicArcLength",
  22. "calcCubicArcLengthC",
  23. "calcQuadraticArcLength",
  24. "calcQuadraticArcLengthC",
  25. "calcCubicBounds",
  26. "calcQuadraticBounds",
  27. "splitLine",
  28. "splitQuadratic",
  29. "splitCubic",
  30. "splitQuadraticAtT",
  31. "splitCubicAtT",
  32. "splitCubicAtTC",
  33. "splitCubicIntoTwoAtTC",
  34. "solveQuadratic",
  35. "solveCubic",
  36. "quadraticPointAtT",
  37. "cubicPointAtT",
  38. "cubicPointAtTC",
  39. "linePointAtT",
  40. "segmentPointAtT",
  41. "lineLineIntersections",
  42. "curveLineIntersections",
  43. "curveCurveIntersections",
  44. "segmentSegmentIntersections",
  45. ]
  46. def calcCubicArcLength(pt1, pt2, pt3, pt4, tolerance=0.005):
  47. """Calculates the arc length for a cubic Bezier segment.
  48. Whereas :func:`approximateCubicArcLength` approximates the length, this
  49. function calculates it by "measuring", recursively dividing the curve
  50. until the divided segments are shorter than ``tolerance``.
  51. Args:
  52. pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
  53. tolerance: Controls the precision of the calcuation.
  54. Returns:
  55. Arc length value.
  56. """
  57. return calcCubicArcLengthC(
  58. complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4), tolerance
  59. )
  60. def _split_cubic_into_two(p0, p1, p2, p3):
  61. mid = (p0 + 3 * (p1 + p2) + p3) * 0.125
  62. deriv3 = (p3 + p2 - p1 - p0) * 0.125
  63. return (
  64. (p0, (p0 + p1) * 0.5, mid - deriv3, mid),
  65. (mid, mid + deriv3, (p2 + p3) * 0.5, p3),
  66. )
  67. @cython.returns(cython.double)
  68. @cython.locals(
  69. p0=cython.complex,
  70. p1=cython.complex,
  71. p2=cython.complex,
  72. p3=cython.complex,
  73. )
  74. @cython.locals(mult=cython.double, arch=cython.double, box=cython.double)
  75. def _calcCubicArcLengthCRecurse(mult, p0, p1, p2, p3):
  76. arch = abs(p0 - p3)
  77. box = abs(p0 - p1) + abs(p1 - p2) + abs(p2 - p3)
  78. if arch * mult >= box:
  79. return (arch + box) * 0.5
  80. else:
  81. one, two = _split_cubic_into_two(p0, p1, p2, p3)
  82. return _calcCubicArcLengthCRecurse(mult, *one) + _calcCubicArcLengthCRecurse(
  83. mult, *two
  84. )
  85. @cython.returns(cython.double)
  86. @cython.locals(
  87. pt1=cython.complex,
  88. pt2=cython.complex,
  89. pt3=cython.complex,
  90. pt4=cython.complex,
  91. )
  92. @cython.locals(
  93. tolerance=cython.double,
  94. mult=cython.double,
  95. )
  96. def calcCubicArcLengthC(pt1, pt2, pt3, pt4, tolerance=0.005):
  97. """Calculates the arc length for a cubic Bezier segment.
  98. Args:
  99. pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
  100. tolerance: Controls the precision of the calcuation.
  101. Returns:
  102. Arc length value.
  103. """
  104. mult = 1.0 + 1.5 * tolerance # The 1.5 is a empirical hack; no math
  105. return _calcCubicArcLengthCRecurse(mult, pt1, pt2, pt3, pt4)
  106. epsilonDigits = 6
  107. epsilon = 1e-10
  108. @cython.cfunc
  109. @cython.inline
  110. @cython.returns(cython.double)
  111. @cython.locals(v1=cython.complex, v2=cython.complex)
  112. def _dot(v1, v2):
  113. return (v1 * v2.conjugate()).real
  114. @cython.cfunc
  115. @cython.inline
  116. @cython.returns(cython.double)
  117. @cython.locals(x=cython.double)
  118. def _intSecAtan(x):
  119. # In : sympy.integrate(sp.sec(sp.atan(x)))
  120. # Out: x*sqrt(x**2 + 1)/2 + asinh(x)/2
  121. return x * math.sqrt(x**2 + 1) / 2 + math.asinh(x) / 2
  122. def calcQuadraticArcLength(pt1, pt2, pt3):
  123. """Calculates the arc length for a quadratic Bezier segment.
  124. Args:
  125. pt1: Start point of the Bezier as 2D tuple.
  126. pt2: Handle point of the Bezier as 2D tuple.
  127. pt3: End point of the Bezier as 2D tuple.
  128. Returns:
  129. Arc length value.
  130. Example::
  131. >>> calcQuadraticArcLength((0, 0), (0, 0), (0, 0)) # empty segment
  132. 0.0
  133. >>> calcQuadraticArcLength((0, 0), (50, 0), (80, 0)) # collinear points
  134. 80.0
  135. >>> calcQuadraticArcLength((0, 0), (0, 50), (0, 80)) # collinear points vertical
  136. 80.0
  137. >>> calcQuadraticArcLength((0, 0), (50, 20), (100, 40)) # collinear points
  138. 107.70329614269008
  139. >>> calcQuadraticArcLength((0, 0), (0, 100), (100, 0))
  140. 154.02976155645263
  141. >>> calcQuadraticArcLength((0, 0), (0, 50), (100, 0))
  142. 120.21581243984076
  143. >>> calcQuadraticArcLength((0, 0), (50, -10), (80, 50))
  144. 102.53273816445825
  145. >>> calcQuadraticArcLength((0, 0), (40, 0), (-40, 0)) # collinear points, control point outside
  146. 66.66666666666667
  147. >>> calcQuadraticArcLength((0, 0), (40, 0), (0, 0)) # collinear points, looping back
  148. 40.0
  149. """
  150. return calcQuadraticArcLengthC(complex(*pt1), complex(*pt2), complex(*pt3))
  151. @cython.returns(cython.double)
  152. @cython.locals(
  153. pt1=cython.complex,
  154. pt2=cython.complex,
  155. pt3=cython.complex,
  156. d0=cython.complex,
  157. d1=cython.complex,
  158. d=cython.complex,
  159. n=cython.complex,
  160. )
  161. @cython.locals(
  162. scale=cython.double,
  163. origDist=cython.double,
  164. a=cython.double,
  165. b=cython.double,
  166. x0=cython.double,
  167. x1=cython.double,
  168. Len=cython.double,
  169. )
  170. def calcQuadraticArcLengthC(pt1, pt2, pt3):
  171. """Calculates the arc length for a quadratic Bezier segment.
  172. Args:
  173. pt1: Start point of the Bezier as a complex number.
  174. pt2: Handle point of the Bezier as a complex number.
  175. pt3: End point of the Bezier as a complex number.
  176. Returns:
  177. Arc length value.
  178. """
  179. # Analytical solution to the length of a quadratic bezier.
  180. # Documentation: https://github.com/fonttools/fonttools/issues/3055
  181. d0 = pt2 - pt1
  182. d1 = pt3 - pt2
  183. d = d1 - d0
  184. n = d * 1j
  185. scale = abs(n)
  186. if scale == 0.0:
  187. return abs(pt3 - pt1)
  188. origDist = _dot(n, d0)
  189. if abs(origDist) < epsilon:
  190. if _dot(d0, d1) >= 0:
  191. return abs(pt3 - pt1)
  192. a, b = abs(d0), abs(d1)
  193. return (a * a + b * b) / (a + b)
  194. x0 = _dot(d, d0) / origDist
  195. x1 = _dot(d, d1) / origDist
  196. Len = abs(2 * (_intSecAtan(x1) - _intSecAtan(x0)) * origDist / (scale * (x1 - x0)))
  197. return Len
  198. def approximateQuadraticArcLength(pt1, pt2, pt3):
  199. """Calculates the arc length for a quadratic Bezier segment.
  200. Uses Gauss-Legendre quadrature for a branch-free approximation.
  201. See :func:`calcQuadraticArcLength` for a slower but more accurate result.
  202. Args:
  203. pt1: Start point of the Bezier as 2D tuple.
  204. pt2: Handle point of the Bezier as 2D tuple.
  205. pt3: End point of the Bezier as 2D tuple.
  206. Returns:
  207. Approximate arc length value.
  208. """
  209. return approximateQuadraticArcLengthC(complex(*pt1), complex(*pt2), complex(*pt3))
  210. @cython.returns(cython.double)
  211. @cython.locals(
  212. pt1=cython.complex,
  213. pt2=cython.complex,
  214. pt3=cython.complex,
  215. )
  216. @cython.locals(
  217. v0=cython.double,
  218. v1=cython.double,
  219. v2=cython.double,
  220. )
  221. def approximateQuadraticArcLengthC(pt1, pt2, pt3):
  222. """Calculates the arc length for a quadratic Bezier segment.
  223. Uses Gauss-Legendre quadrature for a branch-free approximation.
  224. See :func:`calcQuadraticArcLength` for a slower but more accurate result.
  225. Args:
  226. pt1: Start point of the Bezier as a complex number.
  227. pt2: Handle point of the Bezier as a complex number.
  228. pt3: End point of the Bezier as a complex number.
  229. Returns:
  230. Approximate arc length value.
  231. """
  232. # This, essentially, approximates the length-of-derivative function
  233. # to be integrated with the best-matching fifth-degree polynomial
  234. # approximation of it.
  235. #
  236. # https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss.E2.80.93Legendre_quadrature
  237. # abs(BezierCurveC[2].diff(t).subs({t:T})) for T in sorted(.5, .5±sqrt(3/5)/2),
  238. # weighted 5/18, 8/18, 5/18 respectively.
  239. v0 = abs(
  240. -0.492943519233745 * pt1 + 0.430331482911935 * pt2 + 0.0626120363218102 * pt3
  241. )
  242. v1 = abs(pt3 - pt1) * 0.4444444444444444
  243. v2 = abs(
  244. -0.0626120363218102 * pt1 - 0.430331482911935 * pt2 + 0.492943519233745 * pt3
  245. )
  246. return v0 + v1 + v2
  247. def calcQuadraticBounds(pt1, pt2, pt3):
  248. """Calculates the bounding rectangle for a quadratic Bezier segment.
  249. Args:
  250. pt1: Start point of the Bezier as a 2D tuple.
  251. pt2: Handle point of the Bezier as a 2D tuple.
  252. pt3: End point of the Bezier as a 2D tuple.
  253. Returns:
  254. A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
  255. Example::
  256. >>> calcQuadraticBounds((0, 0), (50, 100), (100, 0))
  257. (0, 0, 100, 50.0)
  258. >>> calcQuadraticBounds((0, 0), (100, 0), (100, 100))
  259. (0.0, 0.0, 100, 100)
  260. """
  261. (ax, ay), (bx, by), (cx, cy) = calcQuadraticParameters(pt1, pt2, pt3)
  262. ax2 = ax * 2.0
  263. ay2 = ay * 2.0
  264. roots = []
  265. if ax2 != 0:
  266. roots.append(-bx / ax2)
  267. if ay2 != 0:
  268. roots.append(-by / ay2)
  269. points = [
  270. (ax * t * t + bx * t + cx, ay * t * t + by * t + cy)
  271. for t in roots
  272. if 0 <= t < 1
  273. ] + [pt1, pt3]
  274. return calcBounds(points)
  275. def approximateCubicArcLength(pt1, pt2, pt3, pt4):
  276. """Approximates the arc length for a cubic Bezier segment.
  277. Uses Gauss-Lobatto quadrature with n=5 points to approximate arc length.
  278. See :func:`calcCubicArcLength` for a slower but more accurate result.
  279. Args:
  280. pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
  281. Returns:
  282. Arc length value.
  283. Example::
  284. >>> approximateCubicArcLength((0, 0), (25, 100), (75, 100), (100, 0))
  285. 190.04332968932817
  286. >>> approximateCubicArcLength((0, 0), (50, 0), (100, 50), (100, 100))
  287. 154.8852074945903
  288. >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (150, 0)) # line; exact result should be 150.
  289. 149.99999999999991
  290. >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (-50, 0)) # cusp; exact result should be 150.
  291. 136.9267662156362
  292. >>> approximateCubicArcLength((0, 0), (50, 0), (100, -50), (-50, 0)) # cusp
  293. 154.80848416537057
  294. """
  295. return approximateCubicArcLengthC(
  296. complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4)
  297. )
  298. @cython.returns(cython.double)
  299. @cython.locals(
  300. pt1=cython.complex,
  301. pt2=cython.complex,
  302. pt3=cython.complex,
  303. pt4=cython.complex,
  304. )
  305. @cython.locals(
  306. v0=cython.double,
  307. v1=cython.double,
  308. v2=cython.double,
  309. v3=cython.double,
  310. v4=cython.double,
  311. )
  312. def approximateCubicArcLengthC(pt1, pt2, pt3, pt4):
  313. """Approximates the arc length for a cubic Bezier segment.
  314. Args:
  315. pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
  316. Returns:
  317. Arc length value.
  318. """
  319. # This, essentially, approximates the length-of-derivative function
  320. # to be integrated with the best-matching seventh-degree polynomial
  321. # approximation of it.
  322. #
  323. # https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss.E2.80.93Lobatto_rules
  324. # abs(BezierCurveC[3].diff(t).subs({t:T})) for T in sorted(0, .5±(3/7)**.5/2, .5, 1),
  325. # weighted 1/20, 49/180, 32/90, 49/180, 1/20 respectively.
  326. v0 = abs(pt2 - pt1) * 0.15
  327. v1 = abs(
  328. -0.558983582205757 * pt1
  329. + 0.325650248872424 * pt2
  330. + 0.208983582205757 * pt3
  331. + 0.024349751127576 * pt4
  332. )
  333. v2 = abs(pt4 - pt1 + pt3 - pt2) * 0.26666666666666666
  334. v3 = abs(
  335. -0.024349751127576 * pt1
  336. - 0.208983582205757 * pt2
  337. - 0.325650248872424 * pt3
  338. + 0.558983582205757 * pt4
  339. )
  340. v4 = abs(pt4 - pt3) * 0.15
  341. return v0 + v1 + v2 + v3 + v4
  342. def calcCubicBounds(pt1, pt2, pt3, pt4):
  343. """Calculates the bounding rectangle for a quadratic Bezier segment.
  344. Args:
  345. pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
  346. Returns:
  347. A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
  348. Example::
  349. >>> calcCubicBounds((0, 0), (25, 100), (75, 100), (100, 0))
  350. (0, 0, 100, 75.0)
  351. >>> calcCubicBounds((0, 0), (50, 0), (100, 50), (100, 100))
  352. (0.0, 0.0, 100, 100)
  353. >>> print("%f %f %f %f" % calcCubicBounds((50, 0), (0, 100), (100, 100), (50, 0)))
  354. 35.566243 0.000000 64.433757 75.000000
  355. """
  356. (ax, ay), (bx, by), (cx, cy), (dx, dy) = calcCubicParameters(pt1, pt2, pt3, pt4)
  357. # calc first derivative
  358. ax3 = ax * 3.0
  359. ay3 = ay * 3.0
  360. bx2 = bx * 2.0
  361. by2 = by * 2.0
  362. xRoots = [t for t in solveQuadratic(ax3, bx2, cx) if 0 <= t < 1]
  363. yRoots = [t for t in solveQuadratic(ay3, by2, cy) if 0 <= t < 1]
  364. roots = xRoots + yRoots
  365. points = [
  366. (
  367. ax * t * t * t + bx * t * t + cx * t + dx,
  368. ay * t * t * t + by * t * t + cy * t + dy,
  369. )
  370. for t in roots
  371. ] + [pt1, pt4]
  372. return calcBounds(points)
  373. def splitLine(pt1, pt2, where, isHorizontal):
  374. """Split a line at a given coordinate.
  375. Args:
  376. pt1: Start point of line as 2D tuple.
  377. pt2: End point of line as 2D tuple.
  378. where: Position at which to split the line.
  379. isHorizontal: Direction of the ray splitting the line. If true,
  380. ``where`` is interpreted as a Y coordinate; if false, then
  381. ``where`` is interpreted as an X coordinate.
  382. Returns:
  383. A list of two line segments (each line segment being two 2D tuples)
  384. if the line was successfully split, or a list containing the original
  385. line.
  386. Example::
  387. >>> printSegments(splitLine((0, 0), (100, 100), 50, True))
  388. ((0, 0), (50, 50))
  389. ((50, 50), (100, 100))
  390. >>> printSegments(splitLine((0, 0), (100, 100), 100, True))
  391. ((0, 0), (100, 100))
  392. >>> printSegments(splitLine((0, 0), (100, 100), 0, True))
  393. ((0, 0), (0, 0))
  394. ((0, 0), (100, 100))
  395. >>> printSegments(splitLine((0, 0), (100, 100), 0, False))
  396. ((0, 0), (0, 0))
  397. ((0, 0), (100, 100))
  398. >>> printSegments(splitLine((100, 0), (0, 0), 50, False))
  399. ((100, 0), (50, 0))
  400. ((50, 0), (0, 0))
  401. >>> printSegments(splitLine((0, 100), (0, 0), 50, True))
  402. ((0, 100), (0, 50))
  403. ((0, 50), (0, 0))
  404. """
  405. pt1x, pt1y = pt1
  406. pt2x, pt2y = pt2
  407. ax = pt2x - pt1x
  408. ay = pt2y - pt1y
  409. bx = pt1x
  410. by = pt1y
  411. a = (ax, ay)[isHorizontal]
  412. if a == 0:
  413. return [(pt1, pt2)]
  414. t = (where - (bx, by)[isHorizontal]) / a
  415. if 0 <= t < 1:
  416. midPt = ax * t + bx, ay * t + by
  417. return [(pt1, midPt), (midPt, pt2)]
  418. else:
  419. return [(pt1, pt2)]
  420. def splitQuadratic(pt1, pt2, pt3, where, isHorizontal):
  421. """Split a quadratic Bezier curve at a given coordinate.
  422. Args:
  423. pt1,pt2,pt3: Control points of the Bezier as 2D tuples.
  424. where: Position at which to split the curve.
  425. isHorizontal: Direction of the ray splitting the curve. If true,
  426. ``where`` is interpreted as a Y coordinate; if false, then
  427. ``where`` is interpreted as an X coordinate.
  428. Returns:
  429. A list of two curve segments (each curve segment being three 2D tuples)
  430. if the curve was successfully split, or a list containing the original
  431. curve.
  432. Example::
  433. >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 150, False))
  434. ((0, 0), (50, 100), (100, 0))
  435. >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, False))
  436. ((0, 0), (25, 50), (50, 50))
  437. ((50, 50), (75, 50), (100, 0))
  438. >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, False))
  439. ((0, 0), (12.5, 25), (25, 37.5))
  440. ((25, 37.5), (62.5, 75), (100, 0))
  441. >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, True))
  442. ((0, 0), (7.32233, 14.6447), (14.6447, 25))
  443. ((14.6447, 25), (50, 75), (85.3553, 25))
  444. ((85.3553, 25), (92.6777, 14.6447), (100, -7.10543e-15))
  445. >>> # XXX I'm not at all sure if the following behavior is desirable:
  446. >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, True))
  447. ((0, 0), (25, 50), (50, 50))
  448. ((50, 50), (50, 50), (50, 50))
  449. ((50, 50), (75, 50), (100, 0))
  450. """
  451. a, b, c = calcQuadraticParameters(pt1, pt2, pt3)
  452. solutions = solveQuadratic(
  453. a[isHorizontal], b[isHorizontal], c[isHorizontal] - where
  454. )
  455. solutions = sorted(t for t in solutions if 0 <= t < 1)
  456. if not solutions:
  457. return [(pt1, pt2, pt3)]
  458. return _splitQuadraticAtT(a, b, c, *solutions)
  459. def splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal):
  460. """Split a cubic Bezier curve at a given coordinate.
  461. Args:
  462. pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
  463. where: Position at which to split the curve.
  464. isHorizontal: Direction of the ray splitting the curve. If true,
  465. ``where`` is interpreted as a Y coordinate; if false, then
  466. ``where`` is interpreted as an X coordinate.
  467. Returns:
  468. A list of two curve segments (each curve segment being four 2D tuples)
  469. if the curve was successfully split, or a list containing the original
  470. curve.
  471. Example::
  472. >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 150, False))
  473. ((0, 0), (25, 100), (75, 100), (100, 0))
  474. >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 50, False))
  475. ((0, 0), (12.5, 50), (31.25, 75), (50, 75))
  476. ((50, 75), (68.75, 75), (87.5, 50), (100, 0))
  477. >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 25, True))
  478. ((0, 0), (2.29379, 9.17517), (4.79804, 17.5085), (7.47414, 25))
  479. ((7.47414, 25), (31.2886, 91.6667), (68.7114, 91.6667), (92.5259, 25))
  480. ((92.5259, 25), (95.202, 17.5085), (97.7062, 9.17517), (100, 1.77636e-15))
  481. """
  482. a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4)
  483. solutions = solveCubic(
  484. a[isHorizontal], b[isHorizontal], c[isHorizontal], d[isHorizontal] - where
  485. )
  486. solutions = sorted(t for t in solutions if 0 <= t < 1)
  487. if not solutions:
  488. return [(pt1, pt2, pt3, pt4)]
  489. return _splitCubicAtT(a, b, c, d, *solutions)
  490. def splitQuadraticAtT(pt1, pt2, pt3, *ts):
  491. """Split a quadratic Bezier curve at one or more values of t.
  492. Args:
  493. pt1,pt2,pt3: Control points of the Bezier as 2D tuples.
  494. *ts: Positions at which to split the curve.
  495. Returns:
  496. A list of curve segments (each curve segment being three 2D tuples).
  497. Examples::
  498. >>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5))
  499. ((0, 0), (25, 50), (50, 50))
  500. ((50, 50), (75, 50), (100, 0))
  501. >>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5, 0.75))
  502. ((0, 0), (25, 50), (50, 50))
  503. ((50, 50), (62.5, 50), (75, 37.5))
  504. ((75, 37.5), (87.5, 25), (100, 0))
  505. """
  506. a, b, c = calcQuadraticParameters(pt1, pt2, pt3)
  507. return _splitQuadraticAtT(a, b, c, *ts)
  508. def splitCubicAtT(pt1, pt2, pt3, pt4, *ts):
  509. """Split a cubic Bezier curve at one or more values of t.
  510. Args:
  511. pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
  512. *ts: Positions at which to split the curve.
  513. Returns:
  514. A list of curve segments (each curve segment being four 2D tuples).
  515. Examples::
  516. >>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5))
  517. ((0, 0), (12.5, 50), (31.25, 75), (50, 75))
  518. ((50, 75), (68.75, 75), (87.5, 50), (100, 0))
  519. >>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5, 0.75))
  520. ((0, 0), (12.5, 50), (31.25, 75), (50, 75))
  521. ((50, 75), (59.375, 75), (68.75, 68.75), (77.3438, 56.25))
  522. ((77.3438, 56.25), (85.9375, 43.75), (93.75, 25), (100, 0))
  523. """
  524. a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4)
  525. return _splitCubicAtT(a, b, c, d, *ts)
  526. @cython.locals(
  527. pt1=cython.complex,
  528. pt2=cython.complex,
  529. pt3=cython.complex,
  530. pt4=cython.complex,
  531. a=cython.complex,
  532. b=cython.complex,
  533. c=cython.complex,
  534. d=cython.complex,
  535. )
  536. def splitCubicAtTC(pt1, pt2, pt3, pt4, *ts):
  537. """Split a cubic Bezier curve at one or more values of t.
  538. Args:
  539. pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers..
  540. *ts: Positions at which to split the curve.
  541. Yields:
  542. Curve segments (each curve segment being four complex numbers).
  543. """
  544. a, b, c, d = calcCubicParametersC(pt1, pt2, pt3, pt4)
  545. yield from _splitCubicAtTC(a, b, c, d, *ts)
  546. @cython.returns(cython.complex)
  547. @cython.locals(
  548. t=cython.double,
  549. pt1=cython.complex,
  550. pt2=cython.complex,
  551. pt3=cython.complex,
  552. pt4=cython.complex,
  553. pointAtT=cython.complex,
  554. off1=cython.complex,
  555. off2=cython.complex,
  556. )
  557. @cython.locals(
  558. t2=cython.double, _1_t=cython.double, _1_t_2=cython.double, _2_t_1_t=cython.double
  559. )
  560. def splitCubicIntoTwoAtTC(pt1, pt2, pt3, pt4, t):
  561. """Split a cubic Bezier curve at t.
  562. Args:
  563. pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
  564. t: Position at which to split the curve.
  565. Returns:
  566. A tuple of two curve segments (each curve segment being four complex numbers).
  567. """
  568. t2 = t * t
  569. _1_t = 1 - t
  570. _1_t_2 = _1_t * _1_t
  571. _2_t_1_t = 2 * t * _1_t
  572. pointAtT = (
  573. _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4
  574. )
  575. off1 = _1_t_2 * pt1 + _2_t_1_t * pt2 + t2 * pt3
  576. off2 = _1_t_2 * pt2 + _2_t_1_t * pt3 + t2 * pt4
  577. pt2 = pt1 + (pt2 - pt1) * t
  578. pt3 = pt4 + (pt3 - pt4) * _1_t
  579. return ((pt1, pt2, off1, pointAtT), (pointAtT, off2, pt3, pt4))
  580. def _splitQuadraticAtT(a, b, c, *ts):
  581. ts = list(ts)
  582. segments = []
  583. ts.insert(0, 0.0)
  584. ts.append(1.0)
  585. ax, ay = a
  586. bx, by = b
  587. cx, cy = c
  588. for i in range(len(ts) - 1):
  589. t1 = ts[i]
  590. t2 = ts[i + 1]
  591. delta = t2 - t1
  592. # calc new a, b and c
  593. delta_2 = delta * delta
  594. a1x = ax * delta_2
  595. a1y = ay * delta_2
  596. b1x = (2 * ax * t1 + bx) * delta
  597. b1y = (2 * ay * t1 + by) * delta
  598. t1_2 = t1 * t1
  599. c1x = ax * t1_2 + bx * t1 + cx
  600. c1y = ay * t1_2 + by * t1 + cy
  601. pt1, pt2, pt3 = calcQuadraticPoints((a1x, a1y), (b1x, b1y), (c1x, c1y))
  602. segments.append((pt1, pt2, pt3))
  603. return segments
  604. def _splitCubicAtT(a, b, c, d, *ts):
  605. ts = list(ts)
  606. ts.insert(0, 0.0)
  607. ts.append(1.0)
  608. segments = []
  609. ax, ay = a
  610. bx, by = b
  611. cx, cy = c
  612. dx, dy = d
  613. for i in range(len(ts) - 1):
  614. t1 = ts[i]
  615. t2 = ts[i + 1]
  616. delta = t2 - t1
  617. delta_2 = delta * delta
  618. delta_3 = delta * delta_2
  619. t1_2 = t1 * t1
  620. t1_3 = t1 * t1_2
  621. # calc new a, b, c and d
  622. a1x = ax * delta_3
  623. a1y = ay * delta_3
  624. b1x = (3 * ax * t1 + bx) * delta_2
  625. b1y = (3 * ay * t1 + by) * delta_2
  626. c1x = (2 * bx * t1 + cx + 3 * ax * t1_2) * delta
  627. c1y = (2 * by * t1 + cy + 3 * ay * t1_2) * delta
  628. d1x = ax * t1_3 + bx * t1_2 + cx * t1 + dx
  629. d1y = ay * t1_3 + by * t1_2 + cy * t1 + dy
  630. pt1, pt2, pt3, pt4 = calcCubicPoints(
  631. (a1x, a1y), (b1x, b1y), (c1x, c1y), (d1x, d1y)
  632. )
  633. segments.append((pt1, pt2, pt3, pt4))
  634. return segments
  635. @cython.locals(
  636. a=cython.complex,
  637. b=cython.complex,
  638. c=cython.complex,
  639. d=cython.complex,
  640. t1=cython.double,
  641. t2=cython.double,
  642. delta=cython.double,
  643. delta_2=cython.double,
  644. delta_3=cython.double,
  645. a1=cython.complex,
  646. b1=cython.complex,
  647. c1=cython.complex,
  648. d1=cython.complex,
  649. )
  650. def _splitCubicAtTC(a, b, c, d, *ts):
  651. ts = list(ts)
  652. ts.insert(0, 0.0)
  653. ts.append(1.0)
  654. for i in range(len(ts) - 1):
  655. t1 = ts[i]
  656. t2 = ts[i + 1]
  657. delta = t2 - t1
  658. delta_2 = delta * delta
  659. delta_3 = delta * delta_2
  660. t1_2 = t1 * t1
  661. t1_3 = t1 * t1_2
  662. # calc new a, b, c and d
  663. a1 = a * delta_3
  664. b1 = (3 * a * t1 + b) * delta_2
  665. c1 = (2 * b * t1 + c + 3 * a * t1_2) * delta
  666. d1 = a * t1_3 + b * t1_2 + c * t1 + d
  667. pt1, pt2, pt3, pt4 = calcCubicPointsC(a1, b1, c1, d1)
  668. yield (pt1, pt2, pt3, pt4)
  669. #
  670. # Equation solvers.
  671. #
  672. from math import sqrt, acos, cos, pi
  673. def solveQuadratic(a, b, c, sqrt=sqrt):
  674. """Solve a quadratic equation.
  675. Solves *a*x*x + b*x + c = 0* where a, b and c are real.
  676. Args:
  677. a: coefficient of *x²*
  678. b: coefficient of *x*
  679. c: constant term
  680. Returns:
  681. A list of roots. Note that the returned list is neither guaranteed to
  682. be sorted nor to contain unique values!
  683. """
  684. if abs(a) < epsilon:
  685. if abs(b) < epsilon:
  686. # We have a non-equation; therefore, we have no valid solution
  687. roots = []
  688. else:
  689. # We have a linear equation with 1 root.
  690. roots = [-c / b]
  691. else:
  692. # We have a true quadratic equation. Apply the quadratic formula to find two roots.
  693. DD = b * b - 4.0 * a * c
  694. if DD >= 0.0:
  695. rDD = sqrt(DD)
  696. roots = [(-b + rDD) / 2.0 / a, (-b - rDD) / 2.0 / a]
  697. else:
  698. # complex roots, ignore
  699. roots = []
  700. return roots
  701. def solveCubic(a, b, c, d):
  702. """Solve a cubic equation.
  703. Solves *a*x*x*x + b*x*x + c*x + d = 0* where a, b, c and d are real.
  704. Args:
  705. a: coefficient of *x³*
  706. b: coefficient of *x²*
  707. c: coefficient of *x*
  708. d: constant term
  709. Returns:
  710. A list of roots. Note that the returned list is neither guaranteed to
  711. be sorted nor to contain unique values!
  712. Examples::
  713. >>> solveCubic(1, 1, -6, 0)
  714. [-3.0, -0.0, 2.0]
  715. >>> solveCubic(-10.0, -9.0, 48.0, -29.0)
  716. [-2.9, 1.0, 1.0]
  717. >>> solveCubic(-9.875, -9.0, 47.625, -28.75)
  718. [-2.911392, 1.0, 1.0]
  719. >>> solveCubic(1.0, -4.5, 6.75, -3.375)
  720. [1.5, 1.5, 1.5]
  721. >>> solveCubic(-12.0, 18.0, -9.0, 1.50023651123)
  722. [0.5, 0.5, 0.5]
  723. >>> solveCubic(
  724. ... 9.0, 0.0, 0.0, -7.62939453125e-05
  725. ... ) == [-0.0, -0.0, -0.0]
  726. True
  727. """
  728. #
  729. # adapted from:
  730. # CUBIC.C - Solve a cubic polynomial
  731. # public domain by Ross Cottrell
  732. # found at: http://www.strangecreations.com/library/snippets/Cubic.C
  733. #
  734. if abs(a) < epsilon:
  735. # don't just test for zero; for very small values of 'a' solveCubic()
  736. # returns unreliable results, so we fall back to quad.
  737. return solveQuadratic(b, c, d)
  738. a = float(a)
  739. a1 = b / a
  740. a2 = c / a
  741. a3 = d / a
  742. Q = (a1 * a1 - 3.0 * a2) / 9.0
  743. R = (2.0 * a1 * a1 * a1 - 9.0 * a1 * a2 + 27.0 * a3) / 54.0
  744. R2 = R * R
  745. Q3 = Q * Q * Q
  746. R2 = 0 if R2 < epsilon else R2
  747. Q3 = 0 if abs(Q3) < epsilon else Q3
  748. R2_Q3 = R2 - Q3
  749. if R2 == 0.0 and Q3 == 0.0:
  750. x = round(-a1 / 3.0, epsilonDigits)
  751. return [x, x, x]
  752. elif R2_Q3 <= epsilon * 0.5:
  753. # The epsilon * .5 above ensures that Q3 is not zero.
  754. theta = acos(max(min(R / sqrt(Q3), 1.0), -1.0))
  755. rQ2 = -2.0 * sqrt(Q)
  756. a1_3 = a1 / 3.0
  757. x0 = rQ2 * cos(theta / 3.0) - a1_3
  758. x1 = rQ2 * cos((theta + 2.0 * pi) / 3.0) - a1_3
  759. x2 = rQ2 * cos((theta + 4.0 * pi) / 3.0) - a1_3
  760. x0, x1, x2 = sorted([x0, x1, x2])
  761. # Merge roots that are close-enough
  762. if x1 - x0 < epsilon and x2 - x1 < epsilon:
  763. x0 = x1 = x2 = round((x0 + x1 + x2) / 3.0, epsilonDigits)
  764. elif x1 - x0 < epsilon:
  765. x0 = x1 = round((x0 + x1) / 2.0, epsilonDigits)
  766. x2 = round(x2, epsilonDigits)
  767. elif x2 - x1 < epsilon:
  768. x0 = round(x0, epsilonDigits)
  769. x1 = x2 = round((x1 + x2) / 2.0, epsilonDigits)
  770. else:
  771. x0 = round(x0, epsilonDigits)
  772. x1 = round(x1, epsilonDigits)
  773. x2 = round(x2, epsilonDigits)
  774. return [x0, x1, x2]
  775. else:
  776. x = pow(sqrt(R2_Q3) + abs(R), 1 / 3.0)
  777. x = x + Q / x
  778. if R >= 0.0:
  779. x = -x
  780. x = round(x - a1 / 3.0, epsilonDigits)
  781. return [x]
  782. #
  783. # Conversion routines for points to parameters and vice versa
  784. #
  785. def calcQuadraticParameters(pt1, pt2, pt3):
  786. x2, y2 = pt2
  787. x3, y3 = pt3
  788. cx, cy = pt1
  789. bx = (x2 - cx) * 2.0
  790. by = (y2 - cy) * 2.0
  791. ax = x3 - cx - bx
  792. ay = y3 - cy - by
  793. return (ax, ay), (bx, by), (cx, cy)
  794. def calcCubicParameters(pt1, pt2, pt3, pt4):
  795. x2, y2 = pt2
  796. x3, y3 = pt3
  797. x4, y4 = pt4
  798. dx, dy = pt1
  799. cx = (x2 - dx) * 3.0
  800. cy = (y2 - dy) * 3.0
  801. bx = (x3 - x2) * 3.0 - cx
  802. by = (y3 - y2) * 3.0 - cy
  803. ax = x4 - dx - cx - bx
  804. ay = y4 - dy - cy - by
  805. return (ax, ay), (bx, by), (cx, cy), (dx, dy)
  806. @cython.cfunc
  807. @cython.inline
  808. @cython.locals(
  809. pt1=cython.complex,
  810. pt2=cython.complex,
  811. pt3=cython.complex,
  812. pt4=cython.complex,
  813. a=cython.complex,
  814. b=cython.complex,
  815. c=cython.complex,
  816. )
  817. def calcCubicParametersC(pt1, pt2, pt3, pt4):
  818. c = (pt2 - pt1) * 3.0
  819. b = (pt3 - pt2) * 3.0 - c
  820. a = pt4 - pt1 - c - b
  821. return (a, b, c, pt1)
  822. def calcQuadraticPoints(a, b, c):
  823. ax, ay = a
  824. bx, by = b
  825. cx, cy = c
  826. x1 = cx
  827. y1 = cy
  828. x2 = (bx * 0.5) + cx
  829. y2 = (by * 0.5) + cy
  830. x3 = ax + bx + cx
  831. y3 = ay + by + cy
  832. return (x1, y1), (x2, y2), (x3, y3)
  833. def calcCubicPoints(a, b, c, d):
  834. ax, ay = a
  835. bx, by = b
  836. cx, cy = c
  837. dx, dy = d
  838. x1 = dx
  839. y1 = dy
  840. x2 = (cx / 3.0) + dx
  841. y2 = (cy / 3.0) + dy
  842. x3 = (bx + cx) / 3.0 + x2
  843. y3 = (by + cy) / 3.0 + y2
  844. x4 = ax + dx + cx + bx
  845. y4 = ay + dy + cy + by
  846. return (x1, y1), (x2, y2), (x3, y3), (x4, y4)
  847. @cython.cfunc
  848. @cython.inline
  849. @cython.locals(
  850. a=cython.complex,
  851. b=cython.complex,
  852. c=cython.complex,
  853. d=cython.complex,
  854. p2=cython.complex,
  855. p3=cython.complex,
  856. p4=cython.complex,
  857. )
  858. def calcCubicPointsC(a, b, c, d):
  859. p2 = c * (1 / 3) + d
  860. p3 = (b + c) * (1 / 3) + p2
  861. p4 = a + b + c + d
  862. return (d, p2, p3, p4)
  863. #
  864. # Point at time
  865. #
  866. def linePointAtT(pt1, pt2, t):
  867. """Finds the point at time `t` on a line.
  868. Args:
  869. pt1, pt2: Coordinates of the line as 2D tuples.
  870. t: The time along the line.
  871. Returns:
  872. A 2D tuple with the coordinates of the point.
  873. """
  874. return ((pt1[0] * (1 - t) + pt2[0] * t), (pt1[1] * (1 - t) + pt2[1] * t))
  875. def quadraticPointAtT(pt1, pt2, pt3, t):
  876. """Finds the point at time `t` on a quadratic curve.
  877. Args:
  878. pt1, pt2, pt3: Coordinates of the curve as 2D tuples.
  879. t: The time along the curve.
  880. Returns:
  881. A 2D tuple with the coordinates of the point.
  882. """
  883. x = (1 - t) * (1 - t) * pt1[0] + 2 * (1 - t) * t * pt2[0] + t * t * pt3[0]
  884. y = (1 - t) * (1 - t) * pt1[1] + 2 * (1 - t) * t * pt2[1] + t * t * pt3[1]
  885. return (x, y)
  886. def cubicPointAtT(pt1, pt2, pt3, pt4, t):
  887. """Finds the point at time `t` on a cubic curve.
  888. Args:
  889. pt1, pt2, pt3, pt4: Coordinates of the curve as 2D tuples.
  890. t: The time along the curve.
  891. Returns:
  892. A 2D tuple with the coordinates of the point.
  893. """
  894. t2 = t * t
  895. _1_t = 1 - t
  896. _1_t_2 = _1_t * _1_t
  897. x = (
  898. _1_t_2 * _1_t * pt1[0]
  899. + 3 * (_1_t_2 * t * pt2[0] + _1_t * t2 * pt3[0])
  900. + t2 * t * pt4[0]
  901. )
  902. y = (
  903. _1_t_2 * _1_t * pt1[1]
  904. + 3 * (_1_t_2 * t * pt2[1] + _1_t * t2 * pt3[1])
  905. + t2 * t * pt4[1]
  906. )
  907. return (x, y)
  908. @cython.returns(cython.complex)
  909. @cython.locals(
  910. t=cython.double,
  911. pt1=cython.complex,
  912. pt2=cython.complex,
  913. pt3=cython.complex,
  914. pt4=cython.complex,
  915. )
  916. @cython.locals(t2=cython.double, _1_t=cython.double, _1_t_2=cython.double)
  917. def cubicPointAtTC(pt1, pt2, pt3, pt4, t):
  918. """Finds the point at time `t` on a cubic curve.
  919. Args:
  920. pt1, pt2, pt3, pt4: Coordinates of the curve as complex numbers.
  921. t: The time along the curve.
  922. Returns:
  923. A complex number with the coordinates of the point.
  924. """
  925. t2 = t * t
  926. _1_t = 1 - t
  927. _1_t_2 = _1_t * _1_t
  928. return _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4
  929. def segmentPointAtT(seg, t):
  930. if len(seg) == 2:
  931. return linePointAtT(*seg, t)
  932. elif len(seg) == 3:
  933. return quadraticPointAtT(*seg, t)
  934. elif len(seg) == 4:
  935. return cubicPointAtT(*seg, t)
  936. raise ValueError("Unknown curve degree")
  937. #
  938. # Intersection finders
  939. #
  940. def _line_t_of_pt(s, e, pt):
  941. sx, sy = s
  942. ex, ey = e
  943. px, py = pt
  944. if abs(sx - ex) < epsilon and abs(sy - ey) < epsilon:
  945. # Line is a point!
  946. return -1
  947. # Use the largest
  948. if abs(sx - ex) > abs(sy - ey):
  949. return (px - sx) / (ex - sx)
  950. else:
  951. return (py - sy) / (ey - sy)
  952. def _both_points_are_on_same_side_of_origin(a, b, origin):
  953. xDiff = (a[0] - origin[0]) * (b[0] - origin[0])
  954. yDiff = (a[1] - origin[1]) * (b[1] - origin[1])
  955. return not (xDiff <= 0.0 and yDiff <= 0.0)
  956. def lineLineIntersections(s1, e1, s2, e2):
  957. """Finds intersections between two line segments.
  958. Args:
  959. s1, e1: Coordinates of the first line as 2D tuples.
  960. s2, e2: Coordinates of the second line as 2D tuples.
  961. Returns:
  962. A list of ``Intersection`` objects, each object having ``pt``, ``t1``
  963. and ``t2`` attributes containing the intersection point, time on first
  964. segment and time on second segment respectively.
  965. Examples::
  966. >>> a = lineLineIntersections( (310,389), (453, 222), (289, 251), (447, 367))
  967. >>> len(a)
  968. 1
  969. >>> intersection = a[0]
  970. >>> intersection.pt
  971. (374.44882952482897, 313.73458370177315)
  972. >>> (intersection.t1, intersection.t2)
  973. (0.45069111555824465, 0.5408153767394238)
  974. """
  975. s1x, s1y = s1
  976. e1x, e1y = e1
  977. s2x, s2y = s2
  978. e2x, e2y = e2
  979. if (
  980. math.isclose(s2x, e2x) and math.isclose(s1x, e1x) and not math.isclose(s1x, s2x)
  981. ): # Parallel vertical
  982. return []
  983. if (
  984. math.isclose(s2y, e2y) and math.isclose(s1y, e1y) and not math.isclose(s1y, s2y)
  985. ): # Parallel horizontal
  986. return []
  987. if math.isclose(s2x, e2x) and math.isclose(s2y, e2y): # Line segment is tiny
  988. return []
  989. if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny
  990. return []
  991. if math.isclose(e1x, s1x):
  992. x = s1x
  993. slope34 = (e2y - s2y) / (e2x - s2x)
  994. y = slope34 * (x - s2x) + s2y
  995. pt = (x, y)
  996. return [
  997. Intersection(
  998. pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
  999. )
  1000. ]
  1001. if math.isclose(s2x, e2x):
  1002. x = s2x
  1003. slope12 = (e1y - s1y) / (e1x - s1x)
  1004. y = slope12 * (x - s1x) + s1y
  1005. pt = (x, y)
  1006. return [
  1007. Intersection(
  1008. pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
  1009. )
  1010. ]
  1011. slope12 = (e1y - s1y) / (e1x - s1x)
  1012. slope34 = (e2y - s2y) / (e2x - s2x)
  1013. if math.isclose(slope12, slope34):
  1014. return []
  1015. x = (slope12 * s1x - s1y - slope34 * s2x + s2y) / (slope12 - slope34)
  1016. y = slope12 * (x - s1x) + s1y
  1017. pt = (x, y)
  1018. if _both_points_are_on_same_side_of_origin(
  1019. pt, e1, s1
  1020. ) and _both_points_are_on_same_side_of_origin(pt, s2, e2):
  1021. return [
  1022. Intersection(
  1023. pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
  1024. )
  1025. ]
  1026. return []
  1027. def _alignment_transformation(segment):
  1028. # Returns a transformation which aligns a segment horizontally at the
  1029. # origin. Apply this transformation to curves and root-find to find
  1030. # intersections with the segment.
  1031. start = segment[0]
  1032. end = segment[-1]
  1033. angle = math.atan2(end[1] - start[1], end[0] - start[0])
  1034. return Identity.rotate(-angle).translate(-start[0], -start[1])
  1035. def _curve_line_intersections_t(curve, line):
  1036. aligned_curve = _alignment_transformation(line).transformPoints(curve)
  1037. if len(curve) == 3:
  1038. a, b, c = calcQuadraticParameters(*aligned_curve)
  1039. intersections = solveQuadratic(a[1], b[1], c[1])
  1040. elif len(curve) == 4:
  1041. a, b, c, d = calcCubicParameters(*aligned_curve)
  1042. intersections = solveCubic(a[1], b[1], c[1], d[1])
  1043. else:
  1044. raise ValueError("Unknown curve degree")
  1045. return sorted(i for i in intersections if 0.0 <= i <= 1)
  1046. def curveLineIntersections(curve, line):
  1047. """Finds intersections between a curve and a line.
  1048. Args:
  1049. curve: List of coordinates of the curve segment as 2D tuples.
  1050. line: List of coordinates of the line segment as 2D tuples.
  1051. Returns:
  1052. A list of ``Intersection`` objects, each object having ``pt``, ``t1``
  1053. and ``t2`` attributes containing the intersection point, time on first
  1054. segment and time on second segment respectively.
  1055. Examples::
  1056. >>> curve = [ (100, 240), (30, 60), (210, 230), (160, 30) ]
  1057. >>> line = [ (25, 260), (230, 20) ]
  1058. >>> intersections = curveLineIntersections(curve, line)
  1059. >>> len(intersections)
  1060. 3
  1061. >>> intersections[0].pt
  1062. (84.9000930760723, 189.87306176459828)
  1063. """
  1064. if len(curve) == 3:
  1065. pointFinder = quadraticPointAtT
  1066. elif len(curve) == 4:
  1067. pointFinder = cubicPointAtT
  1068. else:
  1069. raise ValueError("Unknown curve degree")
  1070. intersections = []
  1071. for t in _curve_line_intersections_t(curve, line):
  1072. pt = pointFinder(*curve, t)
  1073. # Back-project the point onto the line, to avoid problems with
  1074. # numerical accuracy in the case of vertical and horizontal lines
  1075. line_t = _line_t_of_pt(*line, pt)
  1076. pt = linePointAtT(*line, line_t)
  1077. intersections.append(Intersection(pt=pt, t1=t, t2=line_t))
  1078. return intersections
  1079. def _curve_bounds(c):
  1080. if len(c) == 3:
  1081. return calcQuadraticBounds(*c)
  1082. elif len(c) == 4:
  1083. return calcCubicBounds(*c)
  1084. raise ValueError("Unknown curve degree")
  1085. def _split_segment_at_t(c, t):
  1086. if len(c) == 2:
  1087. s, e = c
  1088. midpoint = linePointAtT(s, e, t)
  1089. return [(s, midpoint), (midpoint, e)]
  1090. if len(c) == 3:
  1091. return splitQuadraticAtT(*c, t)
  1092. elif len(c) == 4:
  1093. return splitCubicAtT(*c, t)
  1094. raise ValueError("Unknown curve degree")
  1095. def _curve_curve_intersections_t(
  1096. curve1, curve2, precision=1e-3, range1=None, range2=None
  1097. ):
  1098. bounds1 = _curve_bounds(curve1)
  1099. bounds2 = _curve_bounds(curve2)
  1100. if not range1:
  1101. range1 = (0.0, 1.0)
  1102. if not range2:
  1103. range2 = (0.0, 1.0)
  1104. # If bounds don't intersect, go home
  1105. intersects, _ = sectRect(bounds1, bounds2)
  1106. if not intersects:
  1107. return []
  1108. def midpoint(r):
  1109. return 0.5 * (r[0] + r[1])
  1110. # If they do overlap but they're tiny, approximate
  1111. if rectArea(bounds1) < precision and rectArea(bounds2) < precision:
  1112. return [(midpoint(range1), midpoint(range2))]
  1113. c11, c12 = _split_segment_at_t(curve1, 0.5)
  1114. c11_range = (range1[0], midpoint(range1))
  1115. c12_range = (midpoint(range1), range1[1])
  1116. c21, c22 = _split_segment_at_t(curve2, 0.5)
  1117. c21_range = (range2[0], midpoint(range2))
  1118. c22_range = (midpoint(range2), range2[1])
  1119. found = []
  1120. found.extend(
  1121. _curve_curve_intersections_t(
  1122. c11, c21, precision, range1=c11_range, range2=c21_range
  1123. )
  1124. )
  1125. found.extend(
  1126. _curve_curve_intersections_t(
  1127. c12, c21, precision, range1=c12_range, range2=c21_range
  1128. )
  1129. )
  1130. found.extend(
  1131. _curve_curve_intersections_t(
  1132. c11, c22, precision, range1=c11_range, range2=c22_range
  1133. )
  1134. )
  1135. found.extend(
  1136. _curve_curve_intersections_t(
  1137. c12, c22, precision, range1=c12_range, range2=c22_range
  1138. )
  1139. )
  1140. unique_key = lambda ts: (int(ts[0] / precision), int(ts[1] / precision))
  1141. seen = set()
  1142. unique_values = []
  1143. for ts in found:
  1144. key = unique_key(ts)
  1145. if key in seen:
  1146. continue
  1147. seen.add(key)
  1148. unique_values.append(ts)
  1149. return unique_values
  1150. def curveCurveIntersections(curve1, curve2):
  1151. """Finds intersections between a curve and a curve.
  1152. Args:
  1153. curve1: List of coordinates of the first curve segment as 2D tuples.
  1154. curve2: List of coordinates of the second curve segment as 2D tuples.
  1155. Returns:
  1156. A list of ``Intersection`` objects, each object having ``pt``, ``t1``
  1157. and ``t2`` attributes containing the intersection point, time on first
  1158. segment and time on second segment respectively.
  1159. Examples::
  1160. >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ]
  1161. >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ]
  1162. >>> intersections = curveCurveIntersections(curve1, curve2)
  1163. >>> len(intersections)
  1164. 3
  1165. >>> intersections[0].pt
  1166. (81.7831487395506, 109.88904552375288)
  1167. """
  1168. intersection_ts = _curve_curve_intersections_t(curve1, curve2)
  1169. return [
  1170. Intersection(pt=segmentPointAtT(curve1, ts[0]), t1=ts[0], t2=ts[1])
  1171. for ts in intersection_ts
  1172. ]
  1173. def segmentSegmentIntersections(seg1, seg2):
  1174. """Finds intersections between two segments.
  1175. Args:
  1176. seg1: List of coordinates of the first segment as 2D tuples.
  1177. seg2: List of coordinates of the second segment as 2D tuples.
  1178. Returns:
  1179. A list of ``Intersection`` objects, each object having ``pt``, ``t1``
  1180. and ``t2`` attributes containing the intersection point, time on first
  1181. segment and time on second segment respectively.
  1182. Examples::
  1183. >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ]
  1184. >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ]
  1185. >>> intersections = segmentSegmentIntersections(curve1, curve2)
  1186. >>> len(intersections)
  1187. 3
  1188. >>> intersections[0].pt
  1189. (81.7831487395506, 109.88904552375288)
  1190. >>> curve3 = [ (100, 240), (30, 60), (210, 230), (160, 30) ]
  1191. >>> line = [ (25, 260), (230, 20) ]
  1192. >>> intersections = segmentSegmentIntersections(curve3, line)
  1193. >>> len(intersections)
  1194. 3
  1195. >>> intersections[0].pt
  1196. (84.9000930760723, 189.87306176459828)
  1197. """
  1198. # Arrange by degree
  1199. swapped = False
  1200. if len(seg2) > len(seg1):
  1201. seg2, seg1 = seg1, seg2
  1202. swapped = True
  1203. if len(seg1) > 2:
  1204. if len(seg2) > 2:
  1205. intersections = curveCurveIntersections(seg1, seg2)
  1206. else:
  1207. intersections = curveLineIntersections(seg1, seg2)
  1208. elif len(seg1) == 2 and len(seg2) == 2:
  1209. intersections = lineLineIntersections(*seg1, *seg2)
  1210. else:
  1211. raise ValueError("Couldn't work out which intersection function to use")
  1212. if not swapped:
  1213. return intersections
  1214. return [Intersection(pt=i.pt, t1=i.t2, t2=i.t1) for i in intersections]
  1215. def _segmentrepr(obj):
  1216. """
  1217. >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], [0.1, 2.2]]]])
  1218. '(1, (2, 3), (), ((2, (3, 4), (0.1, 2.2))))'
  1219. """
  1220. try:
  1221. it = iter(obj)
  1222. except TypeError:
  1223. return "%g" % obj
  1224. else:
  1225. return "(%s)" % ", ".join(_segmentrepr(x) for x in it)
  1226. def printSegments(segments):
  1227. """Helper for the doctests, displaying each segment in a list of
  1228. segments on a single line as a tuple.
  1229. """
  1230. for segment in segments:
  1231. print(_segmentrepr(segment))
  1232. if __name__ == "__main__":
  1233. import sys
  1234. import doctest
  1235. sys.exit(doctest.testmod().failed)