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
//! Tests of `crate::tf2::entity`: the native members of `CBaseEntity`,
//! called on mock entities whose script class records each call.

use super::*;
use crate::test_support::entities::{MockEntity, base_entity_fields, set_datamap, state_fields};
use crate::test_support::leak;
use crate::test_support::server::{mock_server, null_server};

use crate::test_support::tf2::script_binding::{
	class_description, member_binding, set_script_description,
};

use crate::tf2::damage::CUSTOM_DAMAGE_PLASMA;
use sdk_raw::entities::EFL_KILLME;
use sdk_raw::test_support::entities::{data_map, field};
use sdk_raw::tf2::script_binding::{FLOAT, HANDLE, INT, QANGLE, VECTOR};
use std::cell::{Cell, RefCell};
use std::ffi::{CString, c_char, c_void};

/// A call of a native member: the entity, the member's name, and its
/// arguments.
type Call = (*mut c_void, CString, Vec<Argument>);

/// Where entities hold `m_hScriptInstance`, just before `m_iszScriptId`.
///
/// The crate finds the instance once per process, so every entity of its
/// tests holds it here, as `tests/tf2/script_instances.rs`'s do.
const INSTANCE_OFFSET: usize = 72;

/// The native members the mock entities' script class declares: each one's
/// name and parameter types. All return nothing, and others are missing.
const MEMBERS: [(&CStr, &[sys::ScriptDataType_t]); 14] = [
	(c"AddSolidFlags", &[INT]),
	(c"ApplyAbsVelocityImpulse", &[VECTOR]),
	(c"ApplyLocalAngularVelocityImpulse", &[VECTOR]),
	(c"RemoveSolidFlags", &[INT]),
	(c"SetAbsAngles", &[QANGLE]),
	(c"SetAbsOrigin", &[VECTOR]),
	(c"SetAbsVelocity", &[VECTOR]),
	(c"SetCollisionGroup", &[INT]),
	(c"SetPhysAngularVelocity", &[VECTOR]),
	(c"SetPhysVelocity", &[VECTOR]),
	(c"SetSize", &[VECTOR, VECTOR]),
	(c"SetSolid", &[INT]),
	(c"SetSolidFlags", &[INT]),
	(
		c"TakeDamageCustom",
		&[HANDLE, HANDLE, HANDLE, VECTOR, VECTOR, FLOAT, INT, INT],
	),
];

/// Where entities hold `m_iszScriptId`, as their datamap declares.
const SCRIPT_ID_OFFSET: usize = 80;

/// An argument a native member received.
#[derive(Debug, Clone, PartialEq)]
enum Argument {
	Angles([f32; 3]),
	Float(f32),
	Handle(sys::HSCRIPT),
	Int(c_int),
	Vector([f32; 3]),
}

thread_local! {
	/// Whether the native members' adapters accept their calls.
	static ACCEPTS: Cell<bool> = const { Cell::new(true) };

	/// Each call of a native member, in order.
	static CALLS: RefCell<Vec<Call>> = const { RefCell::new(Vec::new()) };
}

