source_sdk_2013 0.1.0-alpha.8

Higher-level bindings for the Source SDK.
Documentation
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
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
//! Networked class descriptions (`public/server_class.h`, `public/dt_send.h`)
//! and access to the variables they describe.
//!
//! The game describes each networked entity class with a [`ServerClass`],
//! whose [`SendTable`] lists the [`SendProp`]s sent to clients. Tables nest:
//! a class's table embeds its base class's table as a `baseclass` property,
//! and embedded structures as further tables.
//!
//! [`NetProp`] resolves a property by name to where it lives in an entity, as
//! SourceMod's `Prop_Send` lookups do, and reads or writes it after checking
//! the entity's class and the variable's storage.

#[cfg(test)]
#[path = "tests/datatables.rs"]
mod tests;

use crate::NotThreadSafe;
use crate::edicts::Edict;
use crate::entities::{Entity, EntityHandle};
use crate::interfaces::ValveEngine;
use crate::math::{QAngle, Vector};
use glam::Vec2;

use sdk_raw::datatables::{
	SPROP_CHANGES_OFTEN, SPROP_COLLAPSIBLE, SPROP_COORD, SPROP_COORD_MP, SPROP_COORD_MP_INTEGRAL,
	SPROP_COORD_MP_LOWPRECISION, SPROP_ENCODED_AGAINST_TICKCOUNT, SPROP_EXCLUDE, SPROP_INSIDEARRAY,
	SPROP_IS_A_VECTOR_ELEM, SPROP_NORMAL, SPROP_NOSCALE, SPROP_PROXY_ALWAYS_YES, SPROP_ROUNDDOWN,
	SPROP_ROUNDUP, SPROP_UNSIGNED, SPROP_XYZE, call_var_proxy, is_direct_table_proxy,
	standard_var_proxies,
};

use sdk_raw::entities::NUM_NETWORKED_EHANDLE_BITS;
use sdk_raw::util::cstr::{borrow_cstr, copy_cstr};
use std::any::type_name;
use std::ffi::{CStr, CString, c_int, c_void};
use std::fmt::{self, Debug, Display, Formatter};
use std::marker::PhantomData;
use std::ptr::NonNull;

/// How deep [`NetProp`] lookups descend into nested tables before giving up.
const MAX_TABLE_DEPTH: usize = 32;

bitflags::bitflags! {
	/// The `SPROP_*` flags of a [`SendProp`], from `public/dt_common.h`.
	///
	/// Flags read from the engine, such as [`SendProp::flags`], keep every bit,
	/// including those without a constant here. Every bit counts as a known
	/// flag, so [`all`](Self::all) sets all 32, and `!` and
	/// [`from_bits_truncate`](Self::from_bits_truncate) keep unnamed bits too.
	#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
	pub struct PropFlags: c_int {
		/// `SPROP_CHANGES_OFTEN`: the variable changes often, so the engine
		/// moves it to the start of its table, where it gets a small index.
		#[doc(alias("SPROP_CHANGES_OFTEN"))]
		const CHANGES_OFTEN = SPROP_CHANGES_OFTEN;

		/// `SPROP_COLLAPSIBLE`: the data table sits at offset 0 behind
		/// `SendProxy_DataTableToDataTable`, as base class tables do, so the
		/// engine can flatten it away.
		#[doc(alias("SPROP_COLLAPSIBLE"))]
		const COLLAPSIBLE = SPROP_COLLAPSIBLE;

		/// `SPROP_COORD`: the float or vector is a world coordinate, and its
		/// bit count is ignored.
		#[doc(alias("SPROP_COORD"))]
		const COORD = SPROP_COORD;

		/// `SPROP_COORD_MP`: like [`COORD`](Self::COORD), with special handling
		/// for multiplayer games.
		#[doc(alias("SPROP_COORD_MP"))]
		const COORD_MP = SPROP_COORD_MP;

		/// `SPROP_COORD_MP_INTEGRAL`: like [`COORD_MP`](Self::COORD_MP), with
		/// coordinates rounded to whole units.
		#[doc(alias("SPROP_COORD_MP_INTEGRAL"))]
		const COORD_MP_INTEGRAL = SPROP_COORD_MP_INTEGRAL;

		/// `SPROP_COORD_MP_LOWPRECISION`: like [`COORD_MP`](Self::COORD_MP),
		/// with 3 bits for the fractional part instead of 5.
		#[doc(alias("SPROP_COORD_MP_LOWPRECISION"))]
		const COORD_MP_LOW_PRECISION = SPROP_COORD_MP_LOWPRECISION;

		/// `SPROP_ENCODED_AGAINST_TICKCOUNT`: the integer's proxy encodes it
		/// relative to the tick count, as for `m_flSimulationTime`. This flag
		/// is only known to the server, and not networked.
		#[doc(alias("SPROP_ENCODED_AGAINST_TICKCOUNT"))]
		const ENCODED_AGAINST_TICK_COUNT = SPROP_ENCODED_AGAINST_TICKCOUNT;

		/// `SPROP_EXCLUDE`: the property names another property to exclude,
		/// rather than a variable.
		#[doc(alias("SPROP_EXCLUDE"))]
		const EXCLUDE = SPROP_EXCLUDE;

		/// `SPROP_INSIDEARRAY`: the property describes the elements of the
		/// array property after it.
		#[doc(alias("SPROP_INSIDEARRAY"))]
		const INSIDE_ARRAY = SPROP_INSIDEARRAY;

		/// `SPROP_IS_A_VECTOR_ELEM`: the property is one component of a vector,
		/// declared with `SENDINFO_VECTORELEM`.
		#[doc(alias("SPROP_IS_A_VECTOR_ELEM"))]
		const IS_A_VECTOR_ELEM = SPROP_IS_A_VECTOR_ELEM;

		/// `SPROP_NOSCALE`: the float is sent as is, rather than scaled into
		/// the range between its [low](SendProp::low_value) and
		/// [high](SendProp::high_value) values.
		#[doc(alias("SPROP_NOSCALE"))]
		const NO_SCALE = SPROP_NOSCALE;

		/// `SPROP_NORMAL`: the vector is a normal. Integer properties reuse the
		/// bit as `SPROP_VARINT`.
		#[doc(alias("SPROP_NORMAL", "SPROP_VARINT"))]
		const NORMAL = SPROP_NORMAL;

		/// `SPROP_PROXY_ALWAYS_YES`: the data table's proxy is a standard one
		/// that sends the table to every client.
		#[doc(alias("SPROP_PROXY_ALWAYS_YES"))]
		const PROXY_ALWAYS_YES = SPROP_PROXY_ALWAYS_YES;

		/// `SPROP_ROUNDDOWN`: the float's [high value](SendProp::high_value) is
		/// lowered by one encoding step.
		#[doc(alias("SPROP_ROUNDDOWN"))]
		const ROUND_DOWN = SPROP_ROUNDDOWN;

		/// `SPROP_ROUNDUP`: the float's [low value](SendProp::low_value) is
		/// raised by one encoding step.
		#[doc(alias("SPROP_ROUNDUP"))]
		const ROUND_UP = SPROP_ROUNDUP;

		/// `SPROP_UNSIGNED`: the integer is networked unsigned. [`Storage`]
		/// takes its signedness from this flag.
		#[doc(alias("SPROP_UNSIGNED"))]
		const UNSIGNED = SPROP_UNSIGNED;

		/// `SPROP_XYZE`: the vector uses XYZ/exponent encoding.
		#[doc(alias("SPROP_XYZE"))]
		const XYZE = SPROP_XYZE;

		// Bits without a constant here, which the engine may set.
		const _ = !0;
	}
}

