//This program demonstrates a "ghost image" effect problem while scaling with OpenGL and mipmaps.
//Loads bmp1.png and bmp2.png.
//gcc -lallegro -lallegro_image mipmap_mishap.c

#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>

int main() {
	float scale = 1.0;
	bool scale_going_up = false;
	al_init();
	al_init_image_addon();
	al_install_keyboard();

	//We need OpenGL and mipmapping for this.
	al_set_new_display_flags(ALLEGRO_OPENGL);
	al_set_new_bitmap_flags(ALLEGRO_MIPMAP);

	ALLEGRO_DISPLAY* display = al_create_display(400, 400);
	ALLEGRO_TIMER* timer = al_create_timer(1.0 / 60.0);
	ALLEGRO_EVENT_QUEUE* queue = al_create_event_queue();
	al_register_event_source(queue, al_get_timer_event_source(timer));
	al_register_event_source(queue, al_get_keyboard_event_source());

	ALLEGRO_BITMAP* img = al_load_bitmap("bmp1.png");
	ALLEGRO_BITMAP* new_img = al_load_bitmap("bmp2.png");

	//bmp1.png is old. We want bmp2.png on img, now.
	al_set_target_bitmap(img); {
		al_draw_bitmap(new_img, 0 , 0 , 0);
	} al_set_target_backbuffer(display);

	ALLEGRO_EVENT ev;
	al_start_timer(timer);

	while(true) {
		al_wait_for_event(queue, &ev);
		if(ev.type == ALLEGRO_EVENT_TIMER) {

			ALLEGRO_TRANSFORM t, old;
			al_identity_transform(&t);
			al_scale_transform(&t, scale, scale);

			al_copy_transform(&old, al_get_current_transform());
			al_use_transform(&t); {

				al_clear_to_color(al_map_rgb(128 , 0 , 0));
				al_draw_bitmap(img, 0 , 0 , 0);
				al_flip_display();

			} al_use_transform(&old);

			//Animate the scaling.
			scale += (0.40 / 60.0) * (scale_going_up ? 1 : -1);
			if(scale < 0.4) scale_going_up = true;
			if(scale > 1.2) scale_going_up = false;

		} else {
			if(ev.type == ALLEGRO_EVENT_KEY_DOWN) return 0;
		}
	} return 0;
}