#[test]
fn damage_always_has_an_attacker_and_an_inflictor() {
	let mut target = MockEntity::new(1);
	let mut soldier = MockEntity::new(2);
	let mut rocket = MockEntity::new(3);
	let mut launcher = MockEntity::new(4);
	let instances = [&mut target, &mut soldier, &mut rocket, &mut launcher].map(give_instance);
	let [
		target_instance,
		soldier_instance,
		rocket_instance,
		launcher_instance,
	] = instances;
	let object = target.as_ptr().cast::<c_void>();

	set_maps();
	describe();

	let scope = ();
	let server = mock_server(&scope);
	let soldier_entity = soldier.entity();
	let rocket_entity = rocket.entity();
	let launcher_entity = launcher.entity();
	let entity = TfEntity::new(server, target.entity()).unwrap();

	// With no one named, the entity damages itself.
	entity
		.take_damage(Damage::new(25.0, DamageType::BULLET))
		.unwrap();
	// An attacker inflicts its own damage, and an inflictor deals its own.
	entity
		.take_damage(Damage::new(50.0, DamageType::CLUB).attacker(soldier_entity))
		.unwrap();
	entity
		.take_damage(
			Damage::new(90.0, DamageType::BLAST)
				.inflictor(rocket_entity)
				.weapon(launcher_entity)
				.force(Vector::new(0.0, 0.0, 400.0))
				.position(Vector::new(1.0, 2.0, 3.0))
				.custom(CUSTOM_DAMAGE_PLASMA),
		)
		.unwrap();
	entity
		.take_damage(
			Damage::new(-5.0, DamageType::empty())
				.attacker(soldier_entity)
				.inflictor(rocket_entity),
		)
		.unwrap();

	let damage =
		|inflictor, attacker, weapon, force, position, amount, kinds: DamageType, custom| {
			(
				object,
				c"TakeDamageCustom".to_owned(),
				vec![
					Argument::Handle(inflictor),
					Argument::Handle(attacker),
					Argument::Handle(weapon),
					Argument::Vector(force),
					Argument::Vector(position),
					Argument::Float(amount),
					Argument::Int(kinds.bits() as c_int),
					Argument::Int(custom),
				],
			)
		};

	let zero = [0.0; 3];

	assert_eq!(
		CALLS.take(),
		[
			damage(
				target_instance,
				target_instance,
				null_mut(),
				zero,
				zero,
				25.0,
				DamageType::BULLET,
				0,
			),
			damage(
				soldier_instance,
				soldier_instance,
				null_mut(),
				zero,
				zero,
				50.0,
				DamageType::CLUB,
				0,
			),
			damage(
				rocket_instance,
				rocket_instance,
				launcher_instance,
				[0.0, 0.0, 400.0],
				[1.0, 2.0, 3.0],
				90.0,
				DamageType::BLAST,
				CUSTOM_DAMAGE_PLASMA,
			),
			damage(
				rocket_instance,
				soldier_instance,
				null_mut(),
				zero,
				zero,
				-5.0,
				DamageType::empty(),
				0,
			),
		]
	);

	// The damage must be finite.
	let nan = Vector::new(f32::NAN, 0.0, 0.0);

	for damage in [
		Damage::new(f32::INFINITY, DamageType::GENERIC),
		Damage::new(1.0, DamageType::GENERIC).force(nan),
		Damage::new(1.0, DamageType::GENERIC).position(nan),
	] {
		assert_eq!(entity.take_damage(damage), Err(TfEntityError::NonFinite));
	}

	assert!(CALLS.take().is_empty());
}

#[test]
fn damage_from_entities_marked_for_deletion_is_refused() {
	let mut target = MockEntity::new(1);
	let mut soldier = MockEntity::new(2);

	give_instance(&mut target);
	give_instance(&mut soldier);
	soldier.set_eflags(EFL_KILLME);
	set_maps();
	describe();

	let scope = ();
	let server = mock_server(&scope);
	let soldier = soldier.entity();
	let entity = TfEntity::new(server, target.entity()).unwrap();

	assert_eq!(
		entity.take_damage(Damage::new(1.0, DamageType::GENERIC).attacker(soldier)),
		Err(TfEntityError::ScriptInstance(
			ScriptInstanceError::MarkedForDeletion
		))
	);
	assert!(CALLS.take().is_empty());
}

/// Declares [`MEMBERS`] on the `CBaseEntity` script class that mock entities
/// on this thread return, each called through [`record`], which accepts
/// calls until told otherwise.
fn describe() {
	let bindings = MEMBERS
		.iter()
		.map(|&(name, parameters)| {
			let parameters = parameters.to_vec().leak();
			let mut binding = member_binding(name, binding::VOID, parameters, Some(record));

			binding.m_pFunction.val_0 = name.as_ptr() as isize;
			binding
		})
		.collect::<Vec<_>>();

	set_script_description(leak(class_description(
		c"CBaseEntity",
		bindings.leak(),
		null_mut(),
	)));
	ACCEPTS.set(true);
	CALLS.take();
}

