Set FPS

Share your advanced PureBasic knowledge/code with the community.
User avatar
minimy
Enthusiast
Enthusiast
Posts: 619
Joined: Mon Jul 08, 2013 8:43 pm
Location: off world

Set FPS

Post by minimy »

Hi everybody! I dont know if this is the right way to do this, feel free to improve my code.
The idea is lock fps when write a game or any visual software in diferent machines.

Have a nice summer and walk by the shadow :)

Code: Select all

Global canvas

Global FPSreales
Global.d DeltaTMax
Global.q DeltaTAcumulada, DeltaTimeIni

Procedure drawcanvas()
	StartDrawing(CanvasOutput(canvas))
    Box(0,0,OutputWidth(),OutputHeight(), $555555)
    DrawingMode(#PB_2DDrawing_Transparent)
  	DrawText(5,5,"Fps " + StrF(FPSreales,3),$ffffff)
  	DrawText(5,25,"Max " + StrF(DeltaTMax,3),$ffffff)
	StopDrawing()
	
EndProcedure

Procedure setFps(FPSspeed)
  DeltaTMax= 1000 / FPSspeed 
  DeltaTime= ElapsedMilliseconds() - DeltaTimeIni
  DeltaTAcumulada +  DeltaTime
  If(DeltaTAcumulada >= DeltaTMax)
    FPSreales= 1000/DeltaTAcumulada
    DeltaTAcumulada = 0
    drawcanvas()
  EndIf
  DeltaTimeIni= ElapsedMilliseconds()
EndProcedure

MyFPS= 30
OpenWindow(0,0,0,1000,600,"Set FPS to "+Str(MyFPS),#PB_Window_SystemMenu | #PB_Window_ScreenCentered | #PB_Window_MaximizeGadget | #PB_Window_MinimizeGadget)
canvas= CanvasGadget(#PB_Any,5,5,WindowWidth(0),WindowHeight(0))
DeltaTimeIni= ElapsedMilliseconds()

Repeat
  event= WindowEvent()
  
  Select event
    Case #PB_Event_Gadget
      
    Case #PB_Event_CloseWindow
      Break
  EndSelect
  
  setFps(MyFPS)
  Delay(1)

ForEver


If translation=Error: reply="Sorry, Im Spanish": Endif
User avatar
Mijikai
Addict
Addict
Posts: 1520
Joined: Sun Sep 11, 2016 2:17 pm

Re: Set FPS

Post by Mijikai »

Hi minimy,
make sure that the message/event queue is completely processed before doing anything else in the main loop.
Im also not sure what Delay() internally uses but iirc. it should be fine.
User avatar
minimy
Enthusiast
Enthusiast
Posts: 619
Joined: Mon Jul 08, 2013 8:43 pm
Location: off world

Re: Set FPS

Post by minimy »

Hi minimy,
make sure that the message/event queue is completely processed before doing anything else in the main loop.
Im also not sure what Delay() internally uses but iirc. it should be fine.
Hi Mijikai, I think it processes the entire queue of messages (events) and then runs setfps. In any case you can improve and share the code if it seems good to you. I use the delay so as not to block the OS with the application.
Greetings and thanks for the suggestion.
If translation=Error: reply="Sorry, Im Spanish": Endif
Post Reply