/// The type a [`SendProp`] is networked as.
#[doc(alias("SendPropType"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PropKind {
	/// An integer, read as [`NetValue::Int`].
	#[doc(alias("DPT_Int"))]
	Int,

	/// A float, read as [`NetValue::Float`].
	#[doc(alias("DPT_Float"))]
	Float,

	/// Three floats, read as [`NetValue::Vector`].
	#[doc(alias("DPT_Vector"))]
	Vector,

	/// A vector of which only X and Y are networked.
	#[doc(alias("DPT_VectorXY"))]
	VectorXY,

	/// A string, read as [`NetValue::String`].
	#[doc(alias("DPT_String"))]
	String,

	/// Elements described by [`SendProp::array_prop`].
	#[doc(alias("DPT_Array"))]
	Array,

	/// A nested [`SendTable`].
	#[doc(alias("DPT_DataTable"))]
	DataTable,

	/// A type this crate does not know.
	Unknown(i64),
}

impl PropKind {
	/// Converts a `SendPropType`, keeping values this crate does not know.
	fn from_raw(raw: sys::SendPropType) -> Self {
		match raw {
			sys::SendPropType_DPT_Int => Self::Int,
			sys::SendPropType_DPT_Float => Self::Float,
			sys::SendPropType_DPT_Vector => Self::Vector,
			sys::SendPropType_DPT_VectorXY => Self::VectorXY,
			sys::SendPropType_DPT_String => Self::String,
			sys::SendPropType_DPT_Array => Self::Array,
			sys::SendPropType_DPT_DataTable => Self::DataTable,
			unknown => Self::Unknown(i64::from(unknown)),
		}
	}
}

impl Display for PropKind {
	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
		match self {
			Self::Int => f.write_str("integer"),
			Self::Float => f.write_str("float"),
			Self::Vector => f.write_str("vector"),
			Self::VectorXY => f.write_str("XY vector"),
			Self::String => f.write_str("string"),
			Self::Array => f.write_str("array"),
			Self::DataTable => f.write_str("data table"),
			Self::Unknown(raw) => write!(f, "unknown type {raw}"),
		}
	}
}

/// A networked variable's description (`SendProp`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SendProp<'s> {
	raw: NonNull<sys::SendProp>,
	_scope: PhantomData<&'s ()>,
	_not_thread_safe: NotThreadSafe,
}

/// Iterator over a table's properties.
#[derive(Debug, Clone)]
pub struct SendProps<'s> {
	table: SendTable<'s>,
	index: usize,
}

impl ExactSizeIterator for SendProps<'_> {}

impl<'s> Iterator for SendProps<'s> {
	type Item = SendProp<'s>;

	fn next(&mut self) -> Option<Self::Item> {
		let prop = self.table.prop(self.index)?;

		self.index += 1;
		Some(prop)
	}

	fn size_hint(&self) -> (usize, Option<usize>) {
		let remaining = self.table.len().saturating_sub(self.index);

		(remaining, Some(remaining))
	}
}

/// A table of networked variables (`SendTable`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SendTable<'s> {
	raw: NonNull<sys::SendTable>,
	_scope: PhantomData<&'s ()>,
	_not_thread_safe: NotThreadSafe,
}

impl<'s> SendTable<'s> {
	/// # Safety
	///
	/// `raw` must be one of the game DLL's send tables, which are statics.
	pub(crate) const unsafe fn from_raw(raw: NonNull<sys::SendTable>) -> Self {
		Self {
			raw,
			_scope: PhantomData,
			_not_thread_safe: PhantomData,
		}
	}

	/// Returns the native pointer for low-level interop.
	pub const fn as_ptr(self) -> *mut sys::SendTable {
		self.raw.as_ptr()
	}

	/// The table of the base class, which classes embed as a property named
	/// `baseclass`.
	pub fn base(self) -> Option<SendTable<'s>> {
		self.props()
			.find(|prop| prop.kind() == PropKind::DataTable && prop.name() == c"baseclass")
			.and_then(SendProp::data_table)
	}

	/// Whether this is `base`, or derives from it through `baseclass` tables.
	///
	/// Base classes sit at offset 0 of their derived classes, so offsets
	/// resolved in `base` hold for this table's entities too.
	pub fn derives_from(self, base: SendTable<'_>) -> bool {
		let mut table = Some(self);

		for _ in 0..MAX_TABLE_DEPTH {
			match table {
				Some(current) if current.as_ptr() == base.as_ptr() => return true,
				Some(current) => table = current.base(),
				None => return false,
			}
		}

		false
	}

	/// Whether this table is named `name`, such as `DT_Team`, or derives from
	/// a table so named through `baseclass` tables.
	pub(crate) fn derives_from_named(self, name: &CStr) -> bool {
		let mut table = Some(self);

		for _ in 0..MAX_TABLE_DEPTH {
			match table {
				Some(current) if current.name() == name => return true,
				Some(current) => table = current.base(),
				None => return false,
			}
		}

		false
	}

	/// Finds the first property named `name` in the table or the tables nested
	/// within it, depth first, as [`NetProp`] lookups do, but wherever its data
	/// lives: also in a table whose proxy relocates it, such as the game rules'
	/// variables, which TF2 sends from `CTFGameRulesProxy`'s `tf_gamerules_data`.
	///
	/// Array element templates and exclude properties are skipped. Use it to
	/// find a property to [override](crate::send_proxies::SendProxyOverride),
	/// rather than one to read or write.
	pub fn find_prop(self, name: &CStr) -> Option<SendProp<'s>> {
		fn search<'s>(table: SendTable<'s>, name: &CStr, depth: usize) -> Option<SendProp<'s>> {
			if depth > MAX_TABLE_DEPTH {
				return None;
			}

			table.props().find_map(|prop| {
				if prop.flags().contains(PropFlags::INSIDE_ARRAY)
					|| prop.flags().contains(PropFlags::EXCLUDE)
				{
					return None;
				}

				if prop.name() == name {
					return Some(prop);
				}

				prop.data_table()
					.filter(|_| prop.kind() == PropKind::DataTable)
					.and_then(|nested| search(nested, name, depth + 1))
			})
		}

		search(self, name, 0)
	}

	/// Whether the table has no properties.
	pub fn is_empty(self) -> bool {
		self.len() == 0
	}

	/// The number of properties in the table.
	#[doc(alias("GetNumProps"))]
	pub fn len(self) -> usize {
		// SAFETY: As for `name`.
		usize::try_from(unsafe { (&raw const (*self.as_ptr()).m_nProps).read() }).unwrap_or(0)
	}

	/// The table's name, such as `DT_TFPlayer`.
	#[doc(alias("GetName"))]
	pub fn name(self) -> &'s CStr {
		// SAFETY: Send tables and their names are statics of the game DLL.
		// Fields are read without forming references.
		unsafe { borrow_cstr((&raw const (*self.as_ptr()).m_pNetTableName).read()) }
			.unwrap_or_default()
	}

	/// The property at `index`, or `None` if `index` is out of range or the
	/// table has no properties.
	#[doc(alias("GetProp"))]
	pub fn prop(self, index: usize) -> Option<SendProp<'s>> {
		if index >= self.len() {
			return None;
		}

		// SAFETY: As for `name`.
		let props = NonNull::new(unsafe { (&raw const (*self.as_ptr()).m_pProps).read() })?;

		// SAFETY: The index is within the table's array of properties.
		Some(unsafe { SendProp::from_raw(props.add(index)) })
	}

	/// Iterates over the table's properties in order.
	pub fn props(self) -> SendProps<'s> {
		SendProps {
			table: self,
			index: 0,
		}
	}
}