#[test]
fn entities_are_refused_unless_live_on_tf2_with_the_members() {
	let mut mock = MockEntity::new(1);

	set_maps();
	describe();

	let scope = ();
	let server = mock_server(&scope);

	assert!(matches!(
		TfEntity::new(null_server(Game::SourceSdk2013, &scope), mock.entity()),
		Err(TfEntityError::NotTf2)
	));

	ACCEPTS.set(false);
	assert_eq!(
		TfEntity::new(server, mock.entity())
			.unwrap()
			.set_collision_group(TfCollisionGroup::Rockets),
		Err(TfEntityError::Rejected)
	);
	assert_eq!(take_names(), [c"SetCollisionGroup".to_owned()]);

	set_script_description(null_mut());
	assert_eq!(
		TfEntity::new(server, mock.entity())
			.unwrap()
			.add_solid_flags(SolidFlags::NOT_SOLID),
		Err(TfEntityError::UnsupportedMethod)
	);

	describe();
	mock.set_eflags(EFL_KILLME);

	let entity = TfEntity::new(server, mock.entity()).unwrap();

	assert_eq!(
		entity.set_solid_flags(SolidFlags::empty()),
		Err(TfEntityError::MarkedForDeletion)
	);
	assert_eq!(
		entity.take_damage(Damage::new(1.0, DamageType::GENERIC)),
		Err(TfEntityError::MarkedForDeletion)
	);
	assert!(CALLS.take().is_empty());
}

/// Gives a mock entity a script instance, which stands for it in native
/// members' arguments, and returns it.
fn give_instance(mock: &mut MockEntity) -> sys::HSCRIPT {
	let instance = leak(0_u8).cast::<sys::HSCRIPT__>();

	// SAFETY: The handle lies within the mock's 64 words, aligned for it.
	unsafe {
		mock.as_ptr()
			.byte_add(INSTANCE_OFFSET)
			.cast::<sys::HSCRIPT>()
			.write(instance);
	}

	instance
}

#[test]
fn members_receive_their_arguments() {
	let mut mock = MockEntity::new(1);
	let object = mock.as_ptr().cast::<c_void>();

	set_maps();
	describe();

	let scope = ();
	let server = mock_server(&scope);
	let entity = TfEntity::new(server, mock.entity()).unwrap();
	let flags = SolidFlags::NOT_SOLID | SolidFlags::TRIGGER;

	assert_eq!(entity.entity().as_ptr(), object.cast());
	entity.add_solid_flags(flags).unwrap();
	entity.remove_solid_flags(SolidFlags::TRIGGER).unwrap();
	entity.set_solid_flags(SolidFlags::empty()).unwrap();
	entity.set_solid(SolidType::BoundingBox).unwrap();
	entity
		.set_collision_group(TfCollisionGroup::RespawnRooms)
		.unwrap();
	entity.set_abs_origin(Vector::new(4.0, 5.0, 6.0)).unwrap();
	entity
		.set_abs_angles(QAngle {
			pitch: 10.0,
			yaw: 20.0,
			roll: 30.0,
		})
		.unwrap();
	entity.set_abs_velocity(Vector::new(1.0, 2.0, 3.0)).unwrap();
	entity.apply_impulse(Vector::new(0.0, 0.0, 300.0)).unwrap();
	entity
		.apply_angular_impulse(Vector::new(0.0, 90.0, 0.0))
		.unwrap();
	entity
		.set_size(Vector::new(-8.0, -8.0, 0.0), Vector::new(8.0, 8.0, 16.0))
		.unwrap();
	// Empty bounds are ordered.
	entity
		.set_size(Vector::new(1.0, 1.0, 1.0), Vector::new(1.0, 1.0, 1.0))
		.unwrap();

	let call = |name: &CStr, arguments| (object, name.to_owned(), arguments);

	assert_eq!(
		CALLS.take(),
		[
			call(
				c"AddSolidFlags",
				vec![Argument::Int(c_int::from(flags.bits()))]
			),
			call(
				c"RemoveSolidFlags",
				vec![Argument::Int(c_int::from(SolidFlags::TRIGGER.bits()))]
			),
			call(c"SetSolidFlags", vec![Argument::Int(0)]),
			call(
				c"SetSolid",
				vec![Argument::Int(c_int::from(SolidType::BoundingBox.to_raw()))]
			),
			call(
				c"SetCollisionGroup",
				vec![Argument::Int(TfCollisionGroup::RespawnRooms.to_raw())]
			),
			call(c"SetAbsOrigin", vec![Argument::Vector([4.0, 5.0, 6.0])]),
			call(c"SetAbsAngles", vec![Argument::Angles([10.0, 20.0, 30.0])]),
			call(c"SetAbsVelocity", vec![Argument::Vector([1.0, 2.0, 3.0])]),
			call(
				c"ApplyAbsVelocityImpulse",
				vec![Argument::Vector([0.0, 0.0, 300.0])]
			),
			call(
				c"ApplyLocalAngularVelocityImpulse",
				vec![Argument::Vector([0.0, 90.0, 0.0])]
			),
			call(
				c"SetSize",
				vec![
					Argument::Vector([-8.0, -8.0, 0.0]),
					Argument::Vector([8.0, 8.0, 16.0]),
				]
			),
			call(
				c"SetSize",
				vec![
					Argument::Vector([1.0, 1.0, 1.0]),
					Argument::Vector([1.0, 1.0, 1.0]),
				]
			),
		]
	);
}

