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
|
//! Release above the factory roof and clear the apron before taking orders.
use crate::{
flight_altitude::FlightClearance,
ground_support::GroundSupport,
projectile_parts::root_triangle_hit,
route_motion::{follow_route, RouteClearance, WAYPOINT_TOLERANCE},
route_obstacles::{BuildingFootprints, Footprint},
route_traffic::{body_radius, FrameTraffic},
EngineError, LoadedMissionState, ObjectHandle, TransformState, World,
};
use fparkan_msh::Lod;
use fparkan_terrain::SurfaceQuery;
use fparkan_world::transform_state;
use std::collections::VecDeque;
pub(super) struct ReleaseSite {
pub(super) position: [f32; 3],
exit: Option<[f32; 2]>,
roof: Option<f32>,
}
pub(super) fn clear_release_position(
world: &World,
mission: &LoadedMissionState,
buildings: &mut BuildingFootprints,
plant: ObjectHandle,
plant_index: usize,
slot: usize,
preferred: [f32; 3],
) -> Result<Option<ReleaseSite>, EngineError> {
let draft = &mission.object_drafts[slot];
let pose = TransformState {
position: preferred.map(f32::to_bits),
orientation: draft.orientation_raw.map(f32::to_bits),
scale: draft.scale.map(f32::to_bits),
};
buildings.refresh(world, mission);
// The outdoor approximation remains the fallback for unprepared bounds.
let (Some(plant_bounds), Some(radius)) = (
buildings.for_handle(plant),
body_radius(&mission.mission_assets, slot, pose),
) else {
return Ok(Some(ReleaseSite {
position: preferred,
exit: None,
roof: None,
}));
};
let mut blocked = buildings.with_clearance(radius);
let [x, y, _] = preferred;
let traffic = FrameTraffic::read(world, mission);
let Some(neighbors) = traffic.blockers(plant, [x, y], radius) else {
return Ok(None);
};
blocked.extend(neighbors);
let site = release_position(
[x, y],
plant_bounds.expanded(radius),
radius,
&blocked,
|point| {
mission
.terrain
.height_at(point)
.map_err(EngineError::Terrain)
},
)?;
let Some(mut site) = site else {
return Ok(None);
};
let plant_pose = transform_state(world, plant)?;
let [x, y, z] = plant_pose.position.map(f32::from_bits);
if let Some(terrain) = mission
.terrain
.height_at([x, y])
.map_err(EngineError::Terrain)?
{
let top = z + 1000.0;
if let Some((fraction, _)) = root_triangle_hit(
&mission.mission_assets,
plant_index,
plant_pose,
[[x, y, top], [x, y, terrain]],
|_| Some(Lod(0)),
) {
let roof = top + fraction * (terrain - top);
site.exit = Some(site.exit.unwrap_or([site.position[0], site.position[1]]));
// Behavior's upper support ray adds 100 before the 15-unit release offset.
site.position = [x, y, roof + 100.0 + 15.0];
site.roof = Some(roof);
}
}
Ok(Some(site))
}
fn release_position(
preferred: [f32; 2],
plant: Footprint,
radius: f32,
blocked: &[Footprint],
mut height_at: impl FnMut([f32; 2]) -> Result<Option<f32>, EngineError>,
) -> Result<Option<ReleaseSite>, EngineError> {
let center = plant.center();
let mut alternatives = Vec::from(plant.exits(center));
alternatives.extend(plant.corners());
let distance = |p: [f32; 2]| (p[0] - preferred[0]).hypot(p[1] - preferred[1]);
alternatives.sort_by(|&a, &b| distance(a).total_cmp(&distance(b)));
let apron = plant.expanded(radius);
for point in alternatives.into_iter().chain([preferred]) {
if blocked.iter().any(|bounds| bounds.contains(point)) {
continue;
}
let Some(z) = height_at(point)? else {
continue;
};
let position = [point[0], point[1], z + 2.0];
if !apron.contains(point) {
return Ok(Some(ReleaseSite {
position,
exit: None,
roof: None,
}));
}
let mut exits = apron.exits(point);
let distance = |p: [f32; 2]| (p[0] - point[0]).hypot(p[1] - point[1]);
exits.sort_by(|&a, &b| distance(a).total_cmp(&distance(b)));
for exit in exits {
if !blocked.iter().any(|bounds| bounds.intersects(point, exit))
&& height_at(exit)?.is_some()
{
return Ok(Some(ReleaseSite {
position,
exit: Some(exit),
roof: None,
}));
}
}
}
Ok(None)
}
#[derive(Clone)]
pub(super) struct FactoryDeparture {
pub(super) handle: ObjectHandle,
pub(super) plant: ObjectHandle,
goal: [f32; 2],
ground: Option<GroundSupport>,
airborne: bool,
descent: Option<Descent>,
}
#[derive(Clone)]
struct Descent {
roof: f32,
fall_speed: f32,
}
impl FactoryDeparture {
pub(super) fn from_site(
handle: ObjectHandle,
plant: ObjectHandle,
index: usize,
site: ReleaseSite,
mission: &LoadedMissionState,
) -> Option<Self> {
let goal = site.exit?;
let airborne = mission.object_drafts[index]
.original_id
.and_then(|id| mission.unit_chassis_flags.get(&id.0))
.and_then(|chassis| chassis.can_fly)
== Some(true);
let ground = (!airborne)
.then(|| GroundSupport::prepare(&mission.mission_assets, index))
.flatten();
Some(Self {
handle,
plant,
goal,
ground,
airborne,
descent: site.roof.map(|roof| Descent {
roof,
fall_speed: 0.0,
}),
})
}
pub(super) fn move_out(
&mut self,
before: TransformState,
mission: &LoadedMissionState,
traffic: &mut FrameTraffic,
buildings: &BuildingFootprints,
seconds: f32,
) -> Result<TransformState, EngineError> {
let [x, y, altitude] = before.position.map(f32::from_bits);
let radius = traffic.radius(self.handle);
let plant_bounds = buildings
.for_handle(self.plant)
.map(|bounds| bounds.expanded(radius));
let above_plant =
self.descent.is_some() && plant_bounds.is_some_and(|bounds| bounds.contains([x, y]));
let obstacles = buildings.with_clearance_except(radius, above_plant.then_some(self.plant));
let Some(neighbors) = traffic.blockers(self.handle, [x, y], radius) else {
return Ok(before);
};
let flight = (self.airborne && radius > 0.0).then_some(FlightClearance {
body_radius: radius,
height: 2.0 * radius,
vertical_limit: f32::INFINITY,
});
let speed = mission
.control_device_tables
.iter()
.find(|table| table.handle == self.handle)
.and_then(|table| table.owner_profile.as_ref())
.map(|profile| f32::from_bits(profile.current_words[7]))
.filter(|speed| speed.is_finite() && *speed >= 0.0)
.unwrap_or(9.0);
let mut height_at = |point| {
mission
.terrain
.height_at(point)
.map_err(EngineError::Terrain)
};
let (mut after, swept) = follow_route(
before,
&mut VecDeque::from([self.goal]),
speed,
seconds,
RouteClearance {
buildings: &obstacles,
traffic: &neighbors,
flight,
ground: self.descent.is_none().then_some(self.ground).flatten(),
},
&mut height_at,
)?;
if let Some(descent) = &mut self.descent {
let [nx, ny, _] = after.position.map(f32::from_bits);
let xy = [nx, ny];
if let Some(terrain) = height_at(xy)? {
let floor = if let Some(ground) = self.ground {
ground.height(xy, after, &mut height_at)?.unwrap_or(terrain)
} else {
terrain + if self.airborne { 2.0 * radius } else { 2.0 }
};
let over_roof = plant_bounds.is_some_and(|bounds| bounds.contains(xy));
let support = if over_roof {
floor.max(descent.roof + radius)
} else {
floor
};
// shortcut: constant gravity until the original release motion is decoded.
let end_speed = descent.fall_speed + 9.81 * seconds;
let z = (altitude - descent.fall_speed.midpoint(end_speed) * seconds).max(support);
descent.fall_speed = if z > support { end_speed } else { 0.0 };
after.position[2] = z.to_bits();
if !over_roof && z == floor {
self.descent = None;
}
}
}
traffic.reserve(self.handle, swept);
Ok(after)
}
pub(super) fn finished(&self, pose: TransformState) -> bool {
let [x, y, _] = pose.position.map(f32::from_bits);
self.descent.is_none() && (x - self.goal[0]).hypot(y - self.goal[1]) <= WAYPOINT_TOLERANCE
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn release_keeps_the_cleared_path_out_of_the_factory_apron() {
let plant = Footprint::point([0.0; 2]).expanded(5.0);
let parked = Footprint::point([6.0, 0.0]).expanded(1.0);
let flat = |_| Ok(Some(3.0));
let site = release_position([6.0, 0.0], plant, 2.0, &[plant, parked], flat)
.unwrap()
.unwrap();
let [x, y, z] = site.position;
let exit = site.exit.unwrap();
assert!(!plant.contains([x, y]) && !parked.contains([x, y]));
assert!(!plant.expanded(2.0).contains(exit));
assert!(!parked.intersects([x, y], exit));
assert_eq!(z, 5.0);
let occupied = Footprint::point([0.0; 2]).expanded(8.0);
assert!(release_position([6.0, 0.0], plant, 2.0, &[occupied], flat)
.unwrap()
.is_none());
let open_ground = release_position([8.0, 0.0], plant, 2.0, &[plant], |point| {
Ok((point == [8.0, 0.0]).then_some(3.0))
})
.unwrap()
.unwrap();
assert_eq!(open_ground.position, [8.0, 0.0, 5.0]);
assert!(open_ground.exit.is_none());
}
}
|