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
|
//! Sources of the player's strategic camera.
use crate::{Engine, MissionControlDeviceTableStatus, StartingCockpit, SurfaceQuery};
use fparkan_render::{LegacyIron3dEulerTransform, RawCameraTransform};
use fparkan_world::{identity_metadata, registration_sequence, transform_state, ObjectHandle};
use std::f32::consts::FRAC_PI_2;
mod vehicle_camera;
/// Horizontal field of view of the strategic camera.
pub const COMMAND_FOV: f32 = 1.04;
/// The object providing the command interface.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommandPost {
/// Hero at their own clan's bunker communicator.
Bunker(ObjectHandle),
/// A vehicle providing a mobile command link.
Warbot(ObjectHandle),
}
/// Returns the source of strategic control available to the player.
#[must_use]
pub fn command_post(engine: &Engine, cockpit: StartingCockpit) -> Option<CommandPost> {
let mission = engine.loaded.as_ref()?;
if let Some(vehicle) = crate::player_vehicle(engine) {
if vehicle.handle != cockpit.handle {
return None;
}
return vehicle_command_link(engine, vehicle.handle)
.then_some(CommandPost::Warbot(vehicle.handle));
}
let owner = identity_metadata(&engine.world, cockpit.handle)
.ok()?
.owner_id?;
let position = transform_state(&engine.world, cockpit.handle)
.ok()?
.position
.map(f32::from_bits);
mission
.object_drafts
.iter()
.enumerate()
.find_map(|(index, draft)| {
let class = draft.unit_dat_header_flags?;
if !matches!(class, 0x8001_0000 | 0x8002_0000 | 0x8004_0000) {
return None;
}
let handle = crate::mission_object_handle(engine, draft.original_id?)?;
if identity_metadata(&engine.world, handle).ok()?.owner_id != Some(owner) {
return None;
}
let pose = transform_state(&engine.world, handle).ok()?;
crate::mission_events::on_communicator(
&mission.mission_assets,
index,
class,
pose,
position,
)
.then_some(CommandPost::Bunker(handle))
})
}
/// Connects the hero to a selected allied mobile command center within reach.
pub fn mobile_command_post(
engine: &Engine,
cockpit: StartingCockpit,
target: ObjectHandle,
) -> Option<CommandPost> {
if crate::player_vehicle(engine).is_some() {
return None;
}
let hero_owner = identity_metadata(&engine.world, cockpit.handle)
.ok()?
.owner_id?;
let metadata = identity_metadata(&engine.world, target).ok()?;
let draft = engine
.loaded
.as_ref()?
.object_drafts
.get(metadata.original_id?.0 as usize)?;
if metadata.owner_id != Some(hero_owner)
|| draft.unit_dat_header_flags != Some(crate::mission_events::MOBILE_HQ_CLASS)
|| !vehicle_command_link(engine, target)
{
return None;
}
let hero = post_position(engine, cockpit.handle)?;
let position = post_position(engine, target)?;
crate::boarding::vehicle_interaction_distance_sq(hero, position)?;
Some(CommandPost::Warbot(target))
}
fn vehicle_command_link(engine: &Engine, handle: ObjectHandle) -> bool {
engine.loaded.as_ref().is_some_and(|mission| {
mission.control_device_tables.iter().any(|table| {
table.handle == handle
&& !table.node_provider_depletion_marked
&& matches!(&table.status, MissionControlDeviceTableStatus::Available(devices)
if has_command_link(devices))
})
})
}
fn has_command_link(devices: &[crate::EffectiveControlDevice]) -> bool {
// iron3d+0x773a0 and Control+0x2c3c0 search the current tags from index zero.
let index = devices.iter().position(|device| device.descriptor.tag == 1);
// Control+0x2b410 uses the separate cached factory-1 pointer and the
// descriptor currently applied to that device.
index.is_some_and(|index| index > 0)
&& devices
.iter()
.rfind(|device| device.factory_tag == 1)
.is_some_and(|device| device.descriptor.fixed_words[2] & 0x0800_0000 != 0)
}
fn post_position(engine: &Engine, handle: ObjectHandle) -> Option<[f32; 3]> {
registration_sequence(&engine.world, handle).ok()??;
Some(
transform_state(&engine.world, handle)
.ok()?
.position
.map(f32::from_bits),
)
}
/// Held command camera directions during the current frame.
#[derive(Clone, Copy, Default)]
pub struct CommandCameraInput {
/// Motion along the camera's right, forward and vertical axes.
pub translation: [i8; 3],
/// Yaw and upward tilt when the pointer is at a screen edge.
pub rotation: [i8; 2],
}
impl CommandCameraInput {
/// Native edge zones in the 640×480 command interface space.
#[must_use]
pub fn edge_rotation([x, y]: [f32; 2]) -> [i8; 2] {
let x = x.round_ties_even();
let y = y.round_ties_even();
[
i8::from(x < 7.0) - i8::from(x > 633.0),
i8::from(y < 7.0) - i8::from(y > 473.0),
]
}
}
#[derive(Clone, Copy, Default)]
struct CameraAxis {
direction: i8,
held: f32,
rate: f32,
}
impl CameraAxis {
fn step(&mut self, direction: i8, max_rate: f32, dt: f32) -> f32 {
// iron3d+0x372a0/+0x37540 use a half-second ramp, then multiply
// the previous frame's rate by (0.5 - dt) during release.
if direction == 0 {
self.rate *= (0.5 - dt).max(0.0);
} else {
self.held = if direction == self.direction {
(self.held + dt).min(0.5)
} else {
0.0
};
self.rate = f32::from(direction.signum()) * max_rate * (2.0 * self.held);
}
self.direction = direction;
self.rate * dt
}
}
/// The external camera retained while the player uses a command post.
pub struct CommandCamera {
post: CommandPost,
position: [f32; 3],
yaw: f32,
tilt: f32,
follow_distance: f32,
axes: [CameraAxis; 5],
}
impl CommandCamera {
/// Starts at the command post, looking north.
#[must_use]
pub fn new(engine: &Engine, post: CommandPost) -> Option<Self> {
let handle = match post {
CommandPost::Bunker(handle) | CommandPost::Warbot(handle) => handle,
};
Some(Self {
post,
position: post_position(engine, handle)?,
yaw: FRAC_PI_2,
tilt: 1.0,
follow_distance: 0.0,
axes: [CameraAxis::default(); 5],
})
}
/// Advances the external view and returns the pose for this frame.
/// `building_height` reports the highest building hit on the downward segment.
pub fn sample(
&mut self,
engine: &Engine,
dt: f32,
input: CommandCameraInput,
building_height: impl FnOnce([[f32; 3]; 2]) -> Option<f32>,
) -> Option<RawCameraTransform> {
let mission = engine.loaded.as_ref()?;
let terrain = &mission.terrain;
let [min, max] = terrain.surface_bounds()?;
match self.post {
CommandPost::Bunker(_) => {
self.advance_bunker(dt, input, max);
}
CommandPost::Warbot(handle) => {
if !vehicle_command_link(engine, handle) {
return None;
}
let target = post_position(engine, handle)?;
let state = transform_state(&engine.world, handle).ok()?;
let index = identity_metadata(&engine.world, handle)
.ok()?
.original_id?
.0 as usize;
let (_, radius) =
crate::projectile::unit_sphere(&mission.mission_assets, index, state)?;
self.advance_vehicle(dt, input.rotation, max, target, radius);
}
}
let [x, y, z] = self.position;
let ground = terrain.height_at([x, y]).ok()?;
let surface = match self.post {
CommandPost::Bunker(handle) => {
// Only the bunker passes the roof flags to iron3d+0xa1470.
let surface =
building_height([[x, y, max[2]], [x, y, ground.unwrap_or(min[2])]]).or(ground);
self.limit_to_bunker(post_position(engine, handle)?);
surface
}
CommandPost::Warbot(_) => ground,
}
.unwrap_or(0.0);
// The last camera update at iron3d+0x37720 applies this band in both modes.
self.position[2] = z.clamp(surface + 36.0, surface + 236.0);
if !self.position.into_iter().all(f32::is_finite) {
return None;
}
let matrix = LegacyIron3dEulerTransform {
translation: self.position,
orientation_radians: [0.0, FRAC_PI_2 - self.tilt, self.yaw],
}
.try_row_major()?;
Some(RawCameraTransform {
words: matrix.map(f32::to_bits),
})
}
fn advance_bunker(&mut self, dt: f32, input: CommandCameraInput, map_max: [f32; 3]) {
if dt <= 0.0 {
return;
}
// On a stalled frame one large step can be rejected at both tilt limits.
// Use the ordinary 60 Hz step size to keep those slow frames controllable.
let steps = if dt > 0.1 {
(dt * 60.0).ceil() as u32
} else {
1
};
let slice = dt / steps as f32;
for _ in 0..steps {
self.move_bunker(slice, input, map_max);
}
}
fn move_bunker(&mut self, dt: f32, input: CommandCameraInput, map_max: [f32; 3]) {
let [right, forward, up] = input.translation;
let right = self.axes[0].step(right, 125.0, dt);
let forward = self.axes[1].step(forward, 125.0, dt);
let up = self.axes[2].step(up, 62.5, dt);
let (sin, cos) = self.yaw.sin_cos();
let margin = (0.5 * COMMAND_FOV).tan() * self.position[2];
// The native update checks each of the two motions separately.
for [dx, dy] in [[right * sin, -right * cos], [forward * cos, forward * sin]] {
for (axis, step) in [dx, dy].into_iter().enumerate() {
let next = self.position[axis] + step;
if margin < next && next < map_max[axis] {
self.position[axis] = next;
}
}
}
self.position[2] += up;
self.rotate(dt, input.rotation);
}
fn rotate(&mut self, dt: f32, [yaw, tilt]: [i8; 2]) {
self.yaw += self.axes[3].step(yaw, 1.5, dt);
let next_tilt = self.tilt + self.axes[4].step(tilt, 1.5, dt);
if 0.0 < next_tilt && next_tilt < FRAC_PI_2 {
self.tilt = next_tilt;
}
}
fn limit_to_bunker(&mut self, origin: [f32; 3]) {
// iron3d+0x37720 rounds each relative coordinate before testing it.
for (point, center) in self.position[..2].iter_mut().zip(origin) {
let offset = *point - center;
if offset.round_ties_even().abs() > 200.0 {
*point = center + offset.signum() * 200.0;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::synthetic_effective_control_device;
use crate::{
create, load_gameplay_mission, starting_cockpit, EngineServices, MissionMode,
MissionRequest, MissionStartupInput,
};
use fparkan_vfs::DirectoryVfs;
use fparkan_world::OriginalObjectId;
use std::sync::Arc;
#[test]
fn command_link_requires_a_nonzero_match_and_the_cached_pilot_flag() {
let device =
|factory, current| synthetic_effective_control_device(factory, current, 0, None, None);
let generator = device(19, 19);
let mut pilot = device(1, 1);
pilot.descriptor.fixed_words[2] = 0x0800_0000;
assert!(!has_command_link(&[pilot.clone(), generator.clone()]));
assert!(has_command_link(&[generator.clone(), pilot.clone()]));
let mut last_pilot = device(1, 1);
last_pilot.descriptor.fixed_words[2] = 0x0400_0000;
assert!(!has_command_link(&[generator, pilot, last_pilot]));
}
#[test]
fn bunker_camera_moves_in_view_axes_with_native_limits() {
let origin = [300.0, 300.0, 100.0];
let mut camera = CommandCamera {
post: CommandPost::Bunker(ObjectHandle {
generation: 0,
slot: 0,
}),
position: origin,
yaw: FRAC_PI_2,
tilt: 1.0,
follow_distance: 0.0,
axes: [CameraAxis::default(); 5],
};
let input = CommandCameraInput {
translation: [1, 1, 1],
rotation: [0, 0],
};
let map_max = [1024.0, 1024.0, 220.0];
camera.move_bunker(0.25, input, map_max);
assert_eq!(camera.position, origin);
camera.move_bunker(0.25, input, map_max);
assert_eq!(camera.position, [315.625, 315.625, 107.8125]);
camera.move_bunker(0.25, CommandCameraInput::default(), map_max);
assert_eq!(camera.position, [319.53125, 319.53125, 109.765625]);
camera.position[0] = 500.5;
camera.limit_to_bunker(origin);
assert_eq!(camera.position[0], 500.5);
camera.position[0] = 500.6;
camera.limit_to_bunker(origin);
assert_eq!(camera.position[0], 500.0);
assert_eq!(CommandCameraInput::edge_rotation([634.0, 6.0]), [-1, 1]);
assert_eq!(CommandCameraInput::edge_rotation([633.0, 7.0]), [0, 0]);
camera.advance_bunker(
0.8,
CommandCameraInput {
rotation: [0, 1],
..Default::default()
},
map_max,
);
assert!(camera.tilt > 1.5 && camera.tilt < FRAC_PI_2);
}
#[test]
#[ignore = "requires licensed corpus"]
fn licensed_starting_bunker_supplies_strategy_camera() {
let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap();
let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap();
load_gameplay_mission(
&mut engine,
MissionRequest {
key: "MISSIONS/Single.01/data.tma".into(),
mode: MissionMode::SingleMission,
},
MissionStartupInput {
queue_time_ms: 0,
research_creation_gate: false,
},
None,
)
.unwrap();
let hero = starting_cockpit(&engine).unwrap();
let bunker = crate::mission_object_handle(&engine, OriginalObjectId(0)).unwrap();
let post = command_post(&engine, hero);
assert_eq!(post, Some(CommandPost::Bunker(bunker)));
let mut camera = CommandCamera::new(&engine, post.unwrap()).unwrap();
let input = CommandCameraInput::default();
let previous = camera
.sample(&engine, 0.0, input, |_| None)
.unwrap()
.translation();
let native_roof = 108.54639;
let raised = camera
.sample(&engine, 0.0, input, |[[x, y, top], [_, _, ground]]| {
assert_eq!([x, y], [previous[0], previous[1]]);
assert!(ground < native_roof && native_roof < top);
Some(native_roof)
})
.unwrap();
assert_eq!(raised.translation(), [previous[0], previous[1], 144.54639]);
}
}
|