#[test]
fn physics_needs_a_physics_object() {
	let mut mock = MockEntity::new(1);
	let mut object = 0_u8;

	set_maps();
	describe();

	let scope = ();
	let server = mock_server(&scope);
	let velocity = Vector::new(0.0, 0.0, 100.0);

	// Without one, only entities VPhysics does not move can be pushed.
	{
		let entity = TfEntity::new(server, mock.entity()).unwrap();

		entity.apply_impulse(velocity).unwrap();
		assert_eq!(
			entity.set_physics_velocity(velocity),
			Err(TfEntityError::NoPhysicsObject)
		);
		assert_eq!(
			entity.set_physics_angular_velocity(velocity),
			Err(TfEntityError::NoPhysicsObject)
		);
	}

	mock.state().move_type = MoveType::VPhysics.to_raw();

	{
		let entity = TfEntity::new(server, mock.entity()).unwrap();

		assert_eq!(
			entity.apply_impulse(velocity),
			Err(TfEntityError::NoPhysicsObject)
		);
		assert_eq!(
			entity.apply_angular_impulse(velocity),
			Err(TfEntityError::NoPhysicsObject)
		);
	}

	assert_eq!(take_names(), [c"ApplyAbsVelocityImpulse".to_owned()]);
	mock.state().physics_object = (&raw mut object).cast();

	let entity = TfEntity::new(server, mock.entity()).unwrap();

	entity.apply_impulse(velocity).unwrap();
	entity.apply_angular_impulse(velocity).unwrap();
	entity.set_physics_velocity(velocity).unwrap();
	entity.set_physics_angular_velocity(velocity).unwrap();
	assert_eq!(
		take_names(),
		[
			c"ApplyAbsVelocityImpulse".to_owned(),
			c"ApplyLocalAngularVelocityImpulse".to_owned(),
			c"SetPhysVelocity".to_owned(),
			c"SetPhysAngularVelocity".to_owned(),
		]
	);
}

