1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
// Copyright (c) 2014 by SiegeLord
//
// All rights reserved. Distributed under ZLib. For full terms see the file LICENSE.

use allegro_util::{c_bool, from_c_str, Flag};
use bitmap_like::{BitmapFlags, BitmapLike};
use color::{Color, PixelFormat};
use config::Config;
use display::{Display, DisplayFlags, DisplayOption, DisplayOptionImportance};
use std::sync::Mutex;

use events::EventSource;

use ffi::*;
use keycodes::{KeyCode, KeyModifier};
use libc::*;
#[cfg(any(allegro_5_2_0, allegro_5_1_0))]
use shader::{Shader, ShaderPlatform, ShaderType, ShaderUniform};
use std::ffi::{CStr, CString};
use std::mem;
use std::ptr;
use std::thread;
use transformations::Transform;

struct ThreadState
{
	id: thread::ThreadId,
	cur_bitmap: *mut ALLEGRO_BITMAP,
	cur_display: *mut ALLEGRO_DISPLAY,
}

unsafe impl Send for ThreadState {}

lazy_static! {
	static ref THREAD_STATE: Mutex<Vec<ThreadState>> = Mutex::new(vec![]);
}

unsafe fn get_real_bitmap(bmp: *mut ALLEGRO_BITMAP) -> *mut ALLEGRO_BITMAP
{
	if bmp.is_null() || al_is_sub_bitmap(bmp) == 0
	{
		bmp
	}
	else
	{
		al_get_parent_bitmap(bmp)
	}
}

pub(crate) unsafe fn update_thread_state()
{
	let cur_id = thread::current().id();
	let mut thread_state = THREAD_STATE.lock().unwrap();
	let pos = (*thread_state)
		.iter()
		.position(|s| s.id == cur_id)
		.unwrap_or(thread_state.len());
	if pos >= thread_state.len()
	{
		thread_state.push(ThreadState {
			id: cur_id,
			cur_bitmap: ptr::null_mut(),
			cur_display: ptr::null_mut(),
		});
	}
	thread_state[pos].cur_bitmap = get_real_bitmap(al_get_target_bitmap());
	thread_state[pos].cur_display = al_get_current_display();
}

pub(crate) unsafe fn check_bitmap_targeted_elsewhere(bmp: *mut ALLEGRO_BITMAP, action: &str)
{
	if bmp.is_null()
	{
		return;
	}
	let cur_id = thread::current().id();
	let thread_state = THREAD_STATE.lock().unwrap();
	let bmp = get_real_bitmap(bmp);
	if let Some(s) = thread_state
		.iter()
		.find(|s| s.cur_bitmap == bmp && s.id != cur_id)
	{
		panic!(
			"Attempting to {} bitmap {:?} in thread {:?}, but it is still targeted in thread {:?}",
			action, s.cur_bitmap, cur_id, s.id
		);
	}
}

pub(crate) unsafe fn check_display_targeted_elsewhere(disp: *mut ALLEGRO_DISPLAY, action: &str)
{
	if disp.is_null()
	{
		return;
	}
	let cur_id = thread::current().id();
	let thread_state = THREAD_STATE.lock().unwrap();
	if let Some(s) = thread_state
		.iter()
		.find(|s| s.cur_display == disp && s.id != cur_id)
	{
		panic!(
			"Attempting to {} display {:?} in thread {:?}, but it is still targeted in thread {:?}",
			action, s.cur_display, cur_id, s.id
		);
	}
}

fn check_valid_target_bitmap()
{
	unsafe {
		if al_get_target_bitmap().is_null()
		{
			panic!("Target bitmap is null!");
		}
	}
}

flag_type! {
	BitmapDrawingFlags
	{
		FLIP_NONE = 0x1,
		FLIP_HORIZONTAL = ALLEGRO_FLIP_HORIZONTAL << 1,
		FLIP_VERTICAL = ALLEGRO_FLIP_VERTICAL << 1
	}
}