/// A networked entity class, as registered by the game DLL (`ServerClass`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ServerClass<'s> {
	raw: NonNull<sys::ServerClass>,
	_scope: PhantomData<&'s ()>,
	_not_thread_safe: NotThreadSafe,
}

impl<'s> ServerClass<'s> {
	/// # Safety
	///
	/// `raw` must be one of the game DLL's server classes, which are statics.
	pub(crate) const unsafe fn from_raw(raw: NonNull<sys::ServerClass>) -> Self {
		Self {
			raw,
			_scope: PhantomData,
			_not_thread_safe: PhantomData,
		}
	}

	/// Returns the native pointer for low-level interop.
	pub const fn as_ptr(self) -> *mut sys::ServerClass {
		self.raw.as_ptr()
	}

	/// The ID the engine assigned the class for networking.
	#[doc(alias("m_ClassID"))]
	pub fn class_id(self) -> c_int {
		// SAFETY: As for `name`.
		unsafe { (&raw const (*self.as_ptr()).m_ClassID).read() }
	}

	/// The class's network name, such as `CTFPlayer`.
	#[doc(alias("GetName"))]
	pub fn name(self) -> &'s CStr {
		// SAFETY: Server classes and their names are statics of the game DLL.
		// Fields are read without forming references.
		unsafe { borrow_cstr((&raw const (*self.as_ptr()).m_pNetworkName).read()) }
			.unwrap_or_default()
	}

	/// The next class in the game DLL's list, which is sorted by name.
	fn next(self) -> Option<Self> {
		// SAFETY: As for `name`.
		let next = NonNull::new(unsafe { (&raw const (*self.as_ptr()).m_pNext).read() })?;

		// SAFETY: The list only links server classes.
		Some(unsafe { Self::from_raw(next) })
	}

	/// The table of the class's networked variables.
	#[doc(alias("m_pTable"))]
	pub fn table(self) -> Option<SendTable<'s>> {
		// SAFETY: As for `name`.
		let table = NonNull::new(unsafe { (&raw const (*self.as_ptr()).m_pTable).read() })?;

		// SAFETY: Send tables are statics of the game DLL.
		Some(unsafe { SendTable::from_raw(table) })
	}
}

/// Iterator over the game DLL's server classes, sorted by name.
#[derive(Debug, Clone)]
pub struct ServerClasses<'s> {
	next: Option<ServerClass<'s>>,
}

impl<'s> ServerClasses<'s> {
	/// # Safety
	///
	/// `head` must be null or the head of the game DLL's server class list.
	pub(crate) unsafe fn new(head: *mut sys::ServerClass) -> Self {
		Self {
			// SAFETY: The caller upholds the contract.
			next: NonNull::new(head).map(|head| unsafe { ServerClass::from_raw(head) }),
		}
	}
}

impl<'s> Iterator for ServerClasses<'s> {
	type Item = ServerClass<'s>;

	fn next(&mut self) -> Option<Self::Item> {
		let class = self.next?;

		self.next = class.next();
		Some(class)
	}
}

/// Reads a field of a `SendProp` without forming a reference.
macro_rules! prop_field {
	($prop:expr, $field:ident) => {
		// SAFETY: Properties are statics of the game DLL, which the engine only
		// changes while initializing its tables at startup.
		unsafe { (&raw const (*$prop.as_ptr()).$field).read() }
	};
}

/// A value as clients receive it, from [`NetProp::value`].
#[doc(alias("DVariant"))]
#[derive(Debug, Clone, PartialEq)]
pub enum NetValue {
	/// The value of a [`PropKind::Int`] property.
	Int(c_int),

	/// The value of a [`PropKind::Float`] property.
	Float(f32),

	/// The value of a [`PropKind::Vector`] property.
	Vector(Vector),

	/// The X and Y of a [`PropKind::VectorXY`] property.
	VectorXY(Vec2),

	/// A copy of a [`PropKind::String`] property's value, empty if the proxy
	/// gave none.
	String(CString),
}

/// A type a networked variable can be read or written as.
///
/// Implemented for the primitive types of [`Storage`], `bool` for single-byte
/// flags, and [`Vector`] and [`QAngle`] for vectors. Integers are accessed
/// at the variable's width with the signedness of the type used.
pub trait NetVar: sealed::Sealed + Copy {
	/// The storage a variable must be [compatible](Storage::is_compatible)
	/// with to be accessed as this type.
	#[doc(hidden)]
	const STORAGE: Storage;

	/// Reads the variable at `source`, which may be unaligned.
	///
	/// # Safety
	///
	/// `source` must point to a readable variable whose storage is
	/// [compatible](Storage::is_compatible) with [`Self::STORAGE`].
	#[doc(hidden)]
	unsafe fn read(source: *const u8) -> Self;

	/// Writes the value to the variable at `destination`, which may be
	/// unaligned.
	///
	/// # Safety
	///
	/// `destination` must point to a writable variable whose storage is
	/// [compatible](Storage::is_compatible) with [`Self::STORAGE`].
	#[doc(hidden)]
	unsafe fn write(self, destination: *mut u8);
}

