Debian Codegraph @

similar/main/fireball.cpp

raw
1 /*
2 * Portions of this file are copyright Rebirth contributors and licensed as
3 * described in COPYING.txt.
4 * Portions of this file are copyright Parallax Software and licensed
5 * according to the Parallax license below.
6 * See COPYING.txt for license details.
7
8 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
9 SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
10 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
11 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
12 IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
13 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
14 FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
15 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
16 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
17 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
18 */
19
20 /*
21 *
22 * Code for rendering & otherwise dealing with explosions
23 *
24 */
25
26 #include <algorithm>
27 #include <numeric>
28 #include <random>
29 #include <ranges>
30 #include <optional>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34
35 #include "dxxerror.h"
36 #include "maths.h"
37 #include "vecmat.h"
38 #include "gr.h"
39 #include "3d.h"
40
41 #include "inferno.h"
42 #include "object.h"
43 #include "vclip.h"
44 #include "game.h"
45 #include "robot.h"
46 #include "sounds.h"
47 #include "player.h"
48 #include "gauges.h"
49 #include "powerup.h"
50 #include "bm.h"
51 #include "ai.h"
52 #include "weapon.h"
53 #include "fireball.h"
54 #include "collide.h"
55 #include "physics.h"
56 #include "laser.h"
57 #include "wall.h"
58 #include "multi.h"
59 #include "timer.h"
60 #include "playsave.h"
61 #include "gameseg.h"
62 #include "automap.h"
63 #include "byteutil.h"
64
65 #include "compiler-range_for.h"
66 #include "d_array.h"
67 #include "d_enumerate.h"
68 #include "d_levelstate.h"
69 #include "d_range.h"
70 #include "d_zip.h"
71 #include "partial_range.h"
72 #include "segiter.h"
73
74 using std::min;
75
76 #define EXPLOSION_SCALE (F1_0*5/2) //explosion is the obj size times this
77
78 namespace dcx {
79
80 namespace {
81
82 /* C arrays are normally indexed starting from 0. For some use cases,
83 * values in [0, Bias) for some Bias are not useful. Callers must
84 * either waste Bias unused elements at the head of the array, or
85 * subtract Bias from all indexes when accessing the array. This class
86 * automates the latter approach. Its actual size is N, and all index
87 * operations are offset by subtracting Bias. As with std::array,
88 * callers are responsible for passing only valid index values.
89 */
90 template <std::size_t Bias, typename T, std::size_t N>
91 struct biased_index_array : std::array<T, N>
92 {
93 using base_type = std::array<T, N>;
94 using typename base_type::reference;
95 using typename base_type::const_reference;
96 using typename base_type::size_type;
97 /* Not implemented, so delete it to avoid using the base class
98 * implementation, which would not adjust by Bias. This could be
99 * implemented if needed.
100 */
101 constexpr reference at(size_type position) = delete;
102 constexpr reference at(size_type position) const = delete;
103 constexpr reference operator[](size_type pos)
104 {
105 return this->base_type::operator[](pos - Bias);
106 }
107 constexpr const_reference operator[](size_type pos) const
108 {
109 return this->base_type::operator[](pos - Bias);
110 }
111 [[nodiscard]]
112 static constexpr bool valid_index(size_type pos)
113 {
114 return pos >= Bias && pos - Bias < N;
115 }
116 };
117
118 struct connected_segment_raw_distances
119 {
120 using segment_distance_count_type = uint8_t;
121 /* Minimum depth must be at least 2, since very low values are used
122 * for special purposes.
123 */
124 static constexpr std::integral_constant<segment_distance_count_type, 4> minimum_supported_max_depth{};
125 static constexpr std::integral_constant<segment_distance_count_type, 30> maximum_supported_max_depth{};
126 static constexpr std::integral_constant<segment_distance_count_type, 1 + maximum_supported_max_depth - minimum_supported_max_depth> supported_max_depth_range{};
127 /* The value_type must be sufficient to hold the largest number of
128 * segments that could be at a distance of
129 * `maximum_supported_max_depth`.
130 */
131 using depth_count_array = biased_index_array<minimum_supported_max_depth, uint16_t, supported_max_depth_range>;
132 enum class biased_distance : uint8_t
133 {
134 indeterminate,
135 depth_0,
136 };
137 static segment_distance_count_type get_distance_from_biased_distance(const biased_distance d)
138 {
139 return static_cast<segment_distance_count_type>(d) - static_cast<unsigned>(biased_distance::depth_0);
140 }
141 static biased_distance get_biased_distance_from_distance(const segment_distance_count_type d)
142 {
143 return static_cast<biased_distance>(d + static_cast<unsigned>(biased_distance::depth_0));
144 }
145 /* To reduce the stack footprint when recursively visiting segments,
146 * all the arguments that remain constant during the search are
147 * stored in an instance of `builder`, and `visit_segment` is a
148 * member method on `builder`.
149 */
150 struct builder
151 {
152 fvcsegptr &vcsegptr;
153 fvcwallptr &vcwallptr;
154 const segment_distance_count_type max_depth;
155 depth_count_array &count_segments_at_depth;
156 enumerated_array<biased_distance, MAX_SEGMENTS, segnum_t> &depth_by_segment;
157 /* Segments that are farther away than max_depth do not have a
158 * specific distance computed, and are only known to be too far
159 * away.
160 */
161 void visit_segment(vcsegidx_t current_segment_idx, segment_distance_count_type current_depth) const;
162 };
163 /* Initialize all depths to 0. These will be updated as the
164 * constructor traverses the level. Counts are only maintained for
165 * supported depths. If a segment is closer than
166 * `minimum_supported_max_depth` or farther than
167 * `maximum_supported_max_depth`, then it is not counted.
168 */
169 depth_count_array count_segments_at_depth{};
170 /* Initialize all segments to be at the indeterminate distance.
171 *
172 * Traversal of the level data will replace the placeholder distance
173 * with a real value. Traversal requires that every element either
174 * be the value `indeterminate` or have a valid depth from earlier
175 * in the traversal.
176 */
177 static_assert(static_cast<unsigned>(biased_distance::indeterminate) == 0, "`indeterminate` must be 0 so that zero-initialization assigns the value `indeterminate` to every element in the array");
178 enumerated_array<biased_distance, MAX_SEGMENTS, segnum_t> depth_by_segment{};
179 /* Prefer that the maximum depth be passed as a
180 * std::integral_constant so that it can be checked at compile time.
181 * Allow use of non-integral_constant expressions if the caller uses
182 * the explicit constructor.
183 */
184 explicit connected_segment_raw_distances(fvcsegptr &vcsegptr, fvcwallptr &vcwallptr, segment_distance_count_type max_depth, vcsegidx_t current_segment_idx);
185 template <segment_distance_count_type max_depth>
186 connected_segment_raw_distances(fvcsegptr &vcsegptr, fvcwallptr &vcwallptr, std::integral_constant<segment_distance_count_type, max_depth>, vcsegidx_t current_segment_idx) : connected_segment_raw_distances(vcsegptr, vcwallptr, max_depth, current_segment_idx)
187 {
188 static_assert(max_depth <= maximum_supported_max_depth);
189 }
190 /* Scan depth_by_segment to find the Nth segment of the desired
191 * depth, where N is drawn from `uniform_int_distribution(0,
192 * count_of_segments_at_depth - 1)(mrd)`. If there are no segments
193 * at this depth, return an empty std::optional.
194 */
195 std::optional<segnum_t> scan_segment_depths(unsigned desired_depth, std::minstd_rand &mrd) const;
196 };
197
198 static void init_debris_object(object_base &debris, const object_base &parent, const submodel_index subobj_num)
199 {
200 //Set polygon-object-specific data
201 debris.rtype.pobj_info.model_num = parent.rtype.pobj_info.model_num;
202 debris.rtype.pobj_info.subobj_flags = 1 << underlying_value(subobj_num);
203 debris.rtype.pobj_info.tmap_override = parent.rtype.pobj_info.tmap_override;
204
205 //Set physics data for this object
206 debris.mtype.phys_info.velocity = /* added_scaled_random_velocity = */ vm_vec_build_add(
207 /* scaled_random_velocity = */ vm_vec_copy_scale(
208 /* normalized_random_velocity = */ vm_vec_normalized_quick(
209 /* random_velocity = */ vms_vector{
210 .x = D_RAND_MAX/2 - d_rand(),
211 .y = D_RAND_MAX/2 - d_rand(),
212 .z = D_RAND_MAX/2 - d_rand()
213 }
214 ),
215 i2f(10 + (30 * d_rand() / D_RAND_MAX))
216 ),
217 parent.mtype.phys_info.velocity
218 );
219
220 debris.mtype.phys_info.rotvel = {d_rand() + 0x1000, d_rand()*2 + 0x4000, d_rand()*3 + 0x2000};
221 debris.mtype.phys_info.rotthrust = {};
222
223 const fix DEBRIS_LIFE{f1_0 * (PERSISTENT_DEBRIS?60:2)}; //lifespan in seconds
224 debris.lifeleft = 3*DEBRIS_LIFE/4 + fixmul(d_rand(), DEBRIS_LIFE); // Some randomness, so they don't all go away at the same time.
225
226 debris.mtype.phys_info.mass = fixmuldiv(parent.mtype.phys_info.mass, debris.size, parent.size);
227 debris.mtype.phys_info.drag = 0;
228
229 if (PERSISTENT_DEBRIS)
230 {
231 debris.mtype.phys_info.flags |= PF_BOUNCE;
232 debris.mtype.phys_info.drag = 128;
233 }
234 }
235
236 }
237
238 unsigned Num_exploding_walls;
239
240 void init_exploding_walls()
241 {
242 Num_exploding_walls = 0;
243 }
244
245 connected_segment_raw_distances::connected_segment_raw_distances(fvcsegptr &vcsegptr, fvcwallptr &vcwallptr, segment_distance_count_type max_depth, vcsegidx_t current_segment_idx)
246 {
247 builder{vcsegptr, vcwallptr, max_depth, count_segments_at_depth, depth_by_segment}.visit_segment(current_segment_idx, 0u);
248 }
249
250 std::optional<segnum_t> connected_segment_raw_distances::scan_segment_depths(const unsigned desired_depth, std::minstd_rand &mrd) const
251 {
252 const auto count_segments_at_desired_depth{count_segments_at_depth[desired_depth]};
253 if (!count_segments_at_desired_depth)
254 /* No segments exist at this depth. Move to next depth.
255 */
256 return std::nullopt;
257 /* Pick a random segment within the segments at the selected
258 * depth.
259 */
260 std::uniform_int_distribution uid(0u, count_segments_at_desired_depth - 1u);
261 /* Walk over all segments. Ignore any segment at the wrong depth.
262 * Ignore the first `skip_count` segments at the right depth.
263 */
264 const auto initial_skip_count{uid(mrd)};
265 unsigned skip_count{initial_skip_count};
266 const auto desired_biased_depth{get_biased_distance_from_distance(desired_depth)};
267 for (const auto &&[sn, biased_depth] : enumerate(depth_by_segment))
268 {
269 if (biased_depth != desired_biased_depth)
270 continue;
271 if (!skip_count)
272 /* Found a segment at the correct depth and the required
273 * number of segments have been skipped. Pick this segment.
274 */
275 return sn;
276 -- skip_count;
277 }
278 /* This should not happen. `skip_count` is computed such that it is
279 * below the number of segments at a depth of `desired_depth`, so
280 * control should always `return` from the loop.
281 */
282 con_printf(CON_URGENT, DXX_STRINGIZE_FL(__FILE__, __LINE__, "error: count=%u, skip_count=%u, and no segment found at depth %u"), count_segments_at_desired_depth, initial_skip_count, desired_depth);
283 return std::nullopt;
284 }
285
286 void connected_segment_raw_distances::builder::visit_segment(const vcsegidx_t current_segment_idx, const segment_distance_count_type current_depth) const
287 {
288 auto &biased_depth{depth_by_segment[current_segment_idx]};
289 if (biased_depth != biased_distance::indeterminate)
290 {
291 const auto d{get_distance_from_biased_distance(biased_depth)};
292 if (d <= current_depth)
293 /* This segment was already found through some other
294 * route. Leave that result in place.
295 */
296 return;
297 /* If this segment was previously found at a greater depth, and
298 * the current step found a shorter path to that segment, then
299 * reduce the count of segments at the greater depth, since the
300 * recorded depth of this segment will be changed.
301 */
302 if (count_segments_at_depth.valid_index(d))
303 -- count_segments_at_depth[d];
304 }
305 biased_depth = get_biased_distance_from_distance(current_depth);
306 if (current_depth >= max_depth)
307 return;
308 const shared_segment &seg{*vcsegptr(current_segment_idx)};
309 if (seg.special == segment_special::controlcen)
310 {
311 /* Every caller wants to exclude the control-center segment from
312 * the set of choices. If the segment is encountered here,
313 * assign it a depth value that prevents it being selected, and
314 * stop. Stopping here prevents exploring segments beyond the
315 * control-center. If there is a path around the
316 * control-center, that path can be used to reach those segments
317 * instead. This will lead to a slightly higher than accurate
318 * distance value for those segments, but the original Descent
319 * implementation had a random walk that could wander about and
320 * assign high values to any segment it reached. By refusing to
321 * traverse through the control center, this implementation
322 * avoids selecting areas that are only reachable by flying
323 * through the control center.
324 */
325 biased_depth = get_biased_distance_from_distance(0);
326 return;
327 }
328 /* Segments closer than minimum_supported_max_depth or farther than
329 * maximum_supported_max_depth will not be analyzed later, so no
330 * count is maintained for them.
331 *
332 * This increment is deferred until after the control-center check,
333 * so that it does not need to be undone when the control-center is
334 * found.
335 */
336 if (count_segments_at_depth.valid_index(current_depth))
337 ++ count_segments_at_depth[current_depth];
338 for (const auto &&[child_segnum, side] : zip(seg.children, seg.sides))
339 {
340 if (!IS_CHILD(child_segnum))
341 continue;
342 if (const auto wall_num{side.wall_num}; wall_num != wall_none)
343 {
344 auto &w{*vcwallptr(wall_num)};
345 if (w.type == WALL_CLOSED)
346 continue;
347 if (w.type == WALL_DOOR && (w.flags & wall_flag::door_locked))
348 continue;
349 }
350 visit_segment(child_segnum, current_depth + 1);
351 }
352 }
353
354 }
355
356 namespace dsx {
357
358 #if DXX_BUILD_DESCENT == 2
359 fix Flash_effect=0;
360 constexpr int PK1=1, PK2=8;
361 #endif
362
363 namespace {
364
365 static bool can_collide(const object *const weapon_object, const object_base &iter_object, const object *const parent_object)
366 {
367 /* `weapon_object` may not be a weapon in some cases, though the
368 * caller originally expected it would be. For this function, the
369 * distinction is currently irrelevant.
370 */
371 #if DXX_BUILD_DESCENT == 1
372 (void)weapon_object;
373 #elif DXX_BUILD_DESCENT == 2
374 if (weapon_object == &iter_object)
375 return false;
376 if (iter_object.type == OBJ_NONE)
377 return false;
378 if (iter_object.flags & OF_SHOULD_BE_DEAD)
379 return false;
380 #endif
381 switch (iter_object.type)
382 {
383 #if DXX_BUILD_DESCENT == 2
384 case OBJ_WEAPON:
385 return is_proximity_bomb_or_player_smart_mine_or_placed_mine(get_weapon_id(iter_object));
386 #endif
387 case OBJ_CNTRLCEN:
388 case OBJ_PLAYER:
389 return true;
390 case OBJ_ROBOT:
391 if (parent_object == nullptr)
392 return false;
393 if (parent_object->type != OBJ_ROBOT)
394 return true;
395 return get_robot_id(*parent_object) != get_robot_id(iter_object);
396 default:
397 return false;
398 }
399 }
400
401 }
402
403 imobjptridx_t object_create_explosion_without_damage(const d_vclip_array &Vclip, const vmsegptridx_t segnum, const vms_vector &position, const fix size, const vclip_index vclip_type)
404 {
405 const auto &&obj_fireball{obj_create(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, OBJ_FIREBALL, underlying_value(vclip_type), segnum, position, &vmd_identity_matrix, size, object::control_type::explosion, object::movement_type::None, render_type::RT_FIREBALL)};
406 if (obj_fireball)
407 {
408 object &o = *obj_fireball;
409 //now set explosion-specific data
410 o.lifeleft = Vclip[vclip_type].play_time;
411 o.ctype.expl_info.spawn_time = -1;
412 o.ctype.expl_info.delete_objnum = object_none;
413 o.ctype.expl_info.delete_time = -1;
414 }
415 return obj_fireball;
416 }
417
418 namespace {
419
420 static imobjptridx_t object_create_explosion_with_damage(const d_robot_info_array &Robot_info, const d_vclip_array &Vclip, fvmobjptridx &vmobjptridx, const imobjptridx_t obj_explosion_origin, const vmsegptridx_t segnum, const vms_vector &position, const fix size, const vclip_index vclip_type, const fix maxdamage, const fix maxdistance, const fix maxforce, const icobjptridx_t parent)
421 {
422 /* `obj_explosion_origin` may not be a weapon in some cases, though
423 * this function originally expected it would be.
424 */
425 const auto &&obj_fireball{object_create_explosion_without_damage(Vclip, segnum, position, size, vclip_type)};
426 if (obj_fireball == object_none)
427 return object_none;
428 #if DXX_BUILD_DESCENT == 2
429 auto &Objects{LevelUniqueObjectState.Objects};
430 #endif
431 if (maxdamage > 0) {
432 fix force;
433 vms_vector pos_hit, vforce;
434 fix damage;
435 // -- now legal for badass explosions on a wall. Assert(obj_explosion_origin != NULL);
436
437 range_for (const auto &&obj_iter, vmobjptridx)
438 {
439 // Weapons used to be affected by badass explosions, but this introduces serious problems.
440 // When a smart bomb blows up, if one of its children goes right towards a nearby wall, it will
441 // blow up, blowing up all the children. So I remove it. MK, 09/11/94
442 if (can_collide(obj_explosion_origin, obj_iter, parent))
443 {
444 const auto dist{vm_vec_dist_quick(obj_iter->pos, obj_fireball->pos)};
445 // Make damage be from 'maxdamage' to 0.0, where 0.0 is 'maxdistance' away;
446 if ( dist < maxdistance ) {
447 if (object_to_object_visibility(obj_fireball, obj_iter, FQ_TRANSWALL))
448 {
449 damage = maxdamage - fixmuldiv( dist, maxdamage, maxdistance );
450 force = maxforce - fixmuldiv( dist, maxforce, maxdistance );
451
452 // Find the force vector on the object
453 vm_vec_normalized_dir_quick(vforce, obj_iter->pos, obj_fireball->pos);
454 vm_vec_scale(vforce, force );
455
456 // Find where the point of impact is... ( pos_hit )
457 vm_vec_scale(vm_vec_sub(pos_hit, obj_fireball->pos, obj_iter->pos), fixdiv(obj_iter->size, obj_iter->size + dist));
458 switch (obj_iter->type)
459 {
460 #if DXX_BUILD_DESCENT == 2
461 case OBJ_WEAPON:
462 phys_apply_force(obj_iter, vforce);
463
464 if (is_proximity_bomb_or_player_smart_mine(get_weapon_id(obj_iter)))
465 { //prox bombs have chance of blowing up
466 if (fixmul(dist,force) > i2f(8000)) {
467 obj_iter->flags |= OF_SHOULD_BE_DEAD;
468 explode_badass_weapon(Robot_info, obj_iter, obj_iter->pos);
469 }
470 }
471 break;
472 #endif
473 case OBJ_ROBOT:
474 {
475 phys_apply_force(obj_iter, vforce);
476 #if DXX_BUILD_DESCENT == 2
477 // If not a boss, stun for 2 seconds at 32 force, 1 second at 16 force
478 fix flash;
479 if (obj_explosion_origin != object_none && obj_explosion_origin->type == OBJ_WEAPON && Robot_info[get_robot_id(obj_iter)].boss_flag == boss_robot_id::None && (flash = Weapon_info[get_weapon_id(obj_explosion_origin)].flash))
480 {
481 ai_static *const aip{&obj_iter->ctype.ai_info};
482
483 if (obj_fireball->ctype.ai_info.SKIP_AI_COUNT * FrameTime < F1_0)
484 {
485 const int force_val = f2i(fixdiv(vm_vec_mag_quick(vforce) * flash, FrameTime) / 128) + 2;
486 aip->SKIP_AI_COUNT += force_val;
487 obj_iter->mtype.phys_info.rotthrust.x = ((d_rand() - 16384) * force_val) / 16;
488 obj_iter->mtype.phys_info.rotthrust.y = ((d_rand() - 16384) * force_val) / 16;
489 obj_iter->mtype.phys_info.rotthrust.z = ((d_rand() - 16384) * force_val) / 16;
490 obj_iter->mtype.phys_info.flags |= PF_USES_THRUST;
491 } else
492 aip->SKIP_AI_COUNT--;
493 }
494 #endif
495
496 const auto Difficulty_level{underlying_value(GameUniqueState.Difficulty_level)};
497 // When a robot gets whacked by a badass force, he looks towards it because robots tend to get blasted from behind.
498 {
499 vms_vector neg_vforce;
500 neg_vforce.x = vforce.x * -2 * (7 - Difficulty_level)/8;
501 neg_vforce.y = vforce.y * -2 * (7 - Difficulty_level)/8;
502 neg_vforce.z = vforce.z * -2 * (7 - Difficulty_level)/8;
503 phys_apply_rot(obj_iter, neg_vforce);
504 }
505 if (obj_iter->shields >= 0)
506 {
507 #if DXX_BUILD_DESCENT == 2
508 const auto &robot_info{Robot_info[get_robot_id(obj_iter)]};
509 /* Descent 1 bosses produce an index that
510 * is not valid for this array, so they
511 * never test for invulnerability.
512 */
513 if (const auto boss_index{build_boss_robot_index_from_boss_robot_id(robot_info.boss_flag)}; Boss_invulnerable_matter.valid_index(boss_index) && Boss_invulnerable_matter[boss_index])
514 damage /= 4;
515 #endif
516 if (apply_damage_to_robot(Robot_info, obj_iter, damage, parent))
517 if (obj_explosion_origin != object_none && parent == get_local_player().objnum)
518 add_points_to_score(ConsoleObject->ctype.player_info, Robot_info[get_robot_id(obj_iter)].score_value, Game_mode);
519 }
520 #if DXX_BUILD_DESCENT == 2
521 if (obj_explosion_origin != object_none && Robot_info[get_robot_id(obj_iter)].companion && !(obj_explosion_origin->type == OBJ_WEAPON && Weapon_info[get_weapon_id(obj_explosion_origin)].flash))
522 {
523 static const char ouch_str[]{"ouch! " "ouch! " "ouch! " "ouch! "};
524 int count = f2i(damage / 8);
525 if (count > 4)
526 count = 4;
527 else if (count <= 0)
528 count = 1;
529 buddy_message_str(&ouch_str[(4 - count) * 6]);
530 }
531 #endif
532 break;
533 }
534 case OBJ_CNTRLCEN:
535 if (parent != object_none && obj_iter->shields >= 0)
536 apply_damage_to_controlcen(Robot_info, obj_iter, damage, parent);
537 break;
538 case OBJ_PLAYER: {
539 icobjptridx_t killer{object_none};
540 #if DXX_BUILD_DESCENT == 2
541 // Hack! Warning! Test code!
542 fix flash;
543 if (obj_explosion_origin != object_none && obj_explosion_origin->type == OBJ_WEAPON && (flash = Weapon_info[get_weapon_id(obj_explosion_origin)].flash) && get_player_id(obj_iter) == Player_num)
544 {
545 int fe = min(F1_0 * 4, force * flash / 32); // For four seconds or less
546
547 if (laser_parent_is_player(Objects.vcptr, obj_explosion_origin->ctype.laser_info, *ConsoleObject))
548 {
549 fe /= 2;
550 force /= 2;
551 }
552 if (force > F1_0) {
553 Flash_effect = fe;
554 PALETTE_FLASH_ADD(PK1 + f2i(PK2*force), PK1 + f2i(PK2*force), PK1 + f2i(PK2*force));
555 }
556 }
557 #endif
558 if (obj_explosion_origin != object_none && (Game_mode & GM_MULTI) && obj_explosion_origin->type == OBJ_PLAYER)
559 {
560 killer = obj_explosion_origin;
561 }
562 auto vforce2{vforce};
563 if (parent != object_none ) {
564 killer = parent;
565 if (killer != ConsoleObject) // if someone else whacks you, cut force by 2x
566 {
567 vforce2.x /= 2; vforce2.y /= 2; vforce2.z /= 2;
568 }
569 }
570 vforce2.x /= 2; vforce2.y /= 2; vforce2.z /= 2;
571
572 phys_apply_force(obj_iter, vforce);
573 phys_apply_rot(obj_iter, vforce2);
574 if (obj_iter->shields >= 0)
575 {
576 #if DXX_BUILD_DESCENT == 2
577 if (GameUniqueState.Difficulty_level == Difficulty_level_type::_0)
578 damage /= 4;
579 #endif
580 apply_damage_to_player(obj_iter, killer, damage, apply_damage_player::check_for_friendly);
581 }
582 }
583 break;
584
585 default:
586 Int3(); // Illegal object type
587 } // end switch
588 } else {
589 ;
590 } // end if (object_to_object_visibility...
591 } // end if (dist < maxdistance)
592 }
593 } // end for
594 } // end if (maxdamage...
595 return obj_fireball;
596 }
597
598 }
599
600 imobjptridx_t object_create_badass_explosion(const d_robot_info_array &Robot_info, const imobjptridx_t objp, const vmsegptridx_t segnum, const vms_vector &position, fix size, const vclip_index vclip_type, fix maxdamage, fix maxdistance, fix maxforce, const icobjptridx_t parent)
601 {
602 auto &Objects{LevelUniqueObjectState.Objects};
603 auto &vmobjptridx{Objects.vmptridx};
604 const imobjptridx_t rval{object_create_explosion_with_damage(Robot_info, Vclip, vmobjptridx, objp, segnum, position, size, vclip_type, maxdamage, maxdistance, maxforce, parent)};
605
606 if ((objp != object_none) && (objp->type == OBJ_WEAPON))
607 create_weapon_smart_children(objp);
608 return rval;
609 }
610
611 //blows up a badass weapon, creating the badass explosion
612 //return the explosion object
613 void explode_badass_weapon(const d_robot_info_array &Robot_info, const vmobjptridx_t obj,const vms_vector &pos)
614 {
615 auto &Objects{LevelUniqueObjectState.Objects};
616 auto &imobjptridx{Objects.imptridx};
617 const auto weapon_id{get_weapon_id(obj)};
618 const weapon_info *const wi{&Weapon_info[weapon_id]};
619
620 Assert(wi->damage_radius);
621 #if DXX_BUILD_DESCENT == 2
622 if (weapon_id == weapon_id_type::EARTHSHAKER_ID || weapon_id == weapon_id_type::ROBOT_EARTHSHAKER_ID)
623 smega_rock_stuff();
624 #endif
625 digi_link_sound_to_object(sound_effect::SOUND_BADASS_EXPLOSION, obj, 0, F1_0, sound_stack::allow_stacking);
626
627 const auto Difficulty_level{GameUniqueState.Difficulty_level};
628 object_create_badass_explosion(Robot_info, obj, vmsegptridx(obj->segnum), pos,
629 wi->impact_size,
630 wi->robot_hit_vclip,
631 wi->strength[Difficulty_level],
632 wi->damage_radius,wi->strength[Difficulty_level],
633 imobjptridx(obj->ctype.laser_info.parent_num));
634
635 }
636
637 namespace {
638
639 static void explode_badass_object(const d_robot_info_array &Robot_info, fvmsegptridx &vmsegptridx, const vmobjptridx_t objp, fix damage, fix distance, fix force)
640 {
641 const auto &&rval = object_create_badass_explosion(Robot_info, objp, vmsegptridx(objp->segnum), objp->pos, objp->size,
642 get_explosion_vclip(Robot_info, objp, explosion_vclip_stage::s0),
643 damage, distance, force,
644 objp);
645 if (rval != object_none)
646 digi_link_sound_to_object(sound_effect::SOUND_BADASS_EXPLOSION, rval, 0, F1_0, sound_stack::allow_stacking);
647 }
648
649 }
650
651 //blows up the player with a badass explosion
652 //return the explosion object
653 void explode_badass_player(const d_robot_info_array &Robot_info, const vmobjptridx_t objp)
654 {
655 explode_badass_object(Robot_info, vmsegptridx, objp, F1_0*50, F1_0*40, F1_0*150);
656 }
657
658 namespace {
659
660 static void object_create_debris(fvmsegptridx &vmsegptridx, const object_base &parent, const submodel_index subobj_num, const fix subobject_radius)
661 {
662 Assert(parent.type == OBJ_ROBOT || parent.type == OBJ_PLAYER);
663
664 if (const auto objpi{obj_create(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, OBJ_DEBRIS, 0, vmsegptridx(parent.segnum), parent.pos, &parent.orient, subobject_radius, object::control_type::debris, object::movement_type::physics, render_type::RT_POLYOBJ)})
665 init_debris_object(*objpi, parent, subobj_num);
666 /* Ignore failure to create debris. Debris is cosmetic. */
667 }
668
669 }
670
671 void draw_fireball(const d_vclip_array &Vclip, grs_canvas &canvas, const vcobjptridx_t obj)
672 {
673 const auto lifeleft{obj->lifeleft};
674 if (lifeleft > 0)
675 draw_vclip_object(canvas, obj, lifeleft, Vclip[get_fireball_id(obj)]);
676 }
677
678 namespace {
679
680 static unsigned disallowed_cc_dist(fvcsegptr &vcsegptr, fvcvertptr &vcvertptr, const vcsegptridx_t &segp, const vms_vector &player_pos, const vcsegptridx_t player_seg, const unsigned cur_drop_depth)
681 {
682 const shared_segment &sseg{*segp};
683 //don't drop in any children of control centers
684 for (const auto ch : sseg.children)
685 {
686 if (!IS_CHILD(ch))
687 continue;
688 const shared_segment &childsegp{*vcsegptr(ch)};
689 if (childsegp.special == segment_special::controlcen)
690 return 1;
691 }
692 //bail if not far enough from original position
693 const auto tempv{compute_segment_center(vcvertptr, sseg)};
694 if (find_connected_distance(player_pos, player_seg, tempv, segp, -1, wall_is_doorway_mask::fly) < static_cast<fix>(i2f(20) * cur_drop_depth))
695 return 1;
696 return 0;
697 }
698
699 // ------------------------------------------------------------------------------------------------------
700 // Choose segment to drop a powerup in.
701 // For all active net players, try to create a N segment path from the player. If possible, return that
702 // segment. If not possible, try another player. After a few tries, use a random segment.
703 // Don't drop if control center in segment.
704 static vmsegptridx_t choose_drop_segment(fvmsegptridx &vmsegptridx, fvcvertptr &vcvertptr, fvcwallptr &vcwallptr, const playernum_t drop_pnum)
705 {
706 auto &Objects{LevelUniqueObjectState.Objects};
707 auto &vcobjptr{Objects.vcptr};
708 auto &vmobjptr{Objects.vmptr};
709 auto &drop_player{*vcplayerptr(drop_pnum)};
710 auto &drop_playerobj{*vmobjptr(drop_player.objnum)};
711
712 auto mrd{std::minstd_rand(timer_query())};
713 per_player_array<playernum_t> candidate_drop_players;
714 const auto end_drop_players = [&candidate_drop_players, drop_pnum]() {
715 const auto b{candidate_drop_players.begin()};
716 auto r{b};
717 #if DXX_BUILD_DESCENT == 2
718 /* Build a list of active players, excluding the initiator and
719 * anyone from the same team as the initiator.
720 */
721 const auto team_of_drop_player{multi_get_team_from_player(Netgame, drop_pnum)};
722 for (auto &&[pnum, plr] : enumerate(Players))
723 {
724 /* Skip the initiator, so that items will try to jump from
725 * player to player as the item is spent and respawned.
726 */
727 if (pnum == drop_pnum)
728 continue;
729 if (plr.connected == player_connection_status::disconnected)
730 continue;
731 if ((Game_mode & GM_TEAM) && multi_get_team_from_player(Netgame, pnum) == team_of_drop_player)
732 continue;
733 *r++ = pnum;
734 }
735 if (b != r)
736 /* If at least one such player found, stop and use that
737 * list.
738 */
739 return r;
740 #endif
741 /* Otherwise, try again, but allow teammates of the initiator.
742 * Exclude the drop initiator.
743 */
744 for (auto &&[pnum, plr] : enumerate(Players))
745 {
746 if (pnum == drop_pnum)
747 continue;
748 if (plr.connected == player_connection_status::disconnected)
749 continue;
750 *r++ = pnum;
751 }
752 if (b != r)
753 /* If a teammate was found, use that. This encourages the
754 * game to move the items among players.
755 */
756 return r;
757 /* If no player found through other rules, use the player
758 * who triggered the drop event.
759 */
760 *r++ = drop_pnum;
761 return r;
762 }();
763 /* candidate_drop_players now contains the player IDs of all players
764 * that can be used for a drop. Shuffle them for randomness to vary
765 * who will be checked first for each new item.
766 */
767 std::shuffle(candidate_drop_players.begin(), end_drop_players, mrd);
768 static constexpr std::integral_constant<connected_segment_raw_distances::segment_distance_count_type, 8> net_drop_max_depth_lower{};
769 static constexpr std::integral_constant<connected_segment_raw_distances::segment_distance_count_type, 24> net_drop_max_depth_upper{};
770 static constexpr std::integral_constant<connected_segment_raw_distances::segment_distance_count_type, 4> net_drop_min_depth{};
771 static_assert(connected_segment_raw_distances::depth_count_array::valid_index(net_drop_max_depth_lower));
772 static_assert(connected_segment_raw_distances::depth_count_array::valid_index(net_drop_max_depth_upper));
773 static_assert(connected_segment_raw_distances::depth_count_array::valid_index(net_drop_min_depth + 1u));
774
775 const auto &&drop_player_seg{vmsegptridx(drop_playerobj.segnum)};
776
777 /* Defer constructing instances until needed. In most games, a
778 * segment should be found before all MAX_PLAYERS instances are
779 * constructed.
780 */
781 per_player_array<std::unique_ptr<connected_segment_raw_distances>> distance_by_player;
782 std::optional<vmsegptridx_t> fallback_drop;
783 for (const unsigned candidate_depth : xrange(std::uniform_int_distribution(net_drop_max_depth_lower + 0u, net_drop_max_depth_upper + 0u)(mrd), net_drop_min_depth, xrange_descending()))
784 {
785 for (const auto pnum : std::ranges::subrange(candidate_drop_players.begin(), end_drop_players))
786 {
787 auto &plr{*vcplayerptr(pnum)};
788 auto &plrobj{*vcobjptr(plr.objnum)};
789 auto &rdp{distance_by_player[pnum]};
790 if (!rdp)
791 /* connected_segment_raw_distances computes data for all
792 * distances below candidate_depth too. Since the
793 * xrange counts down, this initialization is
794 * sufficient to cover all data required by all passes
795 * of the loop.
796 */
797 rdp = std::make_unique<connected_segment_raw_distances>(vcsegptr, vcwallptr, candidate_depth, plrobj.segnum);
798 auto &rd{*rdp};
799 const auto sn{rd.scan_segment_depths(candidate_depth, mrd)};
800 if (!sn)
801 continue;
802 const auto segnum{*sn};
803 const auto &&segp{vmsegptridx(segnum)};
804 if (disallowed_cc_dist(vcsegptr, vcvertptr, segp, drop_playerobj.pos, drop_player_seg, candidate_depth))
805 {
806 if (!fallback_drop.has_value())
807 fallback_drop = segp;
808 continue;
809 }
810 return segp;
811 }
812 }
813 if (fallback_drop.has_value())
814 /* If no player found a segment acceptable to the first pass
815 * rules, but a player found a reachable segment, use that
816 * segment. This differs slightly from retail, which would
817 * compute the fallback from the initiator, rather than a random
818 * successful player. However, since saving the fallback is
819 * cheap, this is done instead of performing yet another search.
820 */
821 return *fallback_drop;
822 /* This can be reached if there are no segments found at any of the
823 * acceptable depths. If the origin segment is in a small room with
824 * no passable exits, this can happen.
825 *
826 * Give up and pick a completely random segment. This is compatible
827 * with retail.
828 */
829 std::uniform_int_distribution<typename std::underlying_type<segnum_t>::type> uid(0u, Highest_segment_index);
830 return vmsegptridx(vmsegidx_t(segnum_t{uid(mrd)}));
831 }
832
833 }
834
835 // ------------------------------------------------------------------------------------------------------
836 // (Re)spawns powerup if in a network game.
837 void maybe_drop_net_powerup(powerup_type_t powerup_type, bool adjust_cap, bool random_player)
838 {
839 auto &LevelSharedVertexState{LevelSharedSegmentState.get_vertex_state()};
840 auto &LevelUniqueControlCenterState{LevelUniqueObjectState.ControlCenterState};
841 auto &Vertices{LevelSharedVertexState.get_vertices()};
842 playernum_t pnum{Player_num};
843 if ((Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP)) {
844 if ((Game_mode & GM_NETWORK) && adjust_cap)
845 {
846 MultiLevelInv_Recount(); // recount current items
847 if (!MultiLevelInv_AllowSpawn(powerup_type))
848 return;
849 }
850
851 if (LevelUniqueControlCenterState.Control_center_destroyed || Network_status == network_state::endlevel)
852 return;
853
854 if (random_player)
855 {
856 uint_fast32_t failsafe_count{0};
857 do {
858 pnum = d_rand() % MAX_PLAYERS;
859 if (failsafe_count > MAX_PLAYERS*4) // that was plenty of tries to find a good player...
860 {
861 pnum = Player_num; // ... go with Player_num instead
862 break;
863 }
864 failsafe_count++;
865 } while (vcplayerptr(pnum)->connected != player_connection_status::playing);
866 }
867
868 //--old-- segnum = (d_rand() * Highest_segment_index) >> 15;
869 //--old-- Assert((segnum >= 0) && (segnum <= Highest_segment_index));
870 //--old-- if (segnum < 0)
871 //--old-- segnum = -segnum;
872 //--old-- while (segnum > Highest_segment_index)
873 //--old-- segnum /= 2;
874
875 Net_create_loc = 0;
876
877 auto &vcvertptr{Vertices.vcptr};
878 const auto &&segnum{choose_drop_segment(LevelUniqueSegmentState.get_segments().vmptridx, vcvertptr, LevelUniqueWallSubsystemState.Walls.vcptr, pnum)};
879 const auto &&new_pos{pick_random_point_in_seg(vcvertptr, segnum, std::minstd_rand(d_rand()))};
880 const auto &&objnum{drop_powerup(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, Vclip, powerup_type, {}, new_pos, segnum, true)};
881 if (objnum == object_none)
882 return;
883 multi_send_create_powerup(powerup_type, segnum, objnum, new_pos);
884 object_create_explosion_without_damage(Vclip, segnum, new_pos, i2f(5), vclip_index::powerup_disappearance);
885 }
886 }
887
888 namespace {
889
890 // ------------------------------------------------------------------------------------------------------
891 // Return true if current segment contains some object.
892 static const object_base *segment_contains_powerup(fvcobjptridx &vcobjptridx, fvcsegptr &vcsegptr, const unique_segment &segnum, const powerup_type_t obj_id)
893 {
894 for (auto &o : objects_in<const object_base>(segnum, vcobjptridx, vcsegptr))
895 {
896 if (o.type == OBJ_POWERUP && get_powerup_id(o) == obj_id)
897 return &o;
898 }
899 return nullptr;
900 }
901
902 // ------------------------------------------------------------------------------------------------------
903 static const object_base *powerup_nearby_aux(fvcobjptridx &vcobjptridx, fvcsegptr &vcsegptr, const vcsegidx_t segnum, const powerup_type_t object_id, uint_fast32_t depth)
904 {
905 const cscusegment &&segp{vcsegptr(segnum)};
906 if (auto r = segment_contains_powerup(vcobjptridx, vcsegptr, segp, object_id))
907 return r;
908 if (! -- depth)
909 return nullptr;
910 for (const auto seg2 : segp.s.children)
911 {
912 if (seg2 != segment_none)
913 if (auto r = powerup_nearby_aux(vcobjptridx, vcsegptr, seg2, object_id, depth))
914 return r;
915 }
916 return nullptr;
917 }
918
919 // ------------------------------------------------------------------------------------------------------
920 // Return true if some powerup is nearby (within 3 segments).
921 static const object_base *weapon_nearby(fvcobjptridx &vcobjptridx, fvcsegptr &vcsegptr, const object_base &objp, const powerup_type_t weapon_id)
922 {
923 return powerup_nearby_aux(vcobjptridx, vcsegptr, objp.segnum, weapon_id, 2);
924 }
925
926 }
927
928 // ------------------------------------------------------------------------------------------------------
929 void maybe_replace_powerup_with_energy(object_base &del_obj)
930 {
931 auto &Objects{LevelUniqueObjectState.Objects};
932 auto &vcobjptridx{Objects.vcptridx};
933 auto &vmobjptr{Objects.vmptr};
934 /* This function has no special handling to remap laser weapons, so
935 * borrow LASER_INDEX as a flag value to indicate that the powerup
936 * ID was not recognized.
937 */
938 static constexpr primary_weapon_index_t unset_weapon_index{primary_weapon_index_t::LASER_INDEX};
939 primary_weapon_index_t weapon_index{unset_weapon_index};
940
941 if (del_obj.contains.type != contained_object_type::powerup)
942 return;
943
944 switch (del_obj.contains.id.powerup)
945 {
946 case powerup_type_t::POW_CLOAK:
947 if (weapon_nearby(vcobjptridx, vcsegptr, del_obj, powerup_type_t::POW_CLOAK) != nullptr)
948 del_obj.contains.count = 0;
949 return;
950 case powerup_type_t::POW_VULCAN_WEAPON:
951 weapon_index = primary_weapon_index_t::VULCAN_INDEX;
952 break;
953 case powerup_type_t::POW_SPREADFIRE_WEAPON:
954 weapon_index = primary_weapon_index_t::SPREADFIRE_INDEX;
955 break;
956 case powerup_type_t::POW_PLASMA_WEAPON:
957 weapon_index = primary_weapon_index_t::PLASMA_INDEX;
958 break;
959 case powerup_type_t::POW_FUSION_WEAPON:
960 weapon_index = primary_weapon_index_t::FUSION_INDEX;
961 break;
962 #if DXX_BUILD_DESCENT == 2
963 case powerup_type_t::POW_GAUSS_WEAPON:
964 weapon_index = primary_weapon_index_t::GAUSS_INDEX;
965 break;
966 case powerup_type_t::POW_HELIX_WEAPON:
967 weapon_index = primary_weapon_index_t::HELIX_INDEX;
968 break;
969 case powerup_type_t::POW_PHOENIX_WEAPON:
970 weapon_index = primary_weapon_index_t::PHOENIX_INDEX;
971 break;
972 case powerup_type_t::POW_OMEGA_WEAPON:
973 weapon_index = primary_weapon_index_t::OMEGA_INDEX;
974 break;
975 #endif
976 case powerup_type_t::POW_EXTRA_LIFE:
977 case powerup_type_t::POW_ENERGY:
978 case powerup_type_t::POW_SHIELD_BOOST:
979 case powerup_type_t::POW_LASER:
980 case powerup_type_t::POW_KEY_BLUE:
981 case powerup_type_t::POW_KEY_RED:
982 case powerup_type_t::POW_KEY_GOLD:
983 case powerup_type_t::POW_MISSILE_1:
984 case powerup_type_t::POW_MISSILE_4:
985 case powerup_type_t::POW_QUAD_FIRE:
986 case powerup_type_t::POW_PROXIMITY_WEAPON:
987 case powerup_type_t::POW_HOMING_AMMO_1:
988 case powerup_type_t::POW_HOMING_AMMO_4:
989 case powerup_type_t::POW_SMARTBOMB_WEAPON:
990 case powerup_type_t::POW_MEGA_WEAPON:
991 case powerup_type_t::POW_VULCAN_AMMO:
992 case powerup_type_t::POW_TURBO:
993 case powerup_type_t::POW_INVULNERABILITY:
994 case powerup_type_t::POW_MEGAWOW:
995 #if DXX_BUILD_DESCENT == 2
996 case powerup_type_t::POW_SUPER_LASER:
997 case powerup_type_t::POW_FULL_MAP:
998 case powerup_type_t::POW_CONVERTER:
999 case powerup_type_t::POW_AMMO_RACK:
1000 case powerup_type_t::POW_AFTERBURNER:
1001 case powerup_type_t::POW_HEADLIGHT:
1002 case powerup_type_t::POW_SMISSILE1_1:
1003 case powerup_type_t::POW_SMISSILE1_4:
1004 case powerup_type_t::POW_GUIDED_MISSILE_1:
1005 case powerup_type_t::POW_GUIDED_MISSILE_4:
1006 case powerup_type_t::POW_SMART_MINE:
1007 case powerup_type_t::POW_MERCURY_MISSILE_1:
1008 case powerup_type_t::POW_MERCURY_MISSILE_4:
1009 case powerup_type_t::POW_EARTHSHAKER_MISSILE:
1010 case powerup_type_t::POW_FLAG_BLUE:
1011 case powerup_type_t::POW_FLAG_RED:
1012 case powerup_type_t::POW_HOARD_ORB:
1013 #endif
1014 break;
1015 }
1016
1017 // Don't drop vulcan ammo if player maxed out.
1018 auto &player_info{get_local_plrobj().ctype.player_info};
1019 if ((weapon_index_uses_vulcan_ammo(weapon_index) || del_obj.contains.id.powerup == powerup_type_t::POW_VULCAN_AMMO) &&
1020 player_info.vulcan_ammo >= VULCAN_AMMO_MAX)
1021 del_obj.contains.count = 0;
1022 else if (weapon_index != unset_weapon_index)
1023 {
1024 if (has_weapon(player_has_primary_weapon(player_info, weapon_index)) || weapon_nearby(vcobjptridx, vcsegptr, del_obj, del_obj.contains.id.powerup) != nullptr)
1025 {
1026 if (d_rand() > 16384) {
1027 #if DXX_BUILD_DESCENT == 1
1028 del_obj.contains.count = 1;
1029 #endif
1030 del_obj.contains.type = contained_object_type::powerup;
1031 if (weapon_index_uses_vulcan_ammo(weapon_index)) {
1032 del_obj.contains.id.powerup = powerup_type_t::POW_VULCAN_AMMO;
1033 }
1034 else {
1035 del_obj.contains.id.powerup = powerup_type_t::POW_ENERGY;
1036 }
1037 } else {
1038 #if DXX_BUILD_DESCENT == 1
1039 del_obj.contains.count = 0;
1040 #elif DXX_BUILD_DESCENT == 2
1041 del_obj.contains.type = contained_object_type::powerup;
1042 del_obj.contains.id.powerup = powerup_type_t::POW_SHIELD_BOOST;
1043 #endif
1044 }
1045 }
1046 } else if (del_obj.contains.id.powerup == powerup_type_t::POW_QUAD_FIRE)
1047 {
1048 if ((player_info.powerup_flags & PLAYER_FLAGS_QUAD_LASERS) || weapon_nearby(vcobjptridx, vcsegptr, del_obj, del_obj.contains.id.powerup) != nullptr)
1049 {
1050 if (d_rand() > 16384) {
1051 #if DXX_BUILD_DESCENT == 1
1052 del_obj.contains.count = 1;
1053 #endif
1054 del_obj.contains.type = contained_object_type::powerup;
1055 del_obj.contains.id.powerup = powerup_type_t::POW_ENERGY;
1056 } else {
1057 #if DXX_BUILD_DESCENT == 1
1058 del_obj.contains.count = 0;
1059 #elif DXX_BUILD_DESCENT == 2
1060 del_obj.contains.type = contained_object_type::powerup;
1061 del_obj.contains.id.powerup = powerup_type_t::POW_SHIELD_BOOST;
1062 #endif
1063 }
1064 }
1065 }
1066
1067 // If this robot was gated in by the boss and it now contains energy, make it contain nothing,
1068 // else the room gets full of energy.
1069 if (del_obj.matcen_creator == BOSS_GATE_MATCEN_NUM && del_obj.contains.id.powerup == powerup_type_t::POW_ENERGY)
1070 del_obj.contains.count = 0;
1071
1072 // Change multiplayer extra-lives into invulnerability
1073 if ((Game_mode & GM_MULTI) && (del_obj.contains.id.powerup == powerup_type_t::POW_EXTRA_LIFE))
1074 {
1075 del_obj.contains.id.powerup = powerup_type_t::POW_INVULNERABILITY;
1076 }
1077 }
1078
1079 imobjptridx_t drop_powerup(d_level_unique_object_state &LevelUniqueObjectState, const d_level_shared_segment_state &LevelSharedSegmentState, d_level_unique_segment_state &LevelUniqueSegmentState, const d_vclip_array &Vclip, powerup_type_t id, const vms_vector &init_vel, const vms_vector &pos, const vmsegptridx_t segnum, const bool player)
1080 {
1081 const auto old_mag{vm_vec_mag_quick(init_vel)};
1082 int rand_scale;
1083
1084 // We want powerups to move more in network mode.
1085 if ((Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_ROBOTS)) {
1086 rand_scale = 4;
1087 // extra life powerups are converted to invulnerability in multiplayer, for what is an extra life, anyway?
1088 if (id == powerup_type_t::POW_EXTRA_LIFE)
1089 id = powerup_type_t::POW_INVULNERABILITY;
1090 } else
1091 rand_scale = 2;
1092
1093 if (Game_mode & GM_MULTI)
1094 {
1095 if (Net_create_loc >= MAX_NET_CREATE_OBJECTS)
1096 {
1097 con_printf(CON_URGENT, DXX_STRINGIZE_FL("%s", __LINE__, "unable to record network object; Net_create_loc=%u"), __FILE__, Net_create_loc);
1098 return object_none;
1099 }
1100 #if DXX_BUILD_DESCENT == 2
1101 if ((Game_mode & GM_NETWORK) && Network_status == network_state::endlevel)
1102 return object_none;
1103 #endif
1104 }
1105 const auto &&objp{obj_create(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, OBJ_POWERUP, underlying_value(id), segnum, pos, &vmd_identity_matrix, Powerup_info[id].size, object::control_type::powerup, object::movement_type::physics, render_type::RT_POWERUP)};
1106
1107 if (objp == object_none)
1108 return objp;
1109 auto &obj{*objp};
1110 #if DXX_BUILD_DESCENT == 2
1111 if (player)
1112 obj.flags |= OF_PLAYER_DROPPED;
1113 #endif
1114
1115 if (Game_mode & GM_MULTI)
1116 {
1117 Net_create_objnums[Net_create_loc++] = objp;
1118 }
1119
1120 // Give keys zero velocity so they can be tracked better in multi
1121 auto &object_velocity{obj.mtype.phys_info.velocity};
1122 if ((Game_mode & GM_MULTI) && (id >= powerup_type_t::POW_KEY_BLUE) && (id <= powerup_type_t::POW_KEY_GOLD))
1123 object_velocity = {};
1124 else
1125 {
1126 object_velocity = init_vel;
1127 const auto random_velocity_adjustment = [old_mag, rand_scale]() {
1128 return fixmul(old_mag + F1_0 * 32, d_rand() * rand_scale - 16384 * rand_scale);
1129 };
1130 object_velocity.x += random_velocity_adjustment();
1131 object_velocity.y += random_velocity_adjustment();
1132 object_velocity.z += random_velocity_adjustment();
1133 }
1134
1135 obj.mtype.phys_info.drag = 512; //1024;
1136 obj.mtype.phys_info.mass = F1_0;
1137
1138 obj.mtype.phys_info.flags = PF_BOUNCE;
1139
1140 obj.rtype.vclip_info.vclip_num = Powerup_info[id].vclip_num;
1141 obj.rtype.vclip_info.frametime = Vclip[obj.rtype.vclip_info.vclip_num].frame_time;
1142 obj.rtype.vclip_info.framenum = 0;
1143
1144 switch (id)
1145 {
1146 case powerup_type_t::POW_MISSILE_1:
1147 case powerup_type_t::POW_MISSILE_4:
1148 case powerup_type_t::POW_SHIELD_BOOST:
1149 case powerup_type_t::POW_ENERGY:
1150 obj.lifeleft = (d_rand() + F1_0*3) * 64; // Lives for 3 to 3.5 binary minutes (a binary minute is 64 seconds)
1151 if (Game_mode & GM_MULTI)
1152 obj.lifeleft /= 2;
1153 break;
1154 #if DXX_BUILD_DESCENT == 2
1155 case powerup_type_t::POW_OMEGA_WEAPON:
1156 if (!player)
1157 obj.ctype.powerup_info.count = MAX_OMEGA_CHARGE;
1158 break;
1159 case powerup_type_t::POW_GAUSS_WEAPON:
1160 #endif
1161 case powerup_type_t::POW_VULCAN_WEAPON:
1162 if (!player)
1163 obj.ctype.powerup_info.count = VULCAN_WEAPON_AMMO_AMOUNT;
1164 break;
1165 default:
1166 break;
1167 }
1168 return objp;
1169 }
1170
1171 bool drop_powerup(d_level_unique_object_state &LevelUniqueObjectState, const d_level_shared_segment_state &LevelSharedSegmentState, d_level_unique_segment_state &LevelUniqueSegmentState, const d_vclip_array &Vclip, const powerup_type_t id, const unsigned num, const vms_vector &init_vel, const vms_vector &pos, const vmsegptridx_t segnum, const bool player)
1172 {
1173 bool created{false};
1174 for (const auto i : xrange(num))
1175 {
1176 (void)i;
1177 const auto &&obj{drop_powerup(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, Vclip, id, init_vel, pos, segnum, player)};
1178 if (obj == object_none)
1179 /* If one drop failed, assume every additional drop will also fail.
1180 */
1181 break;
1182 created = true;
1183 }
1184 return created;
1185 }
1186
1187 namespace {
1188
1189 static bool drop_robot_egg(const d_robot_info_array &Robot_info, const contained_object_type type, const contained_object_id id, const unsigned num, const vms_vector &init_vel, const vms_vector &pos, const vmsegptridx_t segnum)
1190 {
1191 if (!num)
1192 return false;
1193 switch (type)
1194 {
1195 case contained_object_type::powerup:
1196 return drop_powerup(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, Vclip, id.powerup, num, init_vel, pos, segnum, false);
1197 case contained_object_type::robot:
1198 break;
1199 default:
1200 con_printf(CON_URGENT, DXX_STRINGIZE_FL(__FILE__, __LINE__, "ignoring invalid object type; expected OBJ_POWERUP or OBJ_ROBOT, got type=%i, id=%i"), underlying_value(type), underlying_value(id.powerup));
1201 return false;
1202 }
1203 auto &Polygon_models{LevelSharedPolygonModelState.Polygon_models};
1204 bool created{false};
1205 const auto [normalized_init_magnitude, normalized_init_vel]{vm_vec_normalize_quick_with_magnitude(init_vel)};
1206 const fix scale_magnitude{(F1_0 * 32 + normalized_init_magnitude) * 2};
1207 for (const auto count : xrange(num))
1208 {
1209 (void)count;
1210 auto new_pos{pos};
1211 // This is dangerous, could be outside mine.
1212 // new_pos.x += (d_rand()-16384)*8;
1213 // new_pos.y += (d_rand()-16384)*7;
1214 // new_pos.z += (d_rand()-16384)*6;
1215
1216 const auto rid{id.robot};
1217 auto &robptr{Robot_info[rid]};
1218 const auto &&objp{robot_create(Robot_info, rid, segnum, new_pos, &vmd_identity_matrix, Polygon_models[robptr.model_num].rad, ai_behavior::AIB_NORMAL)};
1219 if (objp == object_none)
1220 break;
1221 auto &obj{*objp};
1222 created = true;
1223 ++LevelUniqueObjectState.accumulated_robots;
1224 ++GameUniqueState.accumulated_robots;
1225 if (Game_mode & GM_MULTI)
1226 {
1227 Net_create_objnums[Net_create_loc++] = objp;
1228 }
1229 //Set polygon-object-specific data
1230
1231 obj.rtype.pobj_info.model_num = robptr.model_num;
1232 obj.rtype.pobj_info.subobj_flags = 0;
1233
1234 //set Physics info
1235 obj.mtype.phys_info.velocity = /* scaled_perturbed_new_velocity = */ vm_vec_copy_scale(
1236 /* normalized_perturbed_new_velocity = */ vm_vec_normalized_quick(
1237 /* perturbed_new_velocity = */ vms_vector{
1238 .x = normalized_init_vel.x + (d_rand() - 16384) * 2,
1239 .y = normalized_init_vel.y + (d_rand() - 16384) * 2,
1240 .z = normalized_init_vel.z + (d_rand() - 16384) * 2
1241 }
1242 ),
1243 scale_magnitude
1244 );
1245
1246 obj.mtype.phys_info.mass = robptr.mass;
1247 obj.mtype.phys_info.drag = robptr.drag;
1248
1249 obj.mtype.phys_info.flags |= (PF_LEVELLING);
1250
1251 obj.shields = robptr.strength;
1252
1253 ai_local *const ailp{&obj.ctype.ai_info.ail};
1254 ailp->player_awareness_type = player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION;
1255 ailp->player_awareness_time = F1_0*3;
1256 obj.ctype.ai_info.CURRENT_STATE = AIS_LOCK;
1257 obj.ctype.ai_info.GOAL_STATE = AIS_LOCK;
1258 obj.ctype.ai_info.REMOTE_OWNER = -1;
1259 }
1260
1261 #if DXX_BUILD_DESCENT == 2
1262 // At JasenW's request, robots which contain robots
1263 // sometimes drop shields.
1264 if (d_rand() > 16384)
1265 {
1266 const auto &&objp{drop_powerup(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, Vclip, powerup_type_t::POW_SHIELD_BOOST, init_vel, pos, segnum, false)};
1267 if (objp != object_none)
1268 created = true;
1269 }
1270 #endif
1271 return created;
1272 }
1273
1274 #if DXX_BUILD_DESCENT == 2
1275 static bool skip_create_egg_powerup(const object &player, powerup_type_t powerup)
1276 {
1277 fix current;
1278 auto &player_info{player.ctype.player_info};
1279 if (powerup == powerup_type_t::POW_SHIELD_BOOST)
1280 current = player.shields;
1281 else if (powerup == powerup_type_t::POW_ENERGY)
1282 current = player_info.energy;
1283 else
1284 return false;
1285 int limit;
1286 if (current >= i2f(150))
1287 limit = 8192;
1288 else if (current >= i2f(100))
1289 limit = 16384;
1290 else
1291 return false;
1292 return d_rand() > limit;
1293 }
1294 #endif
1295
1296 }
1297
1298 bool object_create_robot_egg(const d_robot_info_array &Robot_info, const contained_object_type type, const contained_object_id id, const unsigned num, const vms_vector &init_vel, const vms_vector &pos, const vmsegptridx_t segnum)
1299 {
1300 #if DXX_BUILD_DESCENT == 2
1301 auto &Objects{LevelUniqueObjectState.Objects};
1302 auto &vmobjptr{Objects.vmptr};
1303 if (!(Game_mode & GM_MULTI))
1304 {
1305 if (type == contained_object_type::powerup)
1306 {
1307 if (skip_create_egg_powerup(get_local_plrobj(), id.powerup))
1308 return false;
1309 }
1310 }
1311 #endif
1312 return drop_robot_egg(Robot_info, type, id, num, init_vel, pos, segnum);
1313 }
1314
1315 bool object_create_robot_egg(const d_robot_info_array &Robot_info, object_base &objp)
1316 {
1317 return object_create_robot_egg(Robot_info, objp.contains.type, objp.contains.id, objp.contains.count, objp.mtype.phys_info.velocity, objp.pos, vmsegptridx(objp.segnum));
1318 }
1319
1320 // -------------------------------------------------------------------------------------------------------
1321 // Put count objects of type type (eg, powerup), id = id (eg, energy) into *objp, then drop them! Yippee!
1322 // Returns created object number.
1323 imobjptridx_t call_object_create_egg(const object_base &objp, const powerup_type_t id)
1324 {
1325 return drop_powerup(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, Vclip, id, objp.mtype.phys_info.velocity, objp.pos, vmsegptridx(objp.segnum), true);
1326 }
1327
1328 void call_object_create_egg(const object_base &objp, const unsigned count, const powerup_type_t id)
1329 {
1330 if (count > 0) {
1331 drop_powerup(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, Vclip, id, count, objp.mtype.phys_info.velocity, objp.pos, vmsegptridx(objp.segnum), true);
1332 }
1333 }
1334
1335 //what vclip does this explode with?
1336 vclip_index get_explosion_vclip(const d_robot_info_array &Robot_info, const object_base &obj, explosion_vclip_stage stage)
1337 {
1338 if (obj.type == OBJ_ROBOT)
1339 {
1340 const auto vclip_ptr = stage == explosion_vclip_stage::s0
1341 ? &robot_info::exp1_vclip_num
1342 : &robot_info::exp2_vclip_num;
1343 const auto vclip_num{Robot_info[get_robot_id(obj)].*vclip_ptr};
1344 if (Vclip.valid_index(vclip_num))
1345 return vclip_num;
1346 }
1347 else if (obj.type == OBJ_PLAYER)
1348 {
1349 if (const auto expl_vclip_num{Player_ship->expl_vclip_num}; Vclip.valid_index(expl_vclip_num))
1350 return expl_vclip_num;
1351 }
1352
1353 return vclip_index::small_explosion; //default
1354 }
1355
1356 namespace {
1357
1358 //blow up a polygon model
1359 static void explode_model(object_base &obj)
1360 {
1361 assert(obj.render_type == render_type::RT_POLYOBJ);
1362
1363 const auto poly_model_num{obj.rtype.pobj_info.model_num};
1364 const auto dying_model_num{Dying_modelnums[poly_model_num]};
1365 const auto model_num{(dying_model_num != polygon_model_index::None)
1366 ? (obj.rtype.pobj_info.model_num = dying_model_num)
1367 : poly_model_num
1368 };
1369 auto &pm{LevelSharedPolygonModelState.Polygon_models[model_num]};
1370 const auto n_models{pm.n_models};
1371 if (n_models > 1) {
1372 /* Limit the range to the first `n_models`, since later elements are
1373 * not valid for this model.
1374 *
1375 * Skip over the first element, because Descent has always done that.
1376 */
1377 for (const auto &&[i, submodel_rad] : enumerate(std::span(pm.submodel_rads).first(n_models).template subspan<1>(), submodel_index{})
1378 )
1379 {
1380 #if DXX_BUILD_DESCENT == 2
1381 if (!(i == submodel_index{5} && obj.type == OBJ_ROBOT && get_robot_id(obj) == robot_id::energy_bandit)) //energy sucker energy part
1382 #endif
1383 object_create_debris(vmsegptridx, obj, i, submodel_rad);
1384 }
1385
1386 //make parent object only draw center part
1387 obj.rtype.pobj_info.subobj_flags = 1;
1388 }
1389 }
1390
1391 //if the object has a destroyed model, switch to it. Otherwise, delete it.
1392 static void maybe_delete_object(object_base &del_obj)
1393 {
1394 const auto dead_modelnum{Dead_modelnums[del_obj.rtype.pobj_info.model_num]};
1395 if (dead_modelnum != polygon_model_index::None)
1396 {
1397 del_obj.rtype.pobj_info.model_num = dead_modelnum;
1398 del_obj.flags |= OF_DESTROYED;
1399 }
1400 else { //normal, multi-stage explosion
1401 if (del_obj.type == OBJ_PLAYER)
1402 del_obj.render_type = render_type::RT_NONE;
1403 else
1404 del_obj.flags |= OF_SHOULD_BE_DEAD;
1405 }
1406 }
1407
1408 }
1409
1410 // -------------------------------------------------------------------------------------------------------
1411 //blow up an object. Takes the object to destroy, and the point of impact
1412 void explode_object(d_level_unique_object_state &LevelUniqueObjectState, const d_robot_info_array &Robot_info, const d_level_shared_segment_state &LevelSharedSegmentState, d_level_unique_segment_state &LevelUniqueSegmentState, const vmobjptridx_t hitobj, const fix delay_time)
1413 {
1414 if (hitobj->flags & OF_EXPLODING) return;
1415
1416 if (delay_time) { //wait a little while before creating explosion
1417 //create a placeholder object to do the delay, with id==-1
1418 const auto &&obj = obj_create(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, OBJ_FIREBALL, -1, vmsegptridx(hitobj->segnum), hitobj->pos, &vmd_identity_matrix, 0,
1419 object::control_type::explosion, object::movement_type::None, render_type::RT_NONE);
1420 if (obj == object_none ) {
1421 maybe_delete_object(hitobj); //no explosion, die instantly
1422 Int3();
1423 return;
1424 }
1425 //now set explosion-specific data
1426
1427 obj->lifeleft = delay_time;
1428 obj->ctype.expl_info.delete_objnum = hitobj;
1429 obj->ctype.expl_info.delete_time = -1;
1430 obj->ctype.expl_info.spawn_time = 0;
1431
1432 }
1433 else {
1434 const auto vclip_num{get_explosion_vclip(Robot_info, hitobj, explosion_vclip_stage::s0)};
1435 const imobjptr_t expl_obj{object_create_explosion_without_damage(Vclip, vmsegptridx(hitobj->segnum), hitobj->pos, fixmul(hitobj->size, EXPLOSION_SCALE), vclip_num)};
1436 if (! expl_obj) {
1437 maybe_delete_object(hitobj); //no explosion, die instantly
1438 return;
1439 }
1440
1441 //don't make debris explosions have physics, because they often
1442 //happen when the debris has hit the wall, so the fireball is trying
1443 //to move into the wall, which shows off FVI problems.
1444 if (hitobj->type!=OBJ_DEBRIS && hitobj->movement_source==object::movement_type::physics) {
1445 expl_obj->movement_source = object::movement_type::physics;
1446 expl_obj->mtype.phys_info = hitobj->mtype.phys_info;
1447 }
1448
1449 if (hitobj->render_type == render_type::RT_POLYOBJ && hitobj->type != OBJ_DEBRIS)
1450 explode_model(hitobj);
1451
1452 maybe_delete_object(hitobj);
1453 }
1454
1455 hitobj->flags |= OF_EXPLODING; //say that this is blowing up
1456 hitobj->control_source = object::control_type::None; //become inert while exploding
1457
1458 }
1459
1460 //do whatever needs to be done for this piece of debris for this frame
1461 void do_debris_frame(const d_robot_info_array &Robot_info, const vmobjptridx_t obj)
1462 {
1463 assert(obj->control_source == object::control_type::debris);
1464
1465 if (obj->lifeleft < 0)
1466 explode_object(LevelUniqueObjectState, Robot_info, LevelSharedSegmentState, LevelUniqueSegmentState, obj, 0);
1467 }
1468
1469 //do whatever needs to be done for this explosion for this frame
1470 void do_explosion_sequence(const d_robot_info_array &Robot_info, object &obj)
1471 {
1472 auto &Objects{LevelUniqueObjectState.Objects};
1473 auto &vmobjptr{Objects.vmptr};
1474 auto &vmobjptridx{Objects.vmptridx};
1475 assert(obj.control_source == object::control_type::explosion);
1476
1477 //See if we should die of old age
1478 if (obj.lifeleft <= 0 ) { // We died of old age
1479 obj.flags |= OF_SHOULD_BE_DEAD;
1480 obj.lifeleft = 0;
1481 }
1482
1483 //See if we should create a secondary explosion
1484 if (obj.lifeleft <= obj.ctype.expl_info.spawn_time) {
1485 auto del_obj{vmobjptridx(obj.ctype.expl_info.delete_objnum)};
1486 auto &spawn_pos{del_obj->pos};
1487 Assert(del_obj->type==OBJ_ROBOT || del_obj->type==OBJ_CLUTTER || del_obj->type==OBJ_CNTRLCEN || del_obj->type == OBJ_PLAYER);
1488 Assert(del_obj->segnum != segment_none);
1489
1490 const auto &&expl_obj{[&]{
1491 const auto vclip_num{get_explosion_vclip(Robot_info, del_obj, explosion_vclip_stage::s1)};
1492 #if DXX_BUILD_DESCENT == 2
1493 if (del_obj->type == OBJ_ROBOT)
1494 {
1495 const auto &ri{Robot_info[get_robot_id(del_obj)]};
1496 if (ri.badass)
1497 return object_create_badass_explosion(Robot_info, object_none, vmsegptridx(del_obj->segnum), spawn_pos, fixmul(del_obj->size, EXPLOSION_SCALE), vclip_num, F1_0 * ri.badass, i2f(4) * ri.badass, i2f(35) * ri.badass, object_none);
1498 }
1499 #endif
1500 return object_create_explosion_without_damage(Vclip, vmsegptridx(del_obj->segnum), spawn_pos, fixmul(del_obj->size, EXPLOSION_SCALE), vclip_num);
1501 }()};
1502
1503 if (del_obj->contains.count > 0 && !(Game_mode & GM_MULTI)) { // Multiplayer handled outside of this code!!
1504 // If dropping a weapon that the player has, drop energy instead, unless it's vulcan, in which case drop vulcan ammo.
1505 if (del_obj->contains.type == contained_object_type::powerup)
1506 maybe_replace_powerup_with_energy(del_obj);
1507 object_create_robot_egg(Robot_info, del_obj);
1508 } else if ((del_obj->type == OBJ_ROBOT) && !(Game_mode & GM_MULTI)) { // Multiplayer handled outside this code!!
1509 auto &robptr{Robot_info[get_robot_id(del_obj)]};
1510 if (const auto contains_count{robptr.contains.count})
1511 {
1512 if (((d_rand() * 16) >> 15) < robptr.contains_prob) {
1513 del_obj->contains = robptr.contains;
1514 del_obj->contains.count = ((d_rand() * contains_count) >> 15) + 1;
1515 maybe_replace_powerup_with_energy(del_obj);
1516 object_create_robot_egg(Robot_info, del_obj);
1517 }
1518 }
1519 #if DXX_BUILD_DESCENT == 2
1520 if (robot_is_thief(robptr))
1521 drop_stolen_items_local(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, Vclip, vmsegptridx(del_obj->segnum), del_obj->mtype.phys_info.velocity, del_obj->pos, LevelUniqueObjectState.ThiefState.Stolen_items);
1522 else if (robot_is_companion(robptr))
1523 {
1524 DropBuddyMarker(del_obj);
1525 }
1526 #endif
1527 }
1528
1529 auto &robptr{Robot_info[get_robot_id(del_obj)]};
1530 if (const auto exp2_sound_num{robptr.exp2_sound_num}; exp2_sound_num != sound_effect::None)
1531 digi_link_sound_to_pos(exp2_sound_num, vmsegptridx(del_obj->segnum), sidenum_t::WLEFT, spawn_pos, 0, F1_0);
1532 //PLAY_SOUND_3D( Robot_info[del_obj->id].exp2_sound_num, spawn_pos, del_obj->segnum );
1533
1534 obj.ctype.expl_info.spawn_time = -1;
1535
1536 //make debris
1537 if (del_obj->render_type == render_type::RT_POLYOBJ)
1538 explode_model(del_obj); //explode a polygon model
1539
1540 //set some parm in explosion
1541 //If num_objects < MAX_USED_OBJECTS, expl_obj could be set to dead before this setting causing the delete_obj not to be removed. If so, directly delete del_obj
1542 if (expl_obj && !(expl_obj->flags & OF_SHOULD_BE_DEAD))
1543 {
1544 if (del_obj->movement_source == object::movement_type::physics) {
1545 expl_obj->movement_source = object::movement_type::physics;
1546 expl_obj->mtype.phys_info = del_obj->mtype.phys_info;
1547 }
1548
1549 expl_obj->ctype.expl_info.delete_time = expl_obj->lifeleft/2;
1550 expl_obj->ctype.expl_info.delete_objnum = del_obj;
1551 }
1552 else {
1553 maybe_delete_object(del_obj);
1554 }
1555
1556 }
1557
1558 //See if we should delete an object
1559 if (obj.lifeleft <= obj.ctype.expl_info.delete_time) {
1560 const auto &&del_obj{vmobjptr(obj.ctype.expl_info.delete_objnum)};
1561 obj.ctype.expl_info.delete_time = -1;
1562 maybe_delete_object(del_obj);
1563 }
1564 }
1565
1566 #define EXPL_WALL_TIME UINT16_MAX
1567 #define EXPL_WALL_TOTAL_FIREBALLS 32
1568 #if DXX_BUILD_DESCENT == 1
1569 #define EXPL_WALL_FIREBALL_SIZE 0x48000 //smallest size
1570 #elif DXX_BUILD_DESCENT == 2
1571 #define EXPL_WALL_FIREBALL_SIZE (0x48000*6/10) //smallest size
1572 #endif
1573
1574 //explode the given wall
1575 void explode_wall(fvcvertptr &vcvertptr, const vcsegptridx_t segnum, const sidenum_t sidenum, wall &w)
1576 {
1577 if (w.flags & wall_flag::exploding)
1578 /* Already exploding */
1579 return;
1580 w.explode_time_elapsed = 0;
1581 w.flags |= wall_flag::exploding;
1582 ++ Num_exploding_walls;
1583
1584 //play one long sound for whole door wall explosion
1585 digi_link_sound_to_pos(sound_effect::SOUND_EXPLODING_WALL, segnum, sidenum, compute_center_point_on_side(vcvertptr, segnum, sidenum), 0, F1_0);
1586 }
1587
1588 unsigned do_exploding_wall_frame(const d_robot_info_array &Robot_info, wall &w1)
1589 {
1590 auto &LevelSharedVertexState{LevelSharedSegmentState.get_vertex_state()};
1591 auto &Vertices{LevelSharedVertexState.get_vertices()};
1592 auto &WallAnims{GameSharedState.WallAnims};
1593 assert(w1.flags & wall_flag::exploding);
1594 fix w1_explode_time_elapsed{w1.explode_time_elapsed};
1595 const fix oldfrac{fixdiv(w1_explode_time_elapsed, EXPL_WALL_TIME)};
1596
1597 w1_explode_time_elapsed += FrameTime;
1598 if (w1_explode_time_elapsed > EXPL_WALL_TIME)
1599 w1_explode_time_elapsed = EXPL_WALL_TIME;
1600 w1.explode_time_elapsed = w1_explode_time_elapsed;
1601
1602 const auto w1sidenum{w1.sidenum};
1603 const auto &&seg{vmsegptridx(w1.segnum)};
1604 unsigned walls_updated{0};
1605 if (w1_explode_time_elapsed > (EXPL_WALL_TIME * 3) / 4)
1606 {
1607 const auto &&csegp{seg.absolute_sibling(seg->shared_segment::children[w1sidenum])};
1608 const auto cside{find_connect_side(seg, csegp)};
1609
1610 const auto a{w1.clip_num};
1611 auto &wa{WallAnims[a]};
1612 const auto n{wa.num_frames};
1613 wall_set_tmap_num(wa, seg, w1sidenum, csegp, cside, n - 1);
1614
1615 auto &Walls{LevelUniqueWallSubsystemState.Walls};
1616 auto &vmwallptr{Walls.vmptr};
1617
1618 auto cwall_num{csegp->shared_segment::sides[cside].wall_num};
1619 if (cwall_num != wall_none)
1620 {
1621 auto &w2{*vmwallptr(cwall_num)};
1622 assert(&w1 != &w2);
1623 w2.flags |= wall_flag::blasted;
1624 assert((w1.flags & wall_flag::exploding) || (w2.flags & wall_flag::exploding));
1625 if (w1_explode_time_elapsed >= EXPL_WALL_TIME && w2.flags & wall_flag::exploding)
1626 {
1627 w2.flags &= ~wall_flag::exploding;
1628 ++ walls_updated;
1629 }
1630 }
1631 else
1632 assert(w1.flags & wall_flag::exploding);
1633
1634 w1.flags |= wall_flag::blasted;
1635 if (w1_explode_time_elapsed >= EXPL_WALL_TIME && w1.flags & wall_flag::exploding)
1636 {
1637 w1.flags &= ~wall_flag::exploding;
1638 ++ walls_updated;
1639 }
1640
1641 Num_exploding_walls -= walls_updated;
1642 }
1643
1644 const fix newfrac{fixdiv(w1_explode_time_elapsed, EXPL_WALL_TIME)};
1645
1646 const int old_count{f2i(EXPL_WALL_TOTAL_FIREBALLS * fixmul(oldfrac, oldfrac))};
1647 const int new_count{f2i(EXPL_WALL_TOTAL_FIREBALLS * fixmul(newfrac, newfrac))};
1648 if (old_count >= new_count)
1649 /* for loop would exit with zero iterations if this `if` is
1650 * true. Skip the setup for the loop in that case.
1651 */
1652 return walls_updated;
1653
1654 const auto vertnum_list{get_side_verts(seg, w1sidenum)};
1655
1656 auto &vcvertptr{Vertices.vcptr};
1657 auto &v0{*vcvertptr(vertnum_list[0])};
1658 auto &v1{*vcvertptr(vertnum_list[1])};
1659 auto &v2{*vcvertptr(vertnum_list[2])};
1660
1661 const auto &&vv0{vm_vec_build_sub(v0, v1)};
1662 const auto &&vv1{vm_vec_build_sub(v2, v1)};
1663
1664 //now create all the next explosions
1665
1666 auto &w1normal0{seg->shared_segment::sides[w1sidenum].normals[0]};
1667 for (int e{old_count}; e < new_count; ++e)
1668 {
1669 //calc expl position
1670
1671 auto pos{vm_vec_scale_add(v1, vv0, d_rand() * 2)};
1672 vm_vec_scale_add2(pos,vv1,d_rand() * 2);
1673
1674 const fix size{EXPL_WALL_FIREBALL_SIZE + (2 * EXPL_WALL_FIREBALL_SIZE * e / EXPL_WALL_TOTAL_FIREBALLS)};
1675
1676 //fireballs start away from door, with subsequent ones getting closer
1677 vm_vec_scale_add2(pos, w1normal0, size * (EXPL_WALL_TOTAL_FIREBALLS - e) / EXPL_WALL_TOTAL_FIREBALLS);
1678
1679 if (e & 3) //3 of 4 are normal
1680 object_create_explosion_without_damage(Vclip, seg, pos, size, vclip_index::small_explosion);
1681 else
1682 object_create_badass_explosion(Robot_info, object_none, seg, pos,
1683 size,
1684 vclip_index::small_explosion,
1685 i2f(4), // damage strength
1686 i2f(20), // damage radius
1687 i2f(50), // damage force
1688 object_none // parent id
1689 );
1690 }
1691 return walls_updated;
1692 }
1693
1694 #if DXX_BUILD_DESCENT == 2
1695 //creates afterburner blobs behind the specified object
1696 void drop_afterburner_blobs(object &obj, int count, fix size_scale, fix lifetime)
1697 {
1698 auto pos_left{vm_vec_scale_add(obj.pos, obj.orient.fvec, -obj.size)};
1699 vm_vec_scale_add2(pos_left, obj.orient.rvec, -obj.size/4);
1700 const auto pos_right{vm_vec_scale_add(pos_left, obj.orient.rvec, obj.size / 2)};
1701
1702 if (count == 1)
1703 pos_left = vm_vec_build_avg(pos_left, pos_right);
1704
1705 const auto &&objseg{Segments.vmptridx(obj.segnum)};
1706 {
1707 const auto &&segnum{find_point_seg(LevelSharedSegmentState, LevelUniqueSegmentState, pos_left, objseg)};
1708 if (segnum != segment_none)
1709 object_create_explosion_without_damage(Vclip, segnum, pos_left, size_scale, vclip_index::afterburner_blob);
1710 }
1711
1712 if (count > 1) {
1713 const auto &&segnum{find_point_seg(LevelSharedSegmentState, LevelUniqueSegmentState, pos_right, objseg)};
1714 if (segnum != segment_none) {
1715 const auto &&blob_obj{object_create_explosion_without_damage(Vclip, segnum, pos_right, size_scale, vclip_index::afterburner_blob)};
1716 if (lifetime != -1 && blob_obj != object_none)
1717 blob_obj->lifeleft = lifetime;
1718 }
1719 }
1720 }
1721
1722 /*
1723 * reads n expl_wall structs from a PHYSFS_File and swaps if specified
1724 */
1725 void expl_wall_read_n_swap(fvmwallptr &vmwallptr, PHYSFS_File *const fp, const physfsx_endian swap, const unsigned count)
1726 {
1727 assert(!Num_exploding_walls);
1728 unsigned num_exploding_walls{0};
1729 /* Legacy versions of Descent always write a fixed number of
1730 * entries, even if some or all of those entries are empty. This
1731 * loop needs to count how many entries were valid, as well as load
1732 * them into the correct walls.
1733 */
1734 for (unsigned i{count}; i--;)
1735 {
1736 disk_expl_wall d;
1737 PHYSFSX_readBytes(fp, &d, sizeof(d));
1738 if (swap != physfsx_endian::native)
1739 {
1740 d.segnum = SWAPINT(d.segnum);
1741 d.sidenum = SWAPINT(d.sidenum);
1742 d.time = SWAPINT(d.time);
1743 }
1744 if (const auto s{vcsegidx_t::check_nothrow_index(d.segnum)})
1745 for (const vcsegidx_t dseg{*s}; auto &w : vmwallptr)
1746 {
1747 if (w.segnum != dseg)
1748 continue;
1749 if (underlying_value(w.sidenum) != d.sidenum)
1750 continue;
1751 w.flags |= wall_flag::exploding;
1752 w.explode_time_elapsed = d.time;
1753 ++ num_exploding_walls;
1754 break;
1755 }
1756 }
1757 Num_exploding_walls = num_exploding_walls;
1758 }
1759
1760 void expl_wall_write(fvcwallptr &vcwallptr, PHYSFS_File *const fp)
1761 {
1762 const unsigned num_exploding_walls{Num_exploding_walls};
1763 PHYSFSX_writeBytes(fp, &num_exploding_walls, sizeof(unsigned));
1764 for (auto &e : vcwallptr)
1765 {
1766 if (!(e.flags & wall_flag::exploding))
1767 continue;
1768 disk_expl_wall d;
1769 d.segnum = e.segnum;
1770 d.sidenum = underlying_value(e.sidenum);
1771 d.time = e.explode_time_elapsed;
1772 PHYSFSX_writeBytes(fp, &d, sizeof(d));
1773 }
1774 }
1775
1776 // ------------------------------------------------------------------------------------------------------
1777 // Choose segment to recreate thief in.
1778 vmsegidx_t choose_thief_recreation_segment(fvcsegptr &vcsegptr, fvcwallptr &vcwallptr, const vcsegidx_t plrseg)
1779 {
1780 static constexpr std::integral_constant<connected_segment_raw_distances::segment_distance_count_type, 20> thief_max_depth{};
1781 static constexpr std::integral_constant<connected_segment_raw_distances::segment_distance_count_type, thief_max_depth / 2> thief_min_depth{};
1782 static_assert(thief_min_depth >= connected_segment_raw_distances::minimum_supported_max_depth);
1783 const connected_segment_raw_distances rd(vcsegptr, vcwallptr, thief_max_depth, plrseg);
1784 auto mrd{std::minstd_rand(d_rand())};
1785 /* connected_segment_raw_distances explicitly avoids reporting any
1786 * segment with a ->special of segment_special::controlcen, even if that
1787 * segment is in range. Therefore, any returned segment of the
1788 * appropriate distance is usable.
1789 */
1790 static_assert(rd.count_segments_at_depth.valid_index(thief_max_depth));
1791 static_assert(rd.count_segments_at_depth.valid_index(thief_min_depth + 1u));
1792 for (const unsigned candidate_depth : xrange(thief_max_depth, thief_min_depth, xrange_descending()))
1793 {
1794 if (const auto sn = rd.scan_segment_depths(candidate_depth, mrd))
1795 return *sn;
1796 }
1797 /* This can be reached if there are no segments found at any of the
1798 * acceptable depths. If the origin segment is in a small room with
1799 * no passable exits, this can happen.
1800 *
1801 * Give up and pick a completely random segment. This is compatible
1802 * with retail Descent 2.
1803 */
1804 using distribution_type = typename std::underlying_type<segnum_t>::type;
1805 std::uniform_int_distribution uid(distribution_type{0}, static_cast<distribution_type>(Highest_segment_index));
1806 return segnum_t{uid(mrd)};
1807 }
1808 #endif
1809 }