/// The adapter of every native member, which records the call in [`CALLS`]
/// and returns whether [`ACCEPTS`] says to accept it.
unsafe extern "C" fn record(
	function: sys::ScriptFunctionBindingStorageType_t,
	object: *mut c_void,
	arguments: *mut sys::ScriptVariant_t,
	count: c_int,
	result: *mut sys::ScriptVariant_t,
) -> bool {
	assert!(result.is_null(), "every member returns nothing");

	// SAFETY: `describe` stores each member's name in its binding, and the
	// caller passes `count` arguments of the types the binding declares, whose
	// vectors it keeps alive for the call.
	let (name, arguments) = unsafe {
		(
			CStr::from_ptr(function.val_0 as *const c_char),
			std::slice::from_raw_parts(arguments, usize::try_from(count).unwrap()),
		)
	};

	let arguments = arguments
		.iter()
		.map(|argument| {
			let value = &argument.__bindgen_anon_1;

			// SAFETY: As above, each variant's member is the one its type names.
			unsafe {
				match c_int::from(argument.m_type) {
					FLOAT => Argument::Float(value.m_float),
					HANDLE => Argument::Handle(value.m_hScript),
					INT => Argument::Int(value.m_int),

					VECTOR => {
						let vector = &*value.m_pVector;

						Argument::Vector([vector.x, vector.y, vector.z])
					}

					QANGLE => {
						let angles = &*value.m_pData.cast::<sys::QAngle>();

						Argument::Angles([angles.x, angles.y, angles.z])
					}

					other => panic!("unexpected argument type {other}"),
				}
			}
		})
		.collect();

	CALLS.with_borrow_mut(|calls| calls.push((object, name.to_owned(), arguments)));
	ACCEPTS.get()
}

/// A datamap whose `CBaseEntity` map declares the members mock entities
/// store, and the script ID, for this thread's mock entities.
fn set_maps() {
	let mut fields = Vec::from(base_entity_fields());
	let mut script_id = field(
		c"m_iszScriptId",
		sys::_fieldtypes_FIELD_STRING,
		SCRIPT_ID_OFFSET,
	);

	script_id.fieldSizeInBytes = size_of::<sys::string_t>() as c_int;
	fields.extend(state_fields());
	fields.push(script_id);
	set_datamap(data_map(c"CBaseEntity", fields, null_mut()));
}

/// The names of the members called since the last call of this, in order.
fn take_names() -> Vec<CString> {
	CALLS.take().into_iter().map(|(_, name, _)| name).collect()
}

#[test]
fn values_the_game_mishandles_are_refused() {
	let mut mock = MockEntity::new(1);

	set_maps();
	describe();

	let scope = ();
	let server = mock_server(&scope);
	let entity = TfEntity::new(server, mock.entity()).unwrap();
	let finite = Vector::new(1.0, 2.0, 3.0);

	for value in [
		Vector::new(f32::NAN, 0.0, 0.0),
		Vector::new(0.0, f32::INFINITY, 0.0),
		Vector::new(0.0, 0.0, f32::NEG_INFINITY),
	] {
		let angles = QAngle {
			pitch: value.x,
			yaw: value.y,
			roll: value.z,
		};

		for result in [
			entity.set_abs_origin(value),
			entity.set_abs_angles(angles),
			entity.set_abs_velocity(value),
			entity.apply_impulse(value),
			entity.apply_angular_impulse(value),
			entity.set_physics_velocity(value),
			entity.set_physics_angular_velocity(value),
			entity.set_size(value, finite),
			entity.set_size(Vector::new(-1.0, -2.0, -3.0), value),
		] {
			assert_eq!(result, Err(TfEntityError::NonFinite), "{value:?}");
		}
	}

	// A minimum above its maximum would stop the server.
	for (mins, maxs) in [
		(Vector::new(0.0, 0.0, 1.0), Vector::new(8.0, 8.0, 0.0)),
		(Vector::new(9.0, -8.0, 0.0), Vector::new(8.0, 8.0, 8.0)),
	] {
		assert_eq!(
			entity.set_size(mins, maxs),
			Err(TfEntityError::InvalidBounds)
		);
	}

	assert!(CALLS.take().is_empty());
}