/// The game DLL's standard send proxies (`CStandardSendProxies`).
///
/// A property's proxy converts its variable for networking, so a standard
/// proxy reveals how the variable is stored. Comparisons use widths only,
/// since a linker may fold proxies whose code is identical into one.
#[doc(alias("CStandardSendProxies"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StandardSendProxies<'s> {
	raw: NonNull<sys::CStandardSendProxies>,
	_scope: PhantomData<&'s ()>,
	_not_thread_safe: NotThreadSafe,
}

impl<'s> StandardSendProxies<'s> {
	/// # Safety
	///
	/// `raw` must be the game DLL's `g_StandardSendProxies`.
	pub(crate) const unsafe fn from_raw(raw: NonNull<sys::CStandardSendProxies>) -> Self {
		Self {
			raw,
			_scope: PhantomData,
			_not_thread_safe: PhantomData,
		}
	}

	/// Returns the native pointer for low-level interop.
	pub const fn as_ptr(self) -> *mut sys::CStandardSendProxies {
		self.raw.as_ptr()
	}

	/// Whether a nested table property's proxy passes its data through
	/// unchanged, so offsets into the nested table are relative to the
	/// containing structure.
	pub(crate) fn is_direct(self, prop: SendProp<'_>) -> bool {
		// SAFETY: The proxies are the game DLL's, set up before any plugin
		// loads, and their list of pointer-preserving proxies holds statics of
		// the game DLL, which stays loaded for `'s`. The property is one of its
		// send tables'.
		unsafe { is_direct_table_proxy(self.as_ptr(), prop.as_ptr()) }
	}

	/// How a scalar property's variable is stored, judged by its proxy.
	fn storage(self, prop: SendProp<'_>) -> Storage {
		// SAFETY: As for `is_direct`.
		let proxies = unsafe { standard_var_proxies(self.as_ptr(), prop.as_ptr()) };
		let signed = !prop.flags().contains(PropFlags::UNSIGNED);

		match prop.kind() {
			PropKind::Int if proxies.int8 => [Storage::U8, Storage::I8][usize::from(signed)],
			PropKind::Int if proxies.int16 => [Storage::U16, Storage::I16][usize::from(signed)],
			PropKind::Int if proxies.int32 => [Storage::U32, Storage::I32][usize::from(signed)],

			// The 32-bit integer proxies copy a float alike, and a linker may fold
			// them together.
			PropKind::Float if proxies.float || proxies.int32 => Storage::F32,

			PropKind::Vector if proxies.vector => Storage::Vector,
			_ => Storage::Unknown,
		}
	}
}

/// How a networked variable is stored in its entity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Storage {
	/// An 8-bit integer networked as signed.
	I8,

	/// An 8-bit integer networked with [`PropFlags::UNSIGNED`].
	U8,

	/// A 16-bit integer networked as signed.
	I16,

	/// A 16-bit integer networked with [`PropFlags::UNSIGNED`].
	U16,

	/// A 32-bit integer networked as signed.
	I32,

	/// A 32-bit integer networked with [`PropFlags::UNSIGNED`].
	U32,

	/// A 32-bit float.
	F32,

	/// Three floats, as a `Vector` or `QAngle`.
	Vector,

	/// Stored in a way this crate cannot verify, because the property has no
	/// send proxy or one this crate does not recognize, such as a custom or
	/// string proxy. If it has a proxy, [`NetProp::value`] can still read what
	/// clients see.
	Unknown,
}

impl Storage {
	/// Whether a variable stored as `self` can be accessed as `other`.
	///
	/// Integers only need the same width: signedness comes from
	/// `SPROP_UNSIGNED`, which describes how a value is networked, and the game
	/// sends many `int` variables unsigned.
	pub const fn is_compatible(self, other: Self) -> bool {
		matches!(
			(self, other),
			(Self::I8 | Self::U8, Self::I8 | Self::U8)
				| (Self::I16 | Self::U16, Self::I16 | Self::U16)
				| (Self::I32 | Self::U32, Self::I32 | Self::U32)
				| (Self::F32, Self::F32)
				| (Self::Vector, Self::Vector)
		)
	}
}

impl Display for Storage {
	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
		f.write_str(match self {
			Self::I8 => "i8",
			Self::U8 => "u8",
			Self::I16 => "i16",
			Self::U16 => "u16",
			Self::I32 => "i32",
			Self::U32 => "u32",
			Self::F32 => "f32",
			Self::Vector => "a vector",
			Self::Unknown => "an unknown type",
		})
	}
}

impl<'s> SendProp<'s> {
	/// # Safety
	///
	/// `raw` must be a property of one of the game DLL's send tables.
	pub(crate) const unsafe fn from_raw(raw: NonNull<sys::SendProp>) -> Self {
		Self {
			raw,
			_scope: PhantomData,
			_not_thread_safe: PhantomData,
		}
	}

	/// The property describing each element of a [`PropKind::Array`] property.
	#[doc(alias("GetArrayProp"))]
	pub fn array_prop(self) -> Option<SendProp<'s>> {
		// SAFETY: The array's element property precedes it in the same table.
		NonNull::new(prop_field!(self, m_pArrayProp))
			.map(|prop| unsafe { SendProp::from_raw(prop) })
	}

	/// Returns the native pointer for low-level interop.
	pub const fn as_ptr(self) -> *mut sys::SendProp {
		self.raw.as_ptr()
	}

	/// The number of bits the value is encoded with.
	#[doc(alias("m_nBits"))]
	pub fn bits(self) -> c_int {
		prop_field!(self, m_nBits)
	}

	/// The nested table of a [`PropKind::DataTable`] property.
	#[doc(alias("GetDataTable"))]
	pub fn data_table(self) -> Option<SendTable<'s>> {
		// SAFETY: Send tables are statics of the game DLL.
		NonNull::new(prop_field!(self, m_pDataTable))
			.map(|table| unsafe { SendTable::from_raw(table) })
	}

	/// The number of elements of a [`PropKind::Array`] property.
	#[doc(alias("GetNumElements"))]
	pub fn element_count(self) -> c_int {
		prop_field!(self, m_nElements)
	}

	/// Bytes between consecutive elements of a [`PropKind::Array`] property.
	#[doc(alias("GetElementStride"))]
	pub fn element_stride(self) -> c_int {
		prop_field!(self, m_ElementStride)
	}

	/// The table an [exclude](PropFlags::EXCLUDE) property excludes a property from.
	#[doc(alias("GetExcludeDTName"))]
	pub fn exclude_table_name(self) -> Option<&'s CStr> {
		if !self.flags().contains(PropFlags::EXCLUDE) {
			return None;
		}

		let table = prop_field!(self, m_pExcludeDTName);

		// SAFETY: As for `name`.
		unsafe { borrow_cstr(table) }
	}

	/// The property's `SPROP_*` flags, including those without a constant.
	#[doc(alias("GetFlags"))]
	pub fn flags(self) -> PropFlags {
		PropFlags::from_bits_retain(prop_field!(self, m_Flags))
	}

	/// The highest value a float is encoded to.
	#[doc(alias("m_fHighValue"))]
	pub fn high_value(self) -> f32 {
		prop_field!(self, m_fHighValue)
	}

	/// The type the property is networked as.
	#[doc(alias("GetType"))]
	pub fn kind(self) -> PropKind {
		PropKind::from_raw(prop_field!(self, m_Type))
	}

	/// The lowest value a float is encoded to.
	#[doc(alias("m_fLowValue"))]
	pub fn low_value(self) -> f32 {
		prop_field!(self, m_fLowValue)
	}

	/// The variable's name, such as `m_iHealth`.
	#[doc(alias("GetName"))]
	pub fn name(self) -> &'s CStr {
		let name = prop_field!(self, m_pVarName);

		// SAFETY: Names are string literals of the game DLL.
		unsafe { borrow_cstr(name) }.unwrap_or_default()
	}

	/// Bytes from the start of the structure the property's table describes.
	#[doc(alias("GetOffset"))]
	pub fn offset(self) -> c_int {
		prop_field!(self, m_Offset)
	}
}

