Create an "internal" clock

BlitzMax Forums/BlitzMax Beginners Area/Create an "internal" clock

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

Not that anyone seems to care, but here is what I cobbled.

Global EVENT_CUSTOMCLOCK:Int = 7

Type TCustomClock

	Field year:Int = 0
	Field day:Int = 0
	Field hours:Int = 0
	Field minutes:Int = 0
	Field seconds:Int = 0
	Field hpd:Int = 24
	Field dpy:Int = 365
	Field tickrate:Int = 1
	Field ticker:TTimer
	Field accumulator:Int = 0
	Field trigger:Int = Null

	Method New()
		AddHook(EmitEventHook, timerhook, Self)
	End Method

	Method free()
		RemoveHook(EmitEventHook, timerhook, Self)
	End Method
	
	Function timerhook:Object(iId:Int, tData:Object, tContext:Object)
		Local clock:TCustomClock = TCustomClock(tContext)			'recast the object so it can be worked with
			Local event:TEvent = TEvent(tData)
				If event.ID = EVENT_TIMERTICK And event.source = clock.ticker		'triggered by this instantiation
					clock.seconds:+1
					clock.accumulator:+1
						If clock.seconds = 60 clock.seconds = 0; clock.minutes:+1
						If clock.minutes = 60 clock.minutes = 0; clock.hours:+1
						If clock.hours = clock.hpd clock.hours = 0; clock.day:+1
						If clock.day = clock.dpy clock.day = 0; clock.year:+1
						
					If clock.trigger = clock.accumulator
						Local newevent:TEvent = New TEvent
							newevent.ID = EVENT_CUSTOMCLOCK
							newevent.source = clock
						EmitEvent(newevent)
						
						clock.accumulator = 0
					End If
						
					Return Null
				End If
				Return event										'not what we wanted... send it back
	End Function
	
	Method timeset(hours:Int = 0, minutes:Int = 0, seconds:Int = 0, day:Int = 0, year:Int = 0)
		Self.hours = hours
		Self.minutes = minutes
		Self.seconds = seconds
		Self.day = day
		Self.year = year		
	End Method
	
	Method settrigger(time:Int)
		Self.trigger = time
	End Method
	
End Type

Function CreateCustomClock:TCustomClock(hpd:Int, dpy:Int, rate:Int = 1)
	Local clk:TCustomClock = New TCustomClock
		clk.hpd = hpd
		clk.dpy = dpy
		clk.ticker = CreateTimer(rate)
	Return clk
End Function


And a sample

'clock tester

Include "includes/TCustomClock.bmx"

Local clock:TCustomClock = CreateCustomClock(31, 500, 1) '31 hour day, 500 day year.. thats a really screwed up planet
	clock.settrigger(5)	'fire every 5 seconds

Repeat 
	PollEvent()
	If EventID() = EVENT_CUSTOMCLOCK Print "5 seconds since last tick!"
	Delay(2)
Forever