' QB64PE Triangle Fill Demo by b+
' as found at https://qb64phoenix.com/forum/showthread.php?tid=1897&pid=18586#pid18586

' This BASIC Anywhere Machine port by Charlie Veniot
' This program exported from BASIC Anywhere Machine (Version [5.2.3].[2023.08.08.01.01]) on 2023.08.13 at 01:36 (Coordinated Universal Time)

_Title "Filled Triangle Demo" 'b+ 2023-08-12
Screen _NewImage(800, 600, 12) ' use 16 colors for demo
declare Sub ftri (xx1, yy1, xx2, yy2, xx3, yy3, c)
' _ScreenMove 250, 60
Print "Here is one, press any for many...."
ftri (100, 100, 500, 10, 300, 480, 9)
Sleep
Do
    ftri (Rnd * _Width, Rnd * _Height, Rnd * _Width, Rnd * _Height, Rnd * _Width, Rnd * _Height, int(Rnd * 15)+1)
    _delay 0.25
Loop 

Sub ftri (xx1, yy1, xx2, yy2, xx3, yy3, c)
    'make copies before swapping because QB64 passes by ref and these get changed
    x1 = xx1: y1 = yy1: x2 = xx2: y2 = yy2: x3 = xx3: y3 = yy3
    'thanks Andy Amaya!
    'triangle coordinates must be ordered: where x1 < x2 < x3
    If x2 < x1 Then Swap x1, x2: Swap y1, y2
    If x3 < x1 Then Swap x1, x3: Swap y1, y3
    If x3 < x2 Then Swap x2, x3: Swap y2, y3
    If x1 <> x3 Then slope1 = (y3 - y1) / (x3 - x1)

    'draw the first half of the triangle
    length = x2 - x1
    If length <> 0 Then
        slope2 = (y2 - y1) / (x2 - x1)
        For x = 0 To length
            Line (Int(x + x1), Int(x * slope1 + y1))-(Int(x + x1), Int(x * slope2 + y1)), c
            'lastx2% = lastx%
            lastx% = Int(x + x1)
        Next
    End If

    'draw the second half of the triangle
    y = length * slope1 + y1: length = x3 - x2
    If length <> 0 Then
        slope3 = (y3 - y2) / (x3 - x2)
        For x = 0 To length
            'IF INT(x + x2) <> lastx% AND INT(x + x2) <> lastx2% THEN  'works! but need 2nd? check
            If Int(x + x2) <> lastx% Then
                Line (Int(x + x2), Int(x * slope1 + y))-(Int(x + x2), Int(x * slope3 + y2)), c
            End If
        Next
    End If
End Sub