/// Keeps [`NetVar`] from being implemented outside this crate.
mod sealed {
	pub trait Sealed {}
}

/// Implements [`NetVar`] for primitive types, which are read and written as is.
macro_rules! primitive_net_vars {
	($($Type:ty => $Storage:ident),* $(,)?) => {$(
		impl sealed::Sealed for $Type {}

		impl NetVar for $Type {
			const STORAGE: Storage = Storage::$Storage;

			unsafe fn read(source: *const u8) -> Self {
				// SAFETY: The caller upholds the contract. Every bit pattern is valid.
				unsafe { source.cast::<Self>().read_unaligned() }
			}

			unsafe fn write(self, destination: *mut u8) {
				// SAFETY: The caller upholds the contract.
				unsafe { destination.cast::<Self>().write_unaligned(self) }
			}
		}
	)*};
}

primitive_net_vars! {
	i8 => I8,
	u8 => U8,
	i16 => I16,
	u16 => U16,
	i32 => I32,
	u32 => U32,
	f32 => F32,
}

/// A networked variable resolved by name to where it lives in the entities of
/// one class and every class deriving from it.
///
/// Resolve one with
/// [`ServerGameDll::net_prop`](crate::interfaces::ServerGameDll::net_prop).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NetProp<'s> {
	prop: SendProp<'s>,
	class_table: SendTable<'s>,
	proxies: StandardSendProxies<'s>,
	/// Offset of the structure containing the variable, which proxies receive.
	struct_offset: usize,
	/// Offset of the variable.
	offset: usize,
	/// The element index proxies receive.
	element: c_int,
}

impl<'s> NetProp<'s> {
	/// Finds the first variable named `name` in `table` or the tables nested
	/// within it, depth first, as SourceMod does.
	pub(crate) fn resolve(
		table: SendTable<'s>,
		name: &CStr,
		proxies: StandardSendProxies<'s>,
	) -> Result<Self, NetPropError> {
		struct Found<'s> {
			prop: SendProp<'s>,
			struct_offset: usize,
			offset: c_int,
			relocated_by: Option<SendProp<'s>>,
		}

