// © David R W BArr 2009
// Starfield Demo

// Click "RUN" & Enjoy!!

!include('apron.aps')

!define(BUFFER_W, 512)
!define(BUFFER_H, 512)

!define(STARS,256)


!define(2PI, 6.28318)


!create_reg('buffer', BUFFER_W, BUFFER_H)
!create_reg('image', BUFFER_W, BUFFER_H)


!create_reg('star_mask', STARS, 1)
!create_reg('star_speed', STARS, 1)
!create_reg('star_temp', STARS, 1)
!create_reg('star_r', STARS, 1)
!create_reg('star_t', STARS, 1)

!palette(PAL_GREYSCALE)

!slider('Warp Speed', 0, 100, 10)
!slider('Roll', -90, 90, 0)

r[buffer] = -128
origin_x = BUFFER_W
origin_x = origin_x / 2
origin_y = BUFFER_H
origin_y = origin_y / 2

showreg(r[buffer])

r[star_r] = white_noise(256)
r[star_t] = white_noise(2PI)

r[image] = input(IO_IMAGE_S, 'StarfieldDemo', UNUSED, 'png') 

//Create fast star mask
c = 0
#fastloop
	set(r[star_speed], c, 0, c)
	c = c + 1
	jumpif(c, <, STARS, #fastloop)
r[star_speed] = r[star_speed] / STARS

#start

	// Check for hyperspace
	speed = datain(0)
	jumpif(speed, >, 80, #hyperspace)
	r[buffer] = r[image]
	#hyperspace
	
	// Draw star field
	call(#sub_plot_stars)
	
	// Normal Stars
	speed = speed / 500
	r[star_temp] = r[star_speed] * speed
	r[star_temp] = r[star_r] * r[star_temp]
	r[star_r] = r[star_r] + r[star_temp]
	
	// Create new stars & kill old ones
	r[star_mask] = mask(r[star_r], >, BUFFER_W)
	maskon(r[star_mask])
		r[star_temp] = white_noise(2PI)
		r[star_t] = r[star_temp]
		r[star_temp] = white_noise(origin_x)
		r[star_r] = r[star_temp]
	maskoff(0)
	

	simshow(r[buffer])

jump(#start)

#sub_plot_stars

	roll = datain(1)
	roll = roll / 180
	roll = roll * 3.14159

	c = 0
	#plot_star_loop
		sr = get(r[star_r], c, 0)
		st = get(r[star_t], c, 0)
		
		st = st + roll
		
		sx = vsin(st)
		sx = sx * sr
		sx = sx + origin_x
		
		sy = vcos(st)
		sy = sy * sr
		sy = sy + origin_y
		
		sz = sr
		sz = sz - 128
		
		sx1 = sx + 1
		sy1 = sy + 1
		
		set(r[buffer], sx, sy, sz)
		set(r[buffer], sx1, sy, sz)
		set(r[buffer], sx, sy1, sz)
		set(r[buffer], sx1, sy1, sz)
		
	
	c = c + 1
	jumpif(c, <, STARS, #plot_star_loop)
		



return