$$include '../../meta/macros.ptl'

import [mix linreg clamp fallback SuffixCfg] from "@iosevka/util"
import [MathSansSerif] from "@iosevka/glyph/relation"

glyph-module

glyph-block Letter-Latin-Lower-R : begin
	glyph-block-import CommonShapes
	glyph-block-import Common-Derivatives
	glyph-block-import Mark-Adjustment : LeaningAnchor
	glyph-block-import Letter-Shared : CreateAccentedComposition
	glyph-block-import Letter-Shared-Shapes : PalatalHook RetroflexHook
	glyph-block-import Letter-Blackboard : BBS BBD BBBarRight

	local dfN : DivFrame 1
	local dfR : DivFrame para.advanceScaleF

	# Modes
	local rStraight             0
	local rSerifed              1
	local rNarrow               2
	local rNarrowSerifed        3
	local rEarless              4
	local rCornerHooked         5
	local rCornerHookedSerifed  6

	define [RDim df mode _strokeBar _stroke] : namespace
		local strokeBar : fallback _strokeBar Stroke
		local stroke : fallback _stroke Stroke
		local strokeA : mix strokeBar stroke 0.5
		local { rBalanceMultiplier rHookMultiplier rHookSwMultiplier rSerifLeftExtender hookSuperness } : match mode
			[Just rStraight]            {  1                     1        0        0       2.35 }
			[Just rSerifed]             { (4 / 3)               (2 / 3)  (1 / 4)  (1 / 3)  2.35 }
			[Just rNarrow]              { (2 * (df.adws - 0.5))   1        0        0       2.35 }
			[Just rNarrowSerifed]       { (2 * (df.adws - 0.5))   1        0        0       2.35 }
			[Just rCornerHooked]        { (5 / 8)                1        0        0       2.35 }
			[Just rCornerHookedSerifed] { (4 / 3)               (2 / 3)  (1 / 4)  (1 / 3)  2.35 }
			[Just rEarless]             {  1                     1        0        0       2.35 }

		export : local xBar : df.leftSB + RBalance * rBalanceMultiplier + [HSwToV strokeBar]
		local rSerifX : xBar - [HSwToV : 0.5 * strokeBar]
		local rSerifLeftJut  : SideJut + RBalance * (0.3 + rSerifLeftExtender)
		local rSerifRightJut : rSerifLeftJut * 1.20
		export : local [rBottomSerif y] : glyph-proc
			include : tagged 'serifLB' : union
				HSerif.lb  rSerifX y (rSerifLeftJut + [HSwToV : 0.5 * strokeBar])
				HSerif.rb rSerifX y (rSerifRightJut + [HSwToV : 0.5 * strokeBar])
			local xAtt : rSerifX + rSerifRightJut + [HSwToV : 0.5 * strokeBar]
			set-base-anchor 'palatalHookAttach' xAtt y
			set-base-anchor 'palatalHookPos'    xAtt y

		export : local [rTopSerif y] : tagged 'serifLT'
			HSerif.lt rSerifX y (rSerifLeftJut + [HSwToV : 0.5 * strokeBar])
		export : local fine ShoulderFine
		export : local rHookX : df.rightSB + RBalance2 * rBalanceMultiplier - (OX - O)
		export : local xArchMiddle : match mode
			[Just rStraight]                                      : mix (xBar - fine) rHookX (0.54 + 2 * TanSlope * strokeBar / Width)
			[Just rSerifed]                                       : mix (xBar - fine) rHookX (0.59 + 2 * TanSlope * strokeBar / Width)
			([Just rNarrow] || [Just rNarrowSerifed])             : mix df.width rHookX : Math.max 1.01 (5 / 4 * [mix 1 dfR.adws 2])
			([Just rCornerHooked] || [Just rCornerHookedSerifed]) : rHookX - [HSwToV : 0.5 * strokeBar]
			[Just rEarless]                                       : mix (xBar - [HSwToV strokeBar]) rHookX 0.5
		local mixpin : match mode
			([Just rSerifed] || [Just rCornerHooked] || [Just rCornerHookedSerifed]) : begin
				0.65 + 0.25 * strokeA / Width + 4 * TanSlope * strokeA / Width
			__ : 0.65 + 4 * TanSlope * strokeA / Width
		local rmiddlein : [mix xBar (rHookX - [HSwToV : 1.05 * strokeA]) mixpin] - CorrectionOMidS
		export : local skew : Math.max 0 : (xArchMiddle - rmiddlein) / stroke - TanSlope
		export : local rHookY : RHook * rHookMultiplier + stroke * rHookSwMultiplier
		export : local rHookXN : match mode
			[Just rNarrowSerifed] : mix df.width rHookX df.adws
			[Just rNarrow]        : xArchMiddle + TINY
			__                      rHookX

		export : define [setMarks doTopSerif top bottom] : glyph-proc
			include : LeaningAnchor.Below.VBar.r xBar
			include : LeaningAnchor.Above.Hook
				mix df.leftSB (xBar - [HSwToV Stroke]) : if doTopSerif 0.5 1
				begin df.rightSB
			set-base-anchor 'overlay' (xBar - QuarterStroke) [mix bottom top 0.5]
			set-base-anchor 'palatalHookAttach' xBar bottom
			set-base-anchor 'palatalHookPos' (xBar + [PalatalHook.adviceGap Stroke]) bottom
			currentGlyph.copyBaseAnchorIfAbsent 'leaningAbove' 'above'
			currentGlyph.copyBaseAnchorIfAbsent 'leaningBelow' 'below'

		export : define [setTurnedMarks doTopSerif top bottom] : glyph-proc
			include : LeaningAnchor.Above.VBar.l (df.width - xBar)
			include : LeaningAnchor.Below.Hook
				begin df.leftSB
				df.width - [mix df.leftSB (xBar - [HSwToV Stroke]) : if doTopSerif 0.5 1]
			set-base-anchor 'overlay' (df.width - (xBar - QuarterStroke)) [mix bottom top 0.5]
			currentGlyph.copyBaseAnchorIfAbsent 'leaningAbove' 'above'
			currentGlyph.copyBaseAnchorIfAbsent 'leaningBelow' 'below'

		export hookSuperness

	define [StandardShape df md doTopSerif doBottomSerif] : glyph-proc
		define [object xBar rBottomSerif rTopSerif fine xArchMiddle skew rHookX rHookY hookSuperness] : RDim df md
		include : dispiro
			widths.lhs
			g4.up.start rHookX (XH - rHookY - HalfStroke) [heading Upward]
			arcvh 32 hookSuperness
			g4.left.mid (xArchMiddle - CorrectionOMidS * [linreg 72 0.75 108 1 Stroke]) (XH - O) [widths.heading Stroke 0 {.y (-1) .x (-skew)}]
			archv 32
			straight.down.end (xBar - [HSwToV fine]) (XH * 0.53 + (SmallArchDepth - SmallArchDepthA)) [widths.heading fine 0 Downward]
		include : VBar.r xBar 0 XH
		if doBottomSerif : include : rBottomSerif 0
		if doTopSerif : include : rTopSerif XH

	define [CompactShape    df md ts bs] : CompactShapeImpl df md false ts bs
	define [CornerHookShape df md ts bs] : CompactShapeImpl df md true  ts bs
	define [CompactShapeImpl df md doHookSerif doTopSerif doBottomSerif] : glyph-proc
		define [object xBar rBottomSerif rTopSerif fine xArchMiddle rHookXN] : RDim df md
		define xCor : if doHookSerif 0 : CorrectionOMidS * [linreg 72 0.75 108 1 Stroke]

		define arcTopShift : match md
			[Just rNarrow] : O * [clamp 0 1 : StrokeWidthBlend 0 16]
			__               0
		define arcTopWidth : match md
			[Just rNarrow] : Stroke - O * [clamp 0 1 : StrokeWidthBlend 0 16]
			__               Stroke

		define [ArcKnots] : list
			flat (rHookXN - xCor) (XH - arcTopShift) [if doHookSerif [heading Leftward] null]
			curl (xArchMiddle - xCor) (XH - arcTopShift) [if doHookSerif [heading Leftward] null]
			archv
			straight.down.end (xBar - [HSwToV fine]) (XH * 0.53 + (SmallArchDepth - SmallArchDepthA)) [widths.heading fine 0 Downward]
		include : dispiro [widths.lhs arcTopWidth] [ArcKnots]
		include : VBar.r xBar 0 XH
		if doHookSerif : include : intersection
			VSerif.dr (rHookXN - xCor) XH VJut
			spiro-outline
				ArcKnots
				corner (xBar - [HSwToV fine]) 0
				corner (Width * 16) 0
				corner (Width * 16) XH
		if doBottomSerif : include : rBottomSerif 0
		if doTopSerif : include : rTopSerif XH

	define [EarlessCornerShape df md doTopSerif doBottomSerif] : glyph-proc
		define [object xBar xArchMiddle rHookX rHookY hookSuperness rBottomSerif] : RDim df md
		include : dispiro
			widths.lhs
			g4.up.start rHookX (XH - rHookY - HalfStroke) [heading Upward]
			arcvh nothing hookSuperness
			g4.left.mid (xArchMiddle - CorrectionOMidS) (XH - O) [heading Leftward]
			g4 (xBar - [HSwToV Stroke]) (XH - DToothlessRise)
		include : VBar.r xBar 0 (XH - DToothlessRise)
		if doBottomSerif : include : rBottomSerif 0

	define [EarlessRoundedShape df md doTopSerif doBottomSerif] : glyph-proc
		define [object xBar xArchMiddle rHookX rHookY hookSuperness rBottomSerif] : RDim df md
		local hx : Math.max rHookX (xBar + 1.25 * Stroke)
		include : dispiro
			widths.lhs
			g4   hx (XH - rHookY)
			hookstart XH
			flat (xBar - [HSwToV Stroke]) (XH - SmallArchDepthA)
			curl (xBar - [HSwToV Stroke]) 0 [heading Downward]
		if doBottomSerif : include : rBottomSerif 0

	define [FlapHooklessShape df md doTopSerif doBottomSerif] : glyph-proc
		define [object xBar rBottomSerif xArchMiddle] : RDim df md
		set-base-anchor 'overlay' (xBar - [HSwToV HalfStroke]) (XH / 2)
		include : dispiro
			widths.lhs
			g4.left.start (xArchMiddle - CorrectionOMidS * [linreg 72 0.75 108 1 Stroke]) (XH - O)
			archv
			flat (xBar - [HSwToV Stroke]) (XH - SmallArchDepthA)
			curl (xBar - [HSwToV Stroke]) 0 [heading Downward]
		if doBottomSerif : include : rBottomSerif 0

	define SmallRConfig : SuffixCfg.weave
		# Body
		object
			''             { StandardShape       dfN rStraight     rSerifed             }
			earlessCorner  { EarlessCornerShape  dfN rEarless      rEarless             }
			earlessRounded { EarlessRoundedShape dfN rEarless      rEarless             }
			hookless       { CompactShape        dfN rNarrow       rNarrowSerifed       }
			cornerHooked   { CornerHookShape     dfN rCornerHooked rCornerHookedSerifed }
			compact        { CompactShape        dfR rNarrow       rNarrowSerifed       }
			hooklessFlap   { FlapHooklessShape   dfN rNarrow       rNarrowSerifed       }
			compactFlap    { FlapHooklessShape   dfR rNarrow       rNarrowSerifed       }

		# Serifs
		object
			serifless      { 0 0 }
			topSerifed     { 1 0 }
			baseSerifed    { 0 1 }
			serifed        { 1 1 }

	foreach { suffix { {F df modeSans modeSerifed} {doTS doBS} } } [pairs-of SmallRConfig] : do
		local mode : if (doTS || doBS) modeSerifed modeSans
		create-glyph "r.\(suffix)" : glyph-proc
			set-width df.width
			include : df.markSet.e

			define [object setMarks] : RDim df mode
			include : setMarks doTS XH 0

			include : F df mode doTS doBS

		create-glyph "rLongLeg.\(suffix)" : glyph-proc
			set-width df.width
			include : df.markSet.p

			define [object xBar rBottomSerif setMarks] : RDim df mode
			include : setMarks doTS XH Descender

			include : F df mode doTS 0
			eject-contour 'serifLB'
			include : VBar.r xBar Descender 0
			if doBS : include : rBottomSerif Descender

		create-glyph "rCapLongLeg.\(suffix)" : glyph-proc
			set-width df.width
			include : df.markSet.capDesc

			define [object xBar rBottomSerif setMarks] : RDim df mode
			include : setMarks doTS CAP Descender

			include : with-transform [ApparentTranslate 0 (CAP - XH)] : F df mode doTS 0
			eject-contour 'serifLB'
			include : VBar.r xBar Descender (CAP - XH)
			if doBS : include : rBottomSerif Descender

		create-glyph "fInsular.\(suffix)" : glyph-proc
			include [refer-glyph "rLongLeg.\(suffix)"] AS_BASE ALSO_METRICS
			define [object xBar rHookX] : RDim df mode
			include : HBar.b xBar (rHookX - [Math.max (0.15 * (df.rightSB - df.leftSB)) [HSwToV QuarterStroke]]) 0

		create-glyph "FInsular.\(suffix)" : glyph-proc
			include [refer-glyph "rCapLongLeg.\(suffix)"] AS_BASE ALSO_METRICS
			define [object xBar rHookX] : RDim df mode
			include : HBar.b xBar (rHookX - [Math.max (0.15 * (df.rightSB - df.leftSB)) [HSwToV QuarterStroke]]) 0

		create-glyph "rPalatalHook.\(suffix)" : glyph-proc
			include [refer-glyph "r.\(suffix)"] AS_BASE ALSO_METRICS
			local attach : currentGlyph.gizmo.unapply currentGlyph.baseAnchors.palatalHookAttach
			local pos : currentGlyph.gizmo.unapply currentGlyph.baseAnchors.palatalHookPos
			include : PalatalHook.r (x -- pos.x) (y -- pos.y) (xLink -- attach.x)

		create-glyph "rRTail.\(suffix)" : glyph-proc
			set-width df.width
			include : df.markSet.e
			include : F df mode doTS 0
			eject-contour 'serifLB'

			define [object xBar] : RDim df mode
			include : RetroflexHook.rExt xBar 0

		create-glyph "turnr.\(suffix)" : glyph-proc
			include [refer-glyph "r.\(suffix)"] AS_BASE ALSO_METRICS
			include : FlipAround df.middle (XH / 2)
			include : df.markSet.e
			define [object setTurnedMarks] : RDim df mode
			include : setTurnedMarks doTS XH 0

		create-glyph "rTurnRTail.\(suffix)" : glyph-proc
			include [refer-glyph "r.\(suffix)"] AS_BASE ALSO_METRICS
			eject-contour 'serifLT'
			include : FlipAround df.middle (XH / 2)
			include : df.markSet.e
			define [object xBar setTurnedMarks] : RDim df mode
			include : setTurnedMarks doTS XH 0
			include : RetroflexHook.lExt (df.rightSB - xBar + df.leftSB) 0

		create-glyph "rTurnPalatalHook.\(suffix)" : glyph-proc
			include [refer-glyph "r.\(suffix)"] AS_BASE ALSO_METRICS
			eject-contour 'serifLT'
			include : FlipAround df.middle (XH / 2)
			include : df.markSet.e
			define [object xBar setTurnedMarks] : RDim df mode
			include : setTurnedMarks doTS XH 0
			include : PalatalHook.r
				xLink -- (df.rightSB - xBar + df.leftSB)
				x -- (df.rightSB - xBar + df.leftSB + [HSwToV Stroke] + SideJut)
				y -- 0

		create-glyph "turnrLongLeg.\(suffix)" : glyph-proc
			include [refer-glyph "rLongLeg.\(suffix)"] AS_BASE ALSO_METRICS
			include : FlipAround df.middle (XH / 2)
			include : df.markSet.b
			define [object setTurnedMarks] : RDim df mode
			include : setTurnedMarks doTS Ascender 0

		create-glyph "rTurnLongLegRTail.\(suffix)" : glyph-proc
			include [refer-glyph "rLongLeg.\(suffix)"] AS_BASE ALSO_METRICS
			eject-contour 'serifLT'
			include : FlipAround df.middle (XH / 2)
			include : df.markSet.b
			define [object xBar setTurnedMarks] : RDim df mode
			include : setTurnedMarks doTS Ascender 0
			include : RetroflexHook.lExt (df.rightSB - xBar + df.leftSB) 0

		create-glyph "smallLetterTurnedRWithTail.\(suffix)" : glyph-proc
			include [refer-glyph "rRTail.\(suffix)"] AS_BASE ALSO_METRICS
			include : FlipAround df.middle (XH / 2)
			include : df.markSet.b
			define [object setTurnedMarks] : RDim df mode
			include : setTurnedMarks doTS Ascender 0

	select-variant 'r' 'r'
	link-reduced-variant 'r/sansSerif' 'r' MathSansSerif
	select-variant 'turnr' 0x279 (follow -- 'r')

	CreateAccentedComposition 'rTildeOver' 0x1D72 'r' 'tildeOver'
	CreateAccentedComposition 'turnrTildeOver' 0xAB68 'turnr' 'tildeOver'

	select-variant 'rLongLeg' 0x27C (follow -- 'r')
	select-variant 'turnrLongLeg' 0x27A (follow -- 'r')
	select-variant 'SInsular' 0xA784 (shapeFrom -- 'rCapLongLeg') (follow -- 'rRTail')
	select-variant 'sInsular' 0xA785 (shapeFrom -- 'rLongLeg') (follow -- 'rRTail')
	select-variant 'FInsular' 0xA77B (follow -- 'rRTail')
	select-variant 'fInsular' 0xA77C (follow -- 'rRTail')

	select-variant 'rRTail' 0x27D
	select-variant 'smallLetterTurnedRWithTail' 0x2C79 (follow -- 'rRTail')

	select-variant 'rTurnRTail' 0x27B
	select-variant 'rTurnLongLegRTail' 0x1DF08 (follow -- 'rTurnRTail')
	select-variant 'rPalatalHook' 0x1D89 (follow -- 'r')

	select-variant 'rFlap' 0x27E (shapeFrom -- 'r')
	CreateAccentedComposition 'rFlapTildeOver' 0x1D73 'rFlap' 'tildeOver'

	select-variant 'rTurnPalatalHook' 0x1DF15 (follow -- 'rTurnRTail')
	select-variant 'rFlapPalatalHook' 0x1DF16 (shapeFrom -- 'rPalatalHook') (follow -- 'rFlap')

	define [BBRShape df md doTopSerif doBottomSerif] : glyph-proc
		define [object xBar fine xArchMiddle skew rHookX rHookY hookSuperness] : RDim df md BBD BBS
		include : dispiro
			widths.lhs BBS
			g4.up.start rHookX (XH - rHookY - BBS * 0.5) [heading Upward]
			arcvh nothing hookSuperness
			g4.left.mid (xArchMiddle - CorrectionOMidS * [linreg 72 0.75 108 1 BBS]) (XH - O) [widths.heading BBS 0 {.y (-1) .x (-skew)}]
			archv
			straight.down.end (xBar - [HSwToV fine]) (XH * 0.53 + (SmallArchDepth - SmallArchDepthA)) [widths.heading fine 0 Downward]
		include : BBBarRight xBar 0 XH
		set-base-anchor 'overlay' (xBar - [HSwToV : BBD + BBS * 2] * 0.25) (XH * 0.5)

	create-glyph 'mathbb/r' 0x1D563 : glyph-proc
		include : dfR.markSet.e
		include : BBRShape dfN rStraight 0 0