#[repr(u32)]
#[derive(Copy, Clone, Debug)]
pub enum BlendMode
{
	Zero = ALLEGRO_ZERO,
	One = ALLEGRO_ONE,
	Alpha = ALLEGRO_ALPHA,
	InverseAlpha = ALLEGRO_INVERSE_ALPHA,
	SrcColor = ALLEGRO_SRC_COLOR,
	DestColor = ALLEGRO_DEST_COLOR,
	InverseSrcColor = ALLEGRO_INVERSE_SRC_COLOR,
	InverseDestColor = ALLEGRO_INVERSE_DEST_COLOR,
	ConstColor = ALLEGRO_CONST_COLOR,
	InverseConstColor = ALLEGRO_INVERSE_CONST_COLOR,
}

#[repr(u32)]
#[derive(Copy, Clone, Debug)]
pub enum BlendOperation
{
	Add = ALLEGRO_ADD,
	SrcMinusDest = ALLEGRO_SRC_MINUS_DEST,
	DestMinusSrc = ALLEGRO_DEST_MINUS_SRC,
}

/// Extents of a monitor.
#[derive(Copy, Clone, Debug)]
pub struct MonitorInfo
{
	pub x1: i32,
	pub y1: i32,
	pub x2: i32,
	pub y2: i32,
}

#[repr(u32)]
#[derive(Copy, Clone, Debug)]
pub enum DepthFunction
{
	Never = ALLEGRO_RENDER_NEVER as u32,
	Always = ALLEGRO_RENDER_ALWAYS as u32,
	Less = ALLEGRO_RENDER_LESS as u32,
	Equal = ALLEGRO_RENDER_EQUAL as u32,
	LessEqual = ALLEGRO_RENDER_LESS_EQUAL as u32,
	Greater = ALLEGRO_RENDER_GREATER as u32,
	NotEqual = ALLEGRO_RENDER_NOT_EQUAL as u32,
	GreaterEqual = ALLEGRO_RENDER_GREATER_EQUAL as u32,
}

/// Type through which you'll be doing most your interaction with Allegro.
pub struct Core
{
	system_config: Config,
}

impl Core
{
	/// This must be called on the main thread.
	pub fn init() -> Result<Core, String>
	{
		Core::init_with_config(&Config::new())
	}

	/// Initializes Allegro while merging in the system_config into the system configuration.
	pub fn init_with_config(system_config: &Config) -> Result<Core, String>
	{
		use std::sync::Once;
		static mut RUN_ONCE: Once = Once::new();

		let mut res = Err("Already initialized.".to_string());
		unsafe {
			RUN_ONCE.call_once(|| {
				res = if al_install_system(ALLEGRO_VERSION_INT as c_int, None) != 0
				{
					al_merge_config_into(al_get_system_config(), system_config.get_allegro_config() as *const _);
					let config = Config::wrap(al_get_system_config(), false);
					Ok(Core { system_config: config })
				}
				else
				{
					let version = al_get_allegro_version();
					let major = version >> 24;
					let minor = (version >> 16) & 255;
					let revision = (version >> 8) & 255;
					let release = version & 255;

					Err(format!(
						"The system Allegro version ({}.{}.{}.{}) does not match the version of this binding ({}.{}.{}.{})",
						major, minor, revision, release, ALLEGRO_VERSION, ALLEGRO_SUB_VERSION, ALLEGRO_WIP_VERSION, ALLEGRO_RELEASE_NUMBER
					))
				};
			});
		}
		res
	}

	/// Returns the system config.
	pub fn get_system_config(&self) -> &Config
	{
		&self.system_config
	}

	/// Returns the system config.
	pub fn get_system_config_mut(&mut self) -> &mut Config
	{
		&mut self.system_config
	}

	pub fn get_num_video_adapters(&self) -> i32
	{
		unsafe { al_get_num_video_adapters() as i32 }
	}

	pub fn get_monitor_info(&self, adapter: i32) -> Result<MonitorInfo, ()>
	{
		unsafe {
			let mut c_info = ALLEGRO_MONITOR_INFO {
				x1: 0,
				y1: 0,
				x2: 0,
				y2: 0,
			};
			if al_get_monitor_info(adapter as c_int, &mut c_info as *mut _) != 0
			{
				Ok(MonitorInfo {
					x1: c_info.x1 as i32,
					y1: c_info.y1 as i32,
					x2: c_info.x2 as i32,
					y2: c_info.y2 as i32,
				})
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn rest(&self, seconds: f64)
	{
		unsafe {
			al_rest(seconds as c_double);
		}
	}

	pub fn get_time(&self) -> f64
	{
		unsafe { al_get_time() as f64 }
	}

	pub fn install_keyboard(&self) -> Result<(), ()>
	{
		unsafe {
			if al_install_keyboard() != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn is_keyboard_installed(&self) -> bool
	{
		unsafe { al_is_keyboard_installed() != 0 }
	}

	pub fn get_keyboard_event_source(&self) -> Option<EventSource>
	{
		if self.is_keyboard_installed()
		{
			unsafe { Some(EventSource::wrap(al_get_keyboard_event_source())) }
		}
		else
		{
			None
		}
	}

	pub fn set_keyboard_leds(&self, leds: KeyModifier) -> Result<(), ()>
	{
		assert!(self.is_keyboard_installed());
		unsafe {
			if al_set_keyboard_leds(leds.get() as c_int) != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn keycode_to_name(&self, k: KeyCode) -> String
	{
		assert!(self.is_keyboard_installed());
		unsafe { from_c_str(al_keycode_to_name(k as c_int)) }
	}

	pub fn install_mouse(&self) -> Result<(), ()>
	{
		unsafe {
			if al_install_mouse() != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn is_mouse_installed(&self) -> bool
	{
		unsafe { al_is_mouse_installed() != 0 }
	}

	pub fn get_mouse_event_source(&self) -> Option<EventSource>
	{
		if self.is_mouse_installed()
		{
			unsafe { Some(EventSource::wrap(al_get_mouse_event_source())) }
		}
		else
		{
			None
		}
	}

	pub fn install_joystick(&self) -> Result<(), ()>
	{
		unsafe {
			if al_install_joystick() != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn is_joystick_installed(&self) -> bool
	{
		unsafe { al_is_joystick_installed() != 0 }
	}

	pub fn get_joystick_event_source(&self) -> Option<EventSource>
	{
		if self.is_joystick_installed()
		{
			unsafe { Some(EventSource::wrap(al_get_joystick_event_source())) }
		}
		else
		{
			None
		}
	}

	pub fn reconfigure_joysticks(&self) -> Result<(), ()>
	{
		assert!(self.is_joystick_installed());
		unsafe {
			if al_reconfigure_joysticks() != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn get_num_joysticks(&self) -> i32
	{
		assert!(self.is_joystick_installed());
		unsafe { al_get_num_joysticks() as i32 }
	}

	pub fn get_mouse_num_buttons(&self) -> u32
	{
		assert!(self.is_mouse_installed());
		unsafe { al_get_mouse_num_buttons() as u32 }
	}

	pub fn get_mouse_num_axes(&self) -> u32
	{
		assert!(self.is_mouse_installed());
		unsafe { al_get_mouse_num_axes() as u32 }
	}

	pub fn set_mouse_xy(&self, display: &Display, x: i32, y: i32) -> Result<(), ()>
	{
		assert!(self.is_mouse_installed());
		unsafe {
			if al_set_mouse_xy(display.get_allegro_display(), x as c_int, y as c_int) != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn set_mouse_z(&self, z: i32) -> Result<(), ()>
	{
		assert!(self.is_mouse_installed());
		unsafe {
			if al_set_mouse_z(z as c_int) != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn set_mouse_w(&self, w: i32) -> Result<(), ()>
	{
		assert!(self.is_mouse_installed());
		unsafe {
			if al_set_mouse_w(w as c_int) != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn set_mouse_axis(&self, axis: i32, value: i32) -> Result<(), ()>
	{
		assert!(self.is_mouse_installed());
		unsafe {
			if al_set_mouse_axis(axis as c_int, value as c_int) != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn grab_mouse(&self, display: &Display) -> Result<(), ()>
	{
		assert!(self.is_mouse_installed());
		unsafe {
			if al_grab_mouse(display.get_allegro_display()) != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn ungrab_mouse(&self) -> Result<(), ()>
	{
		assert!(self.is_mouse_installed());
		unsafe {
			if al_ungrab_mouse() != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn set_new_bitmap_flags(&self, flags: BitmapFlags)
	{
		unsafe {
			al_set_new_bitmap_flags(flags.get() as c_int);
		}
	}

	pub fn get_new_bitmap_flags(&self) -> BitmapFlags
	{
		unsafe { mem::transmute(al_get_new_bitmap_flags() as u32) }
	}

	pub fn set_new_bitmap_format(&self, format: PixelFormat)
	{
		unsafe {
			al_set_new_bitmap_format(format as c_int);
		}
	}

	pub fn get_new_bitmap_format(&self) -> PixelFormat
	{
		unsafe { mem::transmute(al_get_new_bitmap_format() as u32) }
	}

	pub fn set_target_bitmap<T: BitmapLike>(&self, bmp: Option<&T>)
	{
		unsafe {
			al_set_target_bitmap(
				bmp.map(|b| b.get_allegro_bitmap())
					.unwrap_or(ptr::null_mut()),
			);
			check_bitmap_targeted_elsewhere(al_get_target_bitmap(), "target");
			check_display_targeted_elsewhere(al_get_current_display(), "target");
			update_thread_state();
		}
	}

	pub fn clear_to_color(&self, color: Color)
	{
		check_valid_target_bitmap();
		unsafe {
			al_clear_to_color(color.get_allegro_color());
		}
	}

	#[cfg(any(allegro_5_2_0, allegro_5_1_2))]
	pub fn clear_depth_buffer(&self, z: f32)
	{
		check_valid_target_bitmap();
		unsafe {
			al_clear_depth_buffer(z);
		}
	}

	pub fn draw_pixel(&self, x: f32, y: f32, color: Color)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_pixel(x as c_float, y as c_float, color.get_allegro_color());
		}
	}

	pub fn put_pixel(&self, x: i32, y: i32, color: Color)
	{
		check_valid_target_bitmap();
		unsafe {
			al_put_pixel(x as c_int, y as c_int, color.get_allegro_color());
		}
	}

	pub fn put_blended_pixel(&self, x: i32, y: i32, color: Color)
	{
		check_valid_target_bitmap();
		unsafe {
			al_put_blended_pixel(x as c_int, y as c_int, color.get_allegro_color());
		}
	}

	pub fn draw_bitmap<T: BitmapLike>(
		&self, bitmap: &T, dx: f32, dy: f32, flags: BitmapDrawingFlags,
	)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_bitmap(
				bitmap.get_allegro_bitmap(),
				dx as c_float,
				dy as c_float,
				(flags.get() >> 1) as c_int,
			);
		}
	}

	pub fn draw_bitmap_region<T: BitmapLike>(
		&self, bitmap: &T, sx: f32, sy: f32, sw: f32, sh: f32, dx: f32, dy: f32,
		flags: BitmapDrawingFlags,
	)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_bitmap_region(
				bitmap.get_allegro_bitmap(),
				sx as c_float,
				sy as c_float,
				sw as c_float,
				sh as c_float,
				dx as c_float,
				dy as c_float,
				(flags.get() >> 1) as c_int,
			);
		}
	}

	pub fn draw_scaled_bitmap<T: BitmapLike>(
		&self, bitmap: &T, sx: f32, sy: f32, sw: f32, sh: f32, dx: f32, dy: f32, dw: f32, dh: f32,
		flags: BitmapDrawingFlags,
	)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_scaled_bitmap(
				bitmap.get_allegro_bitmap(),
				sx as c_float,
				sy as c_float,
				sw as c_float,
				sh as c_float,
				dx as c_float,
				dy as c_float,
				dw as c_float,
				dh as c_float,
				(flags.get() >> 1) as c_int,
			);
		}
	}

	pub fn draw_rotated_bitmap<T: BitmapLike>(
		&self, bitmap: &T, cx: f32, cy: f32, dx: f32, dy: f32, angle: f32,
		flags: BitmapDrawingFlags,
	)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_rotated_bitmap(
				bitmap.get_allegro_bitmap(),
				cx as c_float,
				cy as c_float,
				dx as c_float,
				dy as c_float,
				angle as c_float,
				(flags.get() >> 1) as c_int,
			);
		}
	}

	pub fn draw_scaled_rotated_bitmap<T: BitmapLike>(
		&self, bitmap: &T, cx: f32, cy: f32, dx: f32, dy: f32, xscale: f32, yscale: f32,
		angle: f32, flags: BitmapDrawingFlags,
	)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_scaled_rotated_bitmap(
				bitmap.get_allegro_bitmap(),
				cx as c_float,
				cy as c_float,
				dx as c_float,
				dy as c_float,
				xscale as c_float,
				yscale as c_float,
				angle as c_float,
				(flags.get() >> 1) as c_int,
			);
		}
	}

	pub fn draw_tinted_bitmap<T: BitmapLike>(
		&self, bitmap: &T, tint: Color, dx: f32, dy: f32, flags: BitmapDrawingFlags,
	)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_tinted_bitmap(
				bitmap.get_allegro_bitmap(),
				tint.get_allegro_color(),
				dx as c_float,
				dy as c_float,
				(flags.get() >> 1) as c_int,
			);
		}
	}

	pub fn draw_tinted_bitmap_region<T: BitmapLike>(
		&self, bitmap: &T, tint: Color, sx: f32, sy: f32, sw: f32, sh: f32, dx: f32, dy: f32,
		flags: BitmapDrawingFlags,
	)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_tinted_bitmap_region(
				bitmap.get_allegro_bitmap(),
				tint.get_allegro_color(),
				sx as c_float,
				sy as c_float,
				sw as c_float,
				sh as c_float,
				dx as c_float,
				dy as c_float,
				(flags.get() >> 1) as c_int,
			);
		}
	}

	pub fn draw_tinted_scaled_bitmap<T: BitmapLike>(
		&self, bitmap: &T, tint: Color, sx: f32, sy: f32, sw: f32, sh: f32, dx: f32, dy: f32,
		dw: f32, dh: f32, flags: BitmapDrawingFlags,
	)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_tinted_scaled_bitmap(
				bitmap.get_allegro_bitmap(),
				tint.get_allegro_color(),
				sx as c_float,
				sy as c_float,
				sw as c_float,
				sh as c_float,
				dx as c_float,
				dy as c_float,
				dw as c_float,
				dh as c_float,
				(flags.get() >> 1) as c_int,
			);
		}
	}

	pub fn draw_tinted_rotated_bitmap<T: BitmapLike>(
		&self, bitmap: &T, tint: Color, cx: f32, cy: f32, dx: f32, dy: f32, angle: f32,
		flags: BitmapDrawingFlags,
	)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_tinted_rotated_bitmap(
				bitmap.get_allegro_bitmap(),
				tint.get_allegro_color(),
				cx as c_float,
				cy as c_float,
				dx as c_float,
				dy as c_float,
				angle as c_float,
				(flags.get() >> 1) as c_int,
			);
		}
	}

	pub fn draw_tinted_scaled_rotated_bitmap<T: BitmapLike>(
		&self, bitmap: &T, tint: Color, cx: f32, cy: f32, dx: f32, dy: f32, xscale: f32,
		yscale: f32, angle: f32, flags: BitmapDrawingFlags,
	)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_tinted_scaled_rotated_bitmap(
				bitmap.get_allegro_bitmap(),
				tint.get_allegro_color(),
				cx as c_float,
				cy as c_float,
				dx as c_float,
				dy as c_float,
				xscale as c_float,
				yscale as c_float,
				angle as c_float,
				(flags.get() >> 1) as c_int,
			);
		}
	}

	pub fn draw_tinted_scaled_rotated_bitmap_region<T: BitmapLike>(
		&self, bitmap: &T, sx: f32, sy: f32, sw: f32, sh: f32, tint: Color, cx: f32, cy: f32,
		dx: f32, dy: f32, xscale: f32, yscale: f32, angle: f32, flags: BitmapDrawingFlags,
	)
	{
		check_valid_target_bitmap();
		unsafe {
			al_draw_tinted_scaled_rotated_bitmap_region(
				bitmap.get_allegro_bitmap(),
				sx as c_float,
				sy as c_float,
				sw as c_float,
				sh as c_float,
				tint.get_allegro_color(),
				cx as c_float,
				cy as c_float,
				dx as c_float,
				dy as c_float,
				xscale as c_float,
				yscale as c_float,
				angle as c_float,
				(flags.get() >> 1) as c_int,
			);
		}
	}

	pub fn set_clipping_rectangle(&self, x: i32, y: i32, width: i32, height: i32)
	{
		check_valid_target_bitmap();
		unsafe {
			al_set_clipping_rectangle(x as c_int, y as c_int, width as c_int, height as c_int);
		}
	}

	pub fn reset_clipping_rectangle(&self)
	{
		check_valid_target_bitmap();
		unsafe {
			al_reset_clipping_rectangle();
		}
	}

	pub fn get_clipping_rectangle(&self) -> (i32, i32, i32, i32)
	{
		check_valid_target_bitmap();
		unsafe {
			let mut x: c_int = 0;
			let mut y: c_int = 0;
			let mut width: c_int = 0;
			let mut height: c_int = 0;
			al_get_clipping_rectangle(&mut x, &mut y, &mut width, &mut height);
			(x as i32, y as i32, width as i32, height as i32)
		}
	}

	pub fn set_new_display_flags(&self, flags: DisplayFlags)
	{
		unsafe {
			al_set_new_display_flags(flags.get() as c_int);
		}
	}

	pub fn get_new_display_flags(&self) -> DisplayFlags
	{
		unsafe { mem::transmute(al_get_new_display_flags()) }
	}

	pub fn set_new_display_refresh_rate(&self, rate: i32)
	{
		unsafe {
			al_set_new_display_refresh_rate(rate as c_int);
		}
	}

	pub fn get_new_display_refresh_rate(&self) -> i32
	{
		unsafe { al_get_new_display_refresh_rate() as i32 }
	}

	pub fn set_new_display_adapter(&self, adapter: i32)
	{
		unsafe {
			al_set_new_display_adapter(adapter as c_int);
		}
	}

	pub fn get_new_display_adapter(&self) -> i32
	{
		unsafe { al_get_new_display_adapter() as i32 }
	}

	pub fn set_new_window_position(&self, x: i32, y: i32)
	{
		unsafe {
			al_set_new_window_position(x as c_int, y as c_int);
		}
	}

	pub fn get_new_window_position(&self) -> (i32, i32)
	{
		unsafe {
			use std::mem::MaybeUninit;

			let mut x = MaybeUninit::uninit();
			let mut y = MaybeUninit::uninit();
			al_get_new_window_position(x.as_mut_ptr(), y.as_mut_ptr());
			(x.assume_init() as i32, y.assume_init() as i32)
		}
	}

	pub fn reset_new_display_options(&self)
	{
		unsafe {
			al_reset_new_display_options();
		}
	}

	pub fn set_new_display_option(
		&self, option: DisplayOption, value: i32, importance: DisplayOptionImportance,
	)
	{
		unsafe {
			al_set_new_display_option(option as c_int, value as c_int, importance as c_int);
		}
	}

	pub fn get_new_display_option(&self, option: DisplayOption) -> (i32, DisplayOptionImportance)
	{
		unsafe {
			use std::mem::MaybeUninit;

			let mut imp = MaybeUninit::uninit();

			let val = al_get_new_display_option(option as c_int, imp.as_mut_ptr());
			(val as i32, mem::transmute(imp.assume_init()))
		}
	}

	pub fn get_current_transform(&self) -> Transform
	{
		check_valid_target_bitmap();
		let t = unsafe { al_get_current_transform() };
		unsafe { Transform::wrap(*t) }
	}

	pub fn use_transform(&self, trans: &Transform)
	{
		check_valid_target_bitmap();
		unsafe {
			al_use_transform(&trans.get_allegro_transform());
		}
	}

	#[cfg(any(allegro_5_2_0, allegro_5_1_9))]
	pub fn use_projection_transform(&self, trans: &Transform)
	{
		check_valid_target_bitmap();
		unsafe {
			al_use_projection_transform(&trans.get_allegro_transform());
		}
	}

	/// Set the shader as current for the current bitmap. Pass None to stop using this shader.
	/// Returns an error if the shader isn't compatible with the bitmap.
	#[cfg(any(allegro_5_2_0, allegro_5_1_6))]
	pub fn use_shader(&self, shader: Option<&Shader>) -> Result<(), ()>
	{
		check_valid_target_bitmap();
		match shader
		{
			Some(shader) =>
			{
				let ret = unsafe { al_use_shader(shader.get_allegro_shader()) };
				if ret != 0
				{
					Ok(())
				}
				else
				{
					Err(())
				}
			}
			None =>
			{
				unsafe {
					al_use_shader(ptr::null_mut());
				}
				Ok(())
			}
		}
	}

	/// Returns the source of the shader that Allegro uses by default.
	#[cfg(any(allegro_5_2_0, allegro_5_1_6))]
	pub fn get_default_shader_source(
		&self, platform: ShaderPlatform, shader_type: ShaderType,
	) -> Option<String>
	{
		unsafe {
			let src = al_get_default_shader_source(
				platform as ALLEGRO_SHADER_PLATFORM,
				shader_type as ALLEGRO_SHADER_TYPE,
			);
			if src.is_null()
			{
				None
			}
			else
			{
				Some(CStr::from_ptr(src).to_string_lossy().into_owned())
			}
		}
	}

	pub fn flip_display(&self)
	{
		unsafe {
			al_flip_display();
		}
	}

	pub fn update_display_region(&self, x: i32, y: i32, width: i32, height: i32)
	{
		unsafe {
			al_update_display_region(x as c_int, y as c_int, width as c_int, height as c_int);
		}
	}

	pub fn wait_for_vsync(&self) -> Result<(), ()>
	{
		unsafe {
			if al_wait_for_vsync() != 0
			{
				Ok(())
			}
			else
			{
				Err(())
			}
		}
	}

	pub fn hold_bitmap_drawing(&self, hold: bool)
	{
		unsafe {
			al_hold_bitmap_drawing(hold as c_bool);
		}
	}

	pub fn is_bitmap_drawing_held(&self) -> bool
	{
		unsafe { al_is_bitmap_drawing_held() != 0 }
	}

	/// Set a sampler for a particular uniform and unit for the current shader.
	/// Different uniforms should be set to different units.
	/// Pass None to bmp to clear the sampler.
	#[cfg(any(allegro_5_2_0, allegro_5_1_0))]
	pub fn set_shader_sampler<T: BitmapLike>(
		&mut self, name: &str, bmp: &T, unit: i32,
	) -> Result<(), ()>
	{
		let c_name = CString::new(name.as_bytes()).unwrap();
		let ret = unsafe {
			al_set_shader_sampler(c_name.as_ptr(), bmp.get_allegro_bitmap(), unit as c_int) != 0
		};
		if ret
		{
			Ok(())
		}
		else
		{
			Err(())
		}
	}

	/// Sets a shader uniform to a value.
	#[cfg(any(allegro_5_2_0, allegro_5_1_0))]
	pub fn set_shader_uniform<T: ShaderUniform + ?Sized>(
		&self, name: &str, val: &T,
	) -> Result<(), ()>
	{
		unsafe { val.set_self_for_shader(name) }
	}

	/// Sets a shader uniform to a value.
	#[cfg(any(allegro_5_2_0, allegro_5_1_0))]
	pub fn set_shader_transform(&self, name: &str, val: &Transform) -> Result<(), ()>
	{
		let ret = unsafe {
			let name = CString::new(name.as_bytes()).unwrap();
			al_set_shader_matrix(name.as_ptr(), &val.get_allegro_transform())
		};
		if ret != 0
		{
			Ok(())
		}
		else
		{
			Err(())
		}
	}

	/// Set blender options.
	pub fn set_blender(&self, op: BlendOperation, source: BlendMode, dest: BlendMode)
	{
		unsafe {
			al_set_blender(op as c_int, source as c_int, dest as c_int);
		}
	}

	/// Set blender options, with alpha channel getting a separate setting.
	pub fn set_separate_blender(
		&self, op: BlendOperation, source: BlendMode, dest: BlendMode, alpha_op: BlendOperation,
		alpha_source: BlendMode, alpha_dest: BlendMode,
	)
	{
		unsafe {
			al_set_separate_blender(
				op as c_int,
				source as c_int,
				dest as c_int,
				alpha_op as c_int,
				alpha_source as c_int,
				alpha_dest as c_int,
			);
		}
	}

	pub fn set_depth_test(&self, function: Option<DepthFunction>)
	{
		if let Some(function) = function
		{
			unsafe {
				al_set_render_state(ALLEGRO_DEPTH_TEST, 1);
				al_set_render_state(ALLEGRO_DEPTH_FUNCTION, function as c_int);
			}
		}
		else
		{
			unsafe {
				al_set_render_state(ALLEGRO_DEPTH_TEST, 0);
			}
		}
	}
}