		fn search<'s>(
			table: SendTable<'s>,
			name: &CStr,
			base: usize,
			relocated_by: Option<SendProp<'s>>,
			proxies: StandardSendProxies<'s>,
			depth: usize,
		) -> Option<Found<'s>> {
			if depth > MAX_TABLE_DEPTH {
				return None;
			}

			for prop in table.props() {
				// Array element templates are found through their array, and
				// exclude properties only name variables of other tables.
				if prop.flags().contains(PropFlags::INSIDE_ARRAY)
					|| prop.flags().contains(PropFlags::EXCLUDE)
				{
					continue;
				}

				if prop.name() == name {
					return Some(Found {
						prop,
						struct_offset: base,
						offset: prop.offset(),
						relocated_by,
					});
				}

				if prop.kind() == PropKind::DataTable
					&& let Some(nested) = prop.data_table()
					&& let Some(nested_base) = usize::try_from(prop.offset())
						.ok()
						.and_then(|offset| base.checked_add(offset))
				{
					let relocated_by =
						relocated_by.or_else(|| (!proxies.is_direct(prop)).then_some(prop));

					if let Some(found) =
						search(nested, name, nested_base, relocated_by, proxies, depth + 1)
					{
						return Some(found);
					}
				}
			}

			None
		}

		let Found {
			prop,
			struct_offset,
			offset,
			relocated_by,
		} = search(table, name, 0, None, proxies, 0).ok_or_else(|| NetPropError::NotFound {
			table: lossy(table.name()),
			name: lossy(name),
		})?;

		if let Some(relocated_by) = relocated_by {
			return Err(NetPropError::Relocated {
				name: lossy(name),
				table: lossy(relocated_by.name()),
			});
		}

		let offset = usize::try_from(offset)
			.ok()
			.and_then(|offset| struct_offset.checked_add(offset))
			.ok_or_else(|| NetPropError::InvalidOffset {
				name: lossy(name),
				offset,
			})?;

		Ok(Self {
			prop,
			class_table: table,
			proxies,
			struct_offset,
			offset,
			element: 0,
		})
	}

	/// Checks that the variable's offset holds for `entity`, returning its edict.
	fn check_entity<'e>(self, entity: Entity<'e>) -> Result<Edict<'e>, NetPropError> {
		let not_networked = || NetPropError::NotNetworked {
			class_name: lossy(entity.class_name()),
		};

		let edict = entity.edict().ok_or_else(not_networked)?;
		let table = entity
			.server_class()
			.and_then(ServerClass::table)
			.ok_or_else(not_networked)?;

		if !table.derives_from(self.class_table) {
			return Err(NetPropError::ClassMismatch {
				name: lossy(self.prop.name()),
				expected: lossy(self.class_table.name()),
				class_name: lossy(entity.class_name()),
				found: lossy(table.name()),
			});
		}

		Ok(edict)
	}

	/// Checks that the variable is an entity handle, as `SendPropEHandle`
	/// declares them: a [`PropKind::Int`] of `NUM_NETWORKED_EHANDLE_BITS`
	/// unsigned bits, whose proxy is not one of the standard integer proxies,
	/// which would make it a plain integer.
	fn check_handle(self) -> Result<(), NetPropError> {
		let is_handle = self.prop.kind() == PropKind::Int
			&& self.prop.flags().contains(PropFlags::UNSIGNED)
			&& u32::try_from(self.prop.bits()) == Ok(NUM_NETWORKED_EHANDLE_BITS)
			&& self.storage() == Storage::Unknown;

		if is_handle {
			Ok(())
		} else {
			Err(NetPropError::NotAHandle {
				name: lossy(self.prop.name()),
			})
		}
	}

	/// Checks that the variable is a single value stored compatibly with `T`.
	fn check_storage<T: NetVar>(self) -> Result<(), NetPropError> {
		let name = || lossy(self.prop.name());

		match self.prop.kind() {
			kind @ (PropKind::Array | PropKind::DataTable) => {
				Err(NetPropError::NotAValue { name: name(), kind })
			}

			_ => match self.storage() {
				Storage::Unknown => Err(NetPropError::UnknownStorage { name: name() }),
				storage if storage.is_compatible(T::STORAGE) => Ok(()),

				storage => Err(NetPropError::TypeMismatch {
					name: name(),
					storage,
					requested: type_name::<T>(),
				}),
			},
		}
	}

	/// The table of the class the variable was resolved in.
	pub const fn class_table(self) -> SendTable<'s> {
		self.class_table
	}

	/// An element of an array, or a variable of a nested table, which
	/// `SendPropArray3` uses for arrays.
	///
	/// Fails if the property is neither, if `index` is out of range, if a
	/// nested table's proxy relocates its data, or if the element's offset or
	/// the array's stride is [invalid](NetPropError::InvalidOffset).
	pub fn element(self, index: usize) -> Result<Self, NetPropError> {
		let name = || lossy(self.prop.name());
		let out_of_range = |len| NetPropError::ElementOutOfRange {
			name: name(),
			index,
			len,
		};

		match self.prop.kind() {
			PropKind::Array => {
				let len = usize::try_from(self.prop.element_count()).unwrap_or(0);
				let element = self
					.prop
					.array_prop()
					.filter(|_| index < len)
					.ok_or_else(|| out_of_range(len))?;
				let stride = usize::try_from(self.prop.element_stride()).ok();
				let offset = usize::try_from(element.offset())
					.ok()
					.zip(stride)
					.and_then(|(offset, stride)| {
						self.struct_offset
							.checked_add(offset)?
							.checked_add(stride.checked_mul(index)?)
					})
					.ok_or_else(|| NetPropError::InvalidOffset {
						name: name(),
						offset: element.offset(),
					})?;

				Ok(Self {
					prop: element,
					offset,
					element: c_int::try_from(index).map_err(|_| out_of_range(len))?,
					..self
				})
			}

			PropKind::DataTable => {
				let table = self.prop.data_table().ok_or_else(|| out_of_range(0))?;
				let element = table.prop(index).ok_or_else(|| out_of_range(table.len()))?;

				if !self.proxies.is_direct(self.prop) {
					return Err(NetPropError::Relocated {
						name: lossy(element.name()),
						table: name(),
					});
				}

				let offset = usize::try_from(element.offset())
					.ok()
					.and_then(|offset| self.offset.checked_add(offset))
					.ok_or_else(|| NetPropError::InvalidOffset {
						name: lossy(element.name()),
						offset: element.offset(),
					})?;

				Ok(Self {
					prop: element,
					struct_offset: self.offset,
					offset,
					element: 0,
					..self
				})
			}

			kind => Err(NetPropError::NotAnArray { name: name(), kind }),
		}
	}

	/// The number of elements of an array, or of variables in a nested table.
	pub fn element_count(self) -> Option<usize> {
		match self.prop.kind() {
			PropKind::Array => usize::try_from(self.prop.element_count()).ok(),
			PropKind::DataTable => self.prop.data_table().map(SendTable::len),
			_ => None,
		}
	}

	/// Reads the variable from an entity, as stored.
	///
	/// Fails if the entity is not networked or its class does not derive from
	/// the one the variable was resolved in, or if the variable is not a single
	/// value stored [compatibly](Storage::is_compatible) with `T`.
	pub fn get<T: NetVar>(self, entity: Entity<'_>) -> Result<T, NetPropError> {
		self.check_entity(entity)?;
		self.check_storage::<T>()?;

		// SAFETY: The entity's class derives from the class the offset was
		// resolved in, and the variable's storage is compatible with `T`. Entities are zeroed
		// when allocated, so every byte is initialized.
		Ok(unsafe { T::read(entity.as_ptr().cast::<u8>().add(self.offset)) })
	}

	/// Reads the variable, as stored, from the structure at `base`, such as an
	/// object a nested table's relocating proxy gave.
	///
	/// Fails if the variable is not a single value stored
	/// [compatibly](Storage::is_compatible) with `T`.
	///
	/// # Safety
	///
	/// `base` must point to a live, initialized structure laid out as the table
	/// the variable was resolved in describes.
	#[cfg(feature = "tf2")]
	pub(crate) unsafe fn get_at<T: NetVar>(self, base: NonNull<c_void>) -> Result<T, NetPropError> {
		self.check_storage::<T>()?;

		// SAFETY: The structure is laid out as the variable's table describes, as
		// the caller promises, and the variable's storage is compatible with `T`.
		Ok(unsafe { T::read(base.as_ptr().cast::<u8>().add(self.offset)) })
	}

	/// Reads an entity handle variable (`CHandle`), as stored, from the
	/// structure at `base`, as [`get_handle`](Self::get_handle) reads one from an
	/// entity.
	///
	/// Fails with [`NetPropError::NotAHandle`] as [`get_handle`](Self::get_handle)
	/// does.
	///
	/// # Safety
	///
	/// As for [`get_at`](Self::get_at).
	#[cfg(feature = "tf2")]
	pub(crate) unsafe fn get_handle_at(
		self,
		base: NonNull<c_void>,
	) -> Result<EntityHandle, NetPropError> {
		self.check_handle()?;

		// SAFETY: The structure is laid out as the variable's table describes, as
		// the caller promises, and the variable is a handle, whose `CBaseHandle`
		// holds only its raw value, read without forming a reference or assuming
		// alignment.
		Ok(EntityHandle::from_raw(unsafe {
			base.as_ptr()
				.cast::<u8>()
				.add(self.offset)
				.cast::<u32>()
				.read_unaligned()
		}))
	}

	/// Reads an entity handle variable (`CHandle`) from an entity, as stored,
	/// with its full serial number, unlike the value clients receive, which
	/// [`value`](Self::value) reads.
	///
	/// Fails if the entity is not networked or its class does not derive from
	/// the one the variable was resolved in, or with
	/// [`NetPropError::NotAHandle`] if the property is not declared as
	/// `SendPropEHandle` declares handles: an unsigned integer of 21 bits
	/// (`NUM_NETWORKED_EHANDLE_BITS`), sent through a proxy other than the
	/// standard integer ones, such as `SendProxy_EHandleToInt`.
	#[doc(alias("SendPropEHandle", "CHandle", "EHANDLE"))]
	pub fn get_handle(self, entity: Entity<'_>) -> Result<EntityHandle, NetPropError> {
		self.check_entity(entity)?;
		self.check_handle()?;

		// SAFETY: The entity's class derives from the class the offset was
		// resolved in, and the variable is a handle, whose `CBaseHandle` holds
		// only its raw value, read without forming a reference or assuming
		// alignment. Entities are zeroed when allocated, so every byte is
		// initialized.
		Ok(EntityHandle::from_raw(unsafe {
			entity
				.as_ptr()
				.cast::<u8>()
				.add(self.offset)
				.cast::<u32>()
				.read_unaligned()
		}))
	}

	/// Bytes from the start of the entity to the variable.
	pub const fn offset(self) -> usize {
		self.offset
	}

	/// The property describing the variable.
	pub const fn prop(self) -> SendProp<'s> {
		self.prop
	}

	/// Writes the variable of an entity, and records the change so the engine
	/// sends it to clients.
	///
	/// Fails, without writing, as [`get`](Self::get) does.
	///
	/// # Safety
	///
	/// The game must accept `value` for this variable. Game code trusts its
	/// networked variables, such as a player's class or team, to hold values
	/// it could have assigned itself, and may index arrays with them.
	pub unsafe fn set<T: NetVar>(
		self,
		engine: ValveEngine<'_>,
		entity: Entity<'_>,
		value: T,
	) -> Result<(), NetPropError> {
		let edict = self.check_entity(entity)?;
		self.check_storage::<T>()?;

		// SAFETY: As for `get`. The game writes its variables the same way,
		// through its own pointers, on the main thread.
		unsafe { value.write(entity.as_ptr().cast::<u8>().add(self.offset)) };

		match u16::try_from(self.offset) {
			Ok(offset) => edict.state_changed(engine, offset),
			Err(_) => edict.full_state_changed(engine),
		}

		Ok(())
	}

	/// Writes the variable, as stored, to the structure at `base`, such as an
	/// object a nested table's relocating proxy gave, without recording the
	/// change for clients.
	///
	/// Fails, without writing, as [`get_at`](Self::get_at) does.
	///
	/// # Safety
	///
	/// `base` must point to a live structure laid out as the table the variable
	/// was resolved in describes, and the game must accept `value` for the
	/// variable, as for [`set`](Self::set).
	#[cfg(feature = "tf2")]
	pub(crate) unsafe fn set_at<T: NetVar>(
		self,
		base: NonNull<c_void>,
		value: T,
	) -> Result<(), NetPropError> {
		self.check_storage::<T>()?;

		// SAFETY: The structure is laid out as the variable's table describes, as
		// the caller promises, and the variable's storage is compatible with `T`.
		// The game writes its variables the same way, through its own pointers, on
		// the main thread.
		unsafe { value.write(base.as_ptr().cast::<u8>().add(self.offset)) };

		Ok(())
	}

	/// Writes an entity handle variable (`CHandle`) of an entity, and records
	/// the change so the engine sends it to clients.
	///
	/// This assigns the member, as the game's network variables do, without
	/// what the game's setter of it may also do, such as `SetOwnerEntity`
	/// rechecking collision rules for `m_hOwnerEntity`, which
	/// [`Entity::set_owner`] calls.
	///
	/// Fails, without writing, as [`get_handle`](Self::get_handle) does, or
	/// with [`NetPropError::HandleOutOfRange`] for a handle whose slot lies
	/// past the entity list, which the game would index with it.
	///
	/// # Safety
	///
	/// The game must accept the entity `handle` refers to, if any, for this
	/// variable. Game code may cast what a handle refers to unchecked, as
	/// TF2's client casts a player's `m_hRagdoll` to its ragdoll class.
	#[doc(alias("SendPropEHandle", "CHandle", "EHANDLE"))]
	pub unsafe fn set_handle(
		self,
		engine: ValveEngine<'_>,
		entity: Entity<'_>,
		handle: EntityHandle,
	) -> Result<(), NetPropError> {
		let edict = self.check_entity(entity)?;
		self.check_handle()?;

		if handle
			.index()
			.is_some_and(|index| index >= EntityHandle::SLOTS)
		{
			return Err(NetPropError::HandleOutOfRange {
				name: lossy(self.prop.name()),
				handle,
			});
		}

		// SAFETY: As for `get_handle`. The game writes its variables the same
		// way, through its own pointers, on the main thread.
		unsafe {
			entity
				.as_ptr()
				.cast::<u8>()
				.add(self.offset)
				.cast::<u32>()
				.write_unaligned(handle.to_raw())
		};

		match u16::try_from(self.offset) {
			Ok(offset) => edict.state_changed(engine, offset),
			Err(_) => edict.full_state_changed(engine),
		}

		Ok(())
	}

	/// How the variable is stored.
	pub fn storage(self) -> Storage {
		self.proxies.storage(self.prop)
	}

	/// Reads the variable from an entity as clients receive it, by calling
	/// its send proxy as the engine does when networking the entity.
	///
	/// This works for any scalar variable, including those whose storage is
	/// [unknown](Storage::Unknown), such as entity handles. It fails if the
	/// entity is not networked or its class does not derive from the one the
	/// variable was resolved in, or if the property is not a scalar or has no
	/// proxy.
	#[doc(alias("SendVarProxyFn"))]
	pub fn value(self, entity: Entity<'_>) -> Result<NetValue, NetPropError> {
		let edict = self.check_entity(entity)?;
		let kind = self.prop.kind();

		if matches!(
			kind,
			PropKind::Array | PropKind::DataTable | PropKind::Unknown(_)
		) {
			return Err(NetPropError::NotAValue {
				name: lossy(self.prop.name()),
				kind,
			});
		}

		let base = entity.as_ptr().cast::<u8>();

		// SAFETY: The property is one of the game DLL's, and the proxy is called
		// on the main thread with the arguments the engine passes: the
		// structure containing the variable, the variable, its element, and
		// the entity's index. The entity's class was checked, so both
		// addresses lie within the live entity.
		let value = unsafe {
			call_var_proxy(
				self.prop.as_ptr(),
				base.add(self.struct_offset).cast::<c_void>(),
				base.add(self.offset).cast::<c_void>(),
				self.element,
				edict.index(),
			)
		}
		.ok_or_else(|| NetPropError::NoProxy {
			name: lossy(self.prop.name()),
		})?
		.__bindgen_anon_1;

		// SAFETY: Proxies fill in the union member matching the property type.
		Ok(unsafe {
			match kind {
				PropKind::Int => NetValue::Int(value.m_Int),
				PropKind::Float => NetValue::Float(value.m_Float),

				PropKind::Vector => NetValue::Vector(Vector::new(
					value.m_Vector[0],
					value.m_Vector[1],
					value.m_Vector[2],
				)),

				PropKind::VectorXY => {
					NetValue::VectorXY(Vec2::new(value.m_Vector[0], value.m_Vector[1]))
				}

				PropKind::String => {
					NetValue::String(copy_cstr(value.m_pString).unwrap_or_default())
				}

				PropKind::Array | PropKind::DataTable | PropKind::Unknown(_) => unreachable!(),
			}
		})
	}
}

