Page 1 of 1

Find circle that goes through 3 points

Posted: Fri Aug 14, 2020 8:07 pm
by Seymour Clufley
A generic function that may come in useful for somebody one day:

Code: Select all

Structure PointD
  x.d
  y.d
EndStructure

Structure CircleD
  c.PointD
  r.d
EndStructure


Procedure.d DistanceBetweenTwoPoints(*a.PointD,*b.PointD)
    ProcedureReturn Sqr(Pow(*a\x - *b\x, 2) + Pow(*a\y - *b\y, 2))
EndProcedure


Procedure.b FindCircleThroughThreePoints_Centre(*b.PointD, *c.PointD,*I.PointD)
  B.d = *b\x * *b\x + *b\y * *b\y
  C.d = *c\x * *c\x + *c\y * *c\y
  D.d = *b\x * *c\y - *b\y * *c\x
  *I\x = (*c\y * B - *b\y * C) / (2 * D)
  *I\y = (*b\x * C - *c\x * B) / (2 * D)
EndProcedure

Procedure.b FindCircleThroughThreePoints(*A.PointD, *B.PointD, *C.PointD, *cir.CircleD)
  test1.PointD
  test1\x = *B\x - *A\x
  test1\y = *B\y - *A\y
  test2.PointD
  test2\x = *C\x - *A\x
  test2\y = *C\y - *A\y
  FindCircleThroughThreePoints_Centre(@test1, @test2, *cir\c)
  *cir\c\x + *A\x
  *cir\c\y + *A\y
  *cir\r = DistanceBetweenTwoPoints(*cir\c,*A)
EndProcedure
Demo code (press SPACE to cycle through and ESCAPE to quit):

Code: Select all

iw = 1600
ih = 900
img = CreateImage(#PB_Any,iw,ih)
win = OpenWindow(#PB_Any,0,0,iw,ih,"Circle through 3 points",#PB_Window_ScreenCentered)
imgad = ImageGadget(#PB_Any,0,0,iw,ih,ImageID(img))
space = 5
AddKeyboardShortcut(win,#PB_Shortcut_Space,space)
esc = 6
AddKeyboardShortcut(win,#PB_Shortcut_Escape,esc)


Repeat
  pnts = 3
  Dim pnt.PointD(pnts)
  For p = 1 To pnts
    pnt(p)\x = Random(iw*0.7,iw*0.3)
    pnt(p)\y = Random(ih*0.7,ih*0.3)
  Next p
  FindCircleThroughThreePoints(@pnt(1),@pnt(2),@pnt(3),@cir.CircleD)
  
  img = CreateImage(#PB_Any,iw,ih,24,#Black)
  StartDrawing(ImageOutput(img))
  Box(0,0,OutputWidth(),OutputHeight(),#Black)
  Circle(cir\c\x,cir\c\y,cir\r,#Blue)
  For p = 1 To pnts
    Circle(pnt(p)\x,pnt(p)\y,3,#Yellow)
  Next p
  StopDrawing()
  
  SetGadgetState(imgad,ImageID(img))
  Repeat : Until WaitWindowEvent(5)=#PB_Event_Menu
  If EventMenu()=esc : Break : EndIf
ForEver

Re: Find circle that goes through 3 points

Posted: Sat Aug 15, 2020 6:33 pm
by davido
@Seymour Clufley,
Interesting demonstration.
Thank you for sharing.