Find circle that goes through 3 points

Share your advanced PureBasic knowledge/code with the community.
Seymour Clufley
Addict
Addict
Posts: 1233
Joined: Wed Feb 28, 2007 9:13 am
Location: London

Find circle that goes through 3 points

Post 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
JACK WEBB: "Coding in C is like sculpting a statue using only sandpaper. You can do it, but the result wouldn't be any better. So why bother? Just use the right tools and get the job done."
davido
Addict
Addict
Posts: 1890
Joined: Fri Nov 09, 2012 11:04 pm
Location: Uttoxeter, UK

Re: Find circle that goes through 3 points

Post by davido »

@Seymour Clufley,
Interesting demonstration.
Thank you for sharing.
DE AA EB
Post Reply