/// Why a networked variable could not be found or accessed.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum NetPropError {
	/// The server class has no table of networked variables.
	#[error("server class `{class}` has no send table")]
	NoTable {
		/// The class's network name, such as `CTFPlayer`.
		class: String,
	},

	/// [`ServerGameDll::standard_send_proxies`] found none, so how variables
	/// are stored cannot be recognized.
	///
	/// [`ServerGameDll::standard_send_proxies`]: crate::interfaces::ServerGameDll::standard_send_proxies
	#[error("the game DLL provides no standard send proxies to recognize storage by")]
	NoStandardProxies,

	/// No variable has the name in the table or the tables nested within it.
	#[error("`{table}` has no networked variable named `{name}`")]
	NotFound {
		/// The name of the table searched.
		table: String,

		/// The name looked up.
		name: String,
	},

	/// The variable is inside a nested table whose proxy relocates its data,
	/// so where it lives in the entity is unknown.
	#[error(
		"`{name}` is inside `{table}`, whose send proxy relocates its data, so its address is unknown"
	)]
	Relocated {
		/// The variable's name.
		name: String,

		/// The name of the [`PropKind::DataTable`] property whose proxy
		/// relocates the data.
		table: String,
	},

	/// The variable's offset, or its array's stride, is negative, or its
	/// position in the entity overflows.
	#[error("`{name}` has an invalid offset of {offset} bytes")]
	InvalidOffset {
		/// The variable's name.
		name: String,

		/// The offset the property gives, in bytes.
		offset: c_int,
	},

	/// [`NetProp::get_handle`] or [`NetProp::set_handle`] was called on a
	/// property that is not declared as an entity handle.
	#[error("`{name}` is not networked as an entity handle")]
	NotAHandle {
		/// The property's name.
		name: String,
	},

	/// [`NetProp::set_handle`] was given a handle whose slot lies past the
	/// entity list.
	#[error("`{name}` cannot hold handle {handle}, whose slot lies past the entity list")]
	HandleOutOfRange {
		/// The variable's name.
		name: String,

		/// The handle refused.
		handle: EntityHandle,
	},

	/// The property is an array, a nested table, or of a type this crate does
	/// not know, so it has no single value to access.
	#[error("`{name}` is {kind}, which has no single value")]
	NotAValue {
		/// The property's name.
		name: String,

		/// The type the property is networked as.
		kind: PropKind,
	},

	/// [`NetProp::element`] was called on a property that is neither an array
	/// nor a nested table.
	#[error("`{name}` is {kind}, which has no elements")]
	NotAnArray {
		/// The property's name.
		name: String,

		/// The type the property is networked as.
		kind: PropKind,
	},

	/// [`NetProp::element`] was given an index past the last element.
	#[error("`{name}` has {len} elements, so it has no element {index}")]
	ElementOutOfRange {
		/// The name of the array or nested table property.
		name: String,

		/// The index requested.
		index: usize,

		/// The number of elements.
		len: usize,
	},

	/// The variable is not stored [compatibly](Storage::is_compatible) with
	/// the type requested.
	#[error("`{name}` is stored as {storage}, not {requested}")]
	TypeMismatch {
		/// The variable's name.
		name: String,

		/// How the variable is stored.
		storage: Storage,

		/// The name of the type requested, from [`type_name`].
		requested: &'static str,
	},

	/// The variable's send proxy is missing or is not one of the standard
	/// proxies this crate recognizes, so how it is stored is
	/// [unknown](Storage::Unknown). [`NetProp::value`] can still read it if it
	/// has a proxy.
	#[error(
		"`{name}` has a custom send proxy, so how it is stored is unknown; read it with `NetProp::value` instead"
	)]
	UnknownStorage {
		/// The variable's name.
		name: String,
	},

	/// The property has no send proxy to read its value with.
	#[error("`{name}` has no send proxy")]
	NoProxy {
		/// The property's name.
		name: String,
	},

	/// The entity has no edict, server class, or send table.
	#[error("`{class_name}` is not networked")]
	NotNetworked {
		/// The entity's classname.
		class_name: String,
	},

	/// The entity's class does not derive from the one the variable was
	/// resolved in, so the variable's offset does not hold for it.
	#[error(
		"`{name}` belongs to `{expected}`, which `{class_name}`'s table `{found}` does not derive from"
	)]
	ClassMismatch {
		/// The variable's name.
		name: String,

		/// The name of the table the variable was resolved in.
		expected: String,

		/// The entity's classname.
		class_name: String,

		/// The name of the entity's send table.
		found: String,
	},
}

