bezierTools.py 44 KB

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