impl NetVar for QAngle {
	const STORAGE: Storage = Storage::Vector;

	unsafe fn read(source: *const u8) -> Self {
		// SAFETY: The caller upholds the contract.
		unsafe { source.cast::<sys::QAngle>().read_unaligned() }.into()
	}

	unsafe fn write(self, destination: *mut u8) {
		// SAFETY: The caller upholds the contract.
		unsafe {
			destination
				.cast::<sys::QAngle>()
				.write_unaligned(self.into())
		}
	}
}

impl sealed::Sealed for QAngle {}

impl NetVar for Vector {
	const STORAGE: Storage = Storage::Vector;

	unsafe fn read(source: *const u8) -> Self {
		// SAFETY: The caller upholds the contract.
		unsafe { source.cast::<sys::Vector>().read_unaligned() }.into()
	}

	unsafe fn write(self, destination: *mut u8) {
		// SAFETY: The caller upholds the contract.
		unsafe {
			destination
				.cast::<sys::Vector>()
				.write_unaligned(self.into())
		}
	}
}

impl sealed::Sealed for Vector {}

impl NetVar for bool {
	const STORAGE: Storage = Storage::U8;

	unsafe fn read(source: *const u8) -> Self {
		// SAFETY: The caller upholds the contract. The byte is read as an
		// integer, since the game may store any value in it.
		unsafe { source.read() != 0 }
	}

	unsafe fn write(self, destination: *mut u8) {
		// SAFETY: The caller upholds the contract.
		unsafe { destination.write(u8::from(self)) }
	}
}

impl sealed::Sealed for bool {}

/// Copies a name into an error, replacing invalid UTF-8.
fn lossy(string: &CStr) -> String {
	string.to_string_lossy().into_owned()
}