Debian Codegraph @

similar/main/physics.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 flying through the mines
23 *
24 */
25
26
27 #include <stdio.h>
28 #include <stdlib.h>
29
30 #include "joy.h"
31 #include "dxxerror.h"
32
33 #include "inferno.h"
34 #include "segment.h"
35 #include "object.h"
36 #include "physics.h"
37 #include "robot.h"
38 #include "game.h"
39 #include "collide.h"
40 #include "fvi.h"
41 #include "gameseg.h"
42 #include "wall.h"
43 #include "laser.h"
44 #if DXX_BUILD_DESCENT == 2
45 #include "bm.h"
46 #include "player.h"
47 #define MAX_OBJECT_VEL i2f(100)
48 #endif
49
50 #include "d_construct.h"
51 #include "d_levelstate.h"
52 #include "compiler-range_for.h"
53
54 //Global variables for physics system
55
56 constexpr fix ROLL_RATE{0x2000};
57 constexpr fixang DAMP_ANG{0x400}; //min angle to bank
58 constexpr fix TURNROLL_SCALE{0x4ec4/2};
59
60 namespace {
61
62 [[nodiscard]]
63 static fixang multiply_with_clamp_to_fixang(const fix rotvel, const fix frametime)
64 {
65 /* Express the minimum and maximum as `fix` so that the result of `fixmul`
66 * is compared without truncation. After `std::clamp` is applied, conversion
67 * to `fixang` cannot modify the value, because all possible values in
68 * [`min`, `max`] are representable in `fixang`, and `std::clamp` is
69 * guaranteed to return a value in [`min`, `max`].
70 */
71 static constexpr fix min{std::numeric_limits<fixang>::min()};
72 static constexpr fix max{std::numeric_limits<fixang>::max()};
73 return std::clamp<fix>({fixmul(rotvel, frametime)}, {min}, {max});
74 }
75
76 static void do_physics_align_object(object_base &obj)
77 {
78 fix largest_d{INT32_MIN};
79 const shared_side *best_side{nullptr};
80 // bank player according to segment orientation
81
82 //find side of segment that player is most alligned with
83
84 range_for (auto &i, vcsegptr(obj.segnum)->shared_segment::sides)
85 {
86 const auto d{vm_vec_build_dot(i.normals[0], obj.orient.uvec)};
87 if (largest_d < d)
88 {
89 largest_d = d;
90 best_side = &i;
91 }
92 }
93
94 // new player leveling code: use normal of side closest to our up vec
95 if (!best_side)
96 return;
97 const vms_vector desired_upvec{
98 get_side_is_quad(*best_side)
99 ? vm_vec_normalized(vm_vec_build_avg(best_side->normals[0], best_side->normals[1]))
100 : best_side->normals[0]
101 };
102
103 if (labs(vm_vec_build_dot(desired_upvec, obj.orient.fvec)) < f1_0 / 2)
104 {
105 const auto temp_matrix{vm_vector_to_matrix_u(obj.orient.fvec, desired_upvec)};
106
107 auto delta_ang{vm_vec_delta_ang(obj.orient.uvec, temp_matrix.uvec, obj.orient.fvec)};
108 delta_ang += obj.mtype.phys_info.turnroll;
109
110 if (abs(delta_ang) > DAMP_ANG) {
111 const auto uncapped_roll_ang{fixmul(FrameTime, ROLL_RATE)};
112 const fixang roll_ang{
113 (uncapped_roll_ang > abs(delta_ang))
114 ? delta_ang
115 : (delta_ang < 0
116 ? static_cast<fixang>(-uncapped_roll_ang)
117 : static_cast<fixang>(uncapped_roll_ang))
118 };
119 const auto &&rotmat{vm_angles_2_matrix(
120 vms_angvec{
121 .p = fixang{0},
122 .b = roll_ang,
123 .h = fixang{0}
124 })};
125 obj.orient = vm_matrix_x_matrix(obj.orient, rotmat);
126 }
127 }
128 }
129
130 [[nodiscard]]
131 static fixang set_object_turnroll(object_base &obj, const fix frametime)
132 {
133 const fixang desired_bank{multiply_with_clamp_to_fixang({-obj.mtype.phys_info.rotvel.y}, {TURNROLL_SCALE})};
134 if (const fix delta_ang{desired_bank - obj.mtype.phys_info.turnroll})
135 {
136 const fixang raw_max_roll{multiply_with_clamp_to_fixang(ROLL_RATE, frametime)};
137 /* Casting to `fixang` is safe:
138 * - `raw_max_roll` is a positive `fixang`, since `ROLL_RATE` is
139 * positive and `frametime` is positive, so `raw_max_roll` is in the
140 * range [`1`, `INT16_MAX`].
141 * - `-raw_max_roll` is then in the range [`-INT16_MAX`, `-1`].
142 * - Therefore, [`-raw_max_roll`, `raw_max_roll`] is at worst
143 * [`-INT16_MAX`, `INT16_MAX`].
144 * - `fixang` can represent all values in [`-INT16_MAX`, `INT16_MAX`],
145 * so the conversion does not change the value.
146 */
147 const auto max_roll{static_cast<fixang>(std::clamp<fix>(delta_ang, -raw_max_roll, raw_max_roll))};
148 const auto updated_turnroll{obj.mtype.phys_info.turnroll + max_roll};
149 static constexpr fix minfixang{std::numeric_limits<fixang>::min()};
150 static constexpr fix maxfixang{std::numeric_limits<fixang>::max()};
151 obj.mtype.phys_info.turnroll = {static_cast<fixang>(std::clamp<fix>(updated_turnroll, minfixang, maxfixang))};
152 }
153 return obj.mtype.phys_info.turnroll;
154 }
155
156 }
157
158 #define MAX_IGNORE_OBJS 100
159
160 #ifndef NDEBUG
161 int Total_retries{0}, Total_sims=0;
162 int Dont_move_ai_objects{0};
163 #endif
164
165 #define FT (f1_0/64)
166
167 // -----------------------------------------------------------------------------------------------------------
168 // add rotational velocity & acceleration
169 namespace dsx {
170 namespace {
171 static void do_physics_sim_rot(object_base &obj)
172 {
173 Assert(FrameTime > 0); //Get MATT if hit this!
174
175 if (const physics_info &pi{obj.mtype.phys_info}; !(pi.rotvel.x || pi.rotvel.y || pi.rotvel.z || pi.rotthrust.x || pi.rotthrust.y || pi.rotthrust.z))
176 return;
177
178 if (obj.mtype.phys_info.drag)
179 {
180 const fix drag{(obj.mtype.phys_info.drag * 5) / 2};
181 int count{FrameTime / FT};
182 const fix r{FrameTime % FT};
183 const fix k{fixdiv(r, FT)};
184
185 if (obj.mtype.phys_info.flags & PF_USES_THRUST)
186 {
187 const auto accel{vm_vec_copy_scale(obj.mtype.phys_info.rotthrust, fixdiv(f1_0, obj.mtype.phys_info.mass))};
188 while (count--) {
189 vm_vec_add2(obj.mtype.phys_info.rotvel, accel);
190 vm_vec_scale(obj.mtype.phys_info.rotvel, f1_0 - drag);
191 }
192
193 //do linear scale on remaining bit of time
194
195 vm_vec_scale_add2(obj.mtype.phys_info.rotvel, accel, k);
196 vm_vec_scale(obj.mtype.phys_info.rotvel, f1_0 - fixmul(k, drag));
197 }
198 else
199 #if DXX_BUILD_DESCENT == 2
200 if (! (obj.mtype.phys_info.flags & PF_FREE_SPINNING))
201 #endif
202 {
203 fix total_drag{F1_0};
204 while (count--)
205 total_drag = fixmul(total_drag,f1_0-drag);
206
207 //do linear scale on remaining bit of time
208
209 total_drag = fixmul(total_drag,f1_0-fixmul(k,drag));
210
211 vm_vec_scale(obj.mtype.phys_info.rotvel, total_drag);
212 }
213
214 }
215
216 //now rotate object
217
218 //unrotate object for bank caused by turn
219 const fixang old_turnroll{obj.mtype.phys_info.turnroll};
220 if (old_turnroll)
221 {
222 const auto &&rotmat{vm_angles_2_matrix(
223 vms_angvec{
224 .p = fixang{0},
225 .b = static_cast<fixang>(-old_turnroll),
226 .h = fixang{0}
227 })};
228 obj.orient = vm_matrix_x_matrix(obj.orient, rotmat);
229 }
230
231 const auto frametime{FrameTime};
232
233 obj.orient = vm_matrix_x_matrix(obj.orient, vm_angles_2_matrix(
234 vms_angvec{
235 .p = multiply_with_clamp_to_fixang(obj.mtype.phys_info.rotvel.x, frametime),
236 .b = multiply_with_clamp_to_fixang(obj.mtype.phys_info.rotvel.z, frametime),
237 .h = multiply_with_clamp_to_fixang(obj.mtype.phys_info.rotvel.y, frametime)
238 }));
239
240 //re-rotate object for bank caused by turn
241 /* The call to `set_object_turnroll` may have changed
242 * `.phys_info.turnroll`, so use the returned turnroll, which may differ
243 * from `old_turnroll`.
244 */
245 if (const fixang turnroll{(obj.mtype.phys_info.flags & PF_TURNROLL) ? set_object_turnroll(obj, frametime) : old_turnroll})
246 {
247 obj.orient = vm_matrix_x_matrix(obj.orient, vm_angles_2_matrix(
248 vms_angvec{
249 .p = fixang{0},
250 .b = turnroll,
251 .h = fixang{0}
252 }));
253 }
254 check_and_fix_matrix(obj.orient);
255 }
256
257 // On joining edges fvi tends to get inaccurate as hell. Approach is to check if the object interects with the wall and if so, move away from it.
258 static void fix_illegal_wall_intersection(const vmobjptridx_t obj)
259 {
260 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
261 auto &Objects = LevelUniqueObjectState.Objects;
262 auto &Vertices = LevelSharedVertexState.get_vertices();
263 auto &vmobjptr = Objects.vmptr;
264 if (!(obj->type == OBJ_PLAYER || obj->type == OBJ_ROBOT))
265 return;
266
267 auto &vcvertptr = Vertices.vcptr;
268 const auto &&hresult{sphere_intersects_wall(vcsegptridx, vcvertptr, obj->pos, vcsegptridx(obj->segnum), obj->size)};
269 if (hresult.seg)
270 {
271 vm_vec_scale_add2(obj->pos, hresult.seg->sides[hresult.side].normals[0], FrameTime*10);
272 update_object_seg(vmobjptr, LevelSharedSegmentState, LevelUniqueSegmentState, obj);
273 }
274 }
275
276 class ignore_objects_array_t
277 {
278 using object_index_array = std::array<vcobjidx_t, MAX_IGNORE_OBJS>;
279 object_index_array::iterator iter_first_uninitialized;
280 std::array<std::byte, sizeof(object_index_array)> storage;
281 object_index_array &array()
282 {
283 return *reinterpret_cast<object_index_array *>(&storage);
284 }
285 const object_index_array &array() const
286 {
287 return *reinterpret_cast<const object_index_array *>(&storage);
288 }
289 public:
290 ignore_objects_array_t() :
291 iter_first_uninitialized(array().begin())
292 {
293 }
294 vcobjidx_t *push_back(const vcobjidx_t o)
295 {
296 if (likely(iter_first_uninitialized != array().end()))
297 return std::construct_at(std::to_address(iter_first_uninitialized++), o);
298 return nullptr;
299 }
300 operator std::ranges::subrange<const vcobjidx_t *>() const
301 {
302 return {array().begin(), iter_first_uninitialized};
303 }
304 };
305
306 }
307
308 // -----------------------------------------------------------------------------------------------------------
309 //Simulate a physics object for this frame
310 window_event_result do_physics_sim(const d_robot_info_array &Robot_info, const vmobjptridx_t obj, const vms_vector &obj_previous_position, phys_visited_seglist *const phys_segs)
311 {
312 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
313 auto &Objects = LevelUniqueObjectState.Objects;
314 auto &Vertices = LevelSharedVertexState.get_vertices();
315 auto &vcobjptr = Objects.vcptr;
316 auto &vmobjptr = Objects.vmptr;
317 ignore_objects_array_t ignore_obj_list;
318 fvi_info hit_info;
319 fix moved_time; //how long objected moved before hit something
320 const auto orig_segnum{obj->segnum};
321 bool Player_ScrapeFrame=false;
322 auto result = window_event_result::handled;
323 #if DXX_BUILD_DESCENT == 2
324 bool bounced{};
325 auto &TmapInfo = LevelUniqueTmapInfoState.TmapInfo;
326 #endif
327
328 Assert(obj->movement_source == object::movement_type::physics);
329
330 #ifndef NDEBUG
331 if (Dont_move_ai_objects)
332 if (obj->control_source == object::control_type::ai)
333 return window_event_result::ignored;
334 #endif
335
336 do_physics_sim_rot(obj);
337
338 if (const physics_info &pi{obj->mtype.phys_info}; !(pi.velocity.x || pi.velocity.y || pi.velocity.z || pi.thrust.x || pi.thrust.y || pi.thrust.z))
339 return window_event_result::ignored;
340
341 fix sim_time{FrameTime};
342 const vms_vector start_pos{obj->pos};
343
344 //if uses thrust, cannot have zero drag
345 Assert(!(obj->mtype.phys_info.flags&PF_USES_THRUST) || obj->mtype.phys_info.drag!=0);
346
347 //do thrust & drag
348 if (const fix drag{obj->mtype.phys_info.drag})
349 {
350 int count{FrameTime / FT};
351 const fix r{FrameTime % FT};
352 const fix k{fixdiv(r, FT)};
353
354 if (obj->mtype.phys_info.flags & PF_USES_THRUST) {
355
356 const auto accel{vm_vec_copy_scale(obj->mtype.phys_info.thrust,fixdiv(f1_0,obj->mtype.phys_info.mass))};
357 const bool have_accel{accel.x || accel.y || accel.z};
358
359 while (count--) {
360 if (have_accel)
361 vm_vec_add2(obj->mtype.phys_info.velocity,accel);
362
363 vm_vec_scale(obj->mtype.phys_info.velocity,f1_0-drag);
364 }
365
366 //do linear scale on remaining bit of time
367
368 vm_vec_scale_add2(obj->mtype.phys_info.velocity,accel,k);
369 if (drag)
370 vm_vec_scale(obj->mtype.phys_info.velocity,f1_0-fixmul(k,drag));
371 }
372 else if (drag)
373 {
374 fix total_drag{F1_0};
375
376 while (count--)
377 total_drag = fixmul(total_drag,f1_0-drag);
378
379 //do linear scale on remaining bit of time
380
381 total_drag = fixmul(total_drag,f1_0-fixmul(k,drag));
382
383 vm_vec_scale(obj->mtype.phys_info.velocity,total_drag);
384 }
385 }
386
387 int count{0};
388 auto &vcvertptr = Vertices.vcptr;
389 auto &Walls = LevelUniqueWallSubsystemState.Walls;
390 auto &vcwallptr = Walls.vcptr;
391 auto fate{fvi_hit_type::None};
392 bool try_again{};
393 bool obj_stopped{};
394 do {
395 try_again = 0;
396
397 //Move the object
398 const auto frame_vec{vm_vec_copy_scale(obj->mtype.phys_info.velocity, sim_time)};
399
400 if (frame_vec == vms_vector{})
401 break;
402
403 count++;
404
405 // If retry count is getting large, then we are trying to do something stupid.
406 if (count > 8) break; // in original code this was 3 for all non-player objects. still leave us some limit in case fvi goes apeshit.
407
408 const auto new_pos = vm_vec_build_add(obj->pos,frame_vec);
409 int flags{0};
410 if (obj->type == OBJ_WEAPON)
411 flags |= FQ_TRANSPOINT;
412
413 if (phys_segs)
414 flags |= FQ_GET_SEGLIST;
415
416 fate = find_vector_intersection(fvi_query{
417 obj->pos,
418 new_pos,
419 ignore_obj_list,
420 &LevelUniqueObjectState,
421 &Robot_info,
422 flags,
423 obj,
424 }, obj->segnum, obj->size, hit_info);
425 // Matt: Mike's hack.
426 if (fate == fvi_hit_type::Object)
427 {
428 auto &objp = *vcobjptr(hit_info.hit_object);
429
430 if ((objp.type == OBJ_WEAPON && is_proximity_bomb_or_player_smart_mine(get_weapon_id(objp))) ||
431 objp.type == OBJ_POWERUP) // do not increase count for powerups since they *should* not change our movement
432 count--;
433 }
434
435 #ifndef NDEBUG
436 if (fate == fvi_hit_type::BadP0)
437 Int3();
438 #endif
439
440 if (phys_segs && !hit_info.seglist.empty())
441 {
442 auto n_phys_segs{phys_segs->nsegs};
443 if (n_phys_segs && phys_segs->seglist[n_phys_segs - 1] == hit_info.seglist[0])
444 n_phys_segs--;
445 range_for (const auto &hs, hit_info.seglist)
446 {
447 if (!(n_phys_segs < phys_segs->seglist.size() - 1))
448 break;
449 phys_segs->seglist[n_phys_segs++] = hs;
450 }
451 phys_segs->nsegs = n_phys_segs;
452 }
453
454 const vms_vector ipos{hit_info.hit_pnt}; //position after this frame
455 const auto iseg{hit_info.hit_seg};
456 const sidenum_t WallHitSide{hit_info.hit_side};
457 const segnum_t WallHitSeg{hit_info.hit_side_seg};
458
459 if (iseg==segment_none) { //some sort of horrible error
460 if (obj->type == OBJ_WEAPON)
461 obj->flags |= OF_SHOULD_BE_DEAD;
462 break;
463 }
464
465 assert(!(fate == fvi_hit_type::Wall && (WallHitSeg == segment_none || WallHitSeg > Highest_segment_index)));
466
467 const vms_vector save_pos{obj->pos}; //save the object's position
468 const auto save_seg{obj->segnum};
469
470 // update object's position and segment number
471 obj->pos = ipos;
472
473 const auto &&obj_segp = Segments.vmptridx(iseg);
474 if ( iseg != obj->segnum )
475 obj_relink(vmobjptr, Segments.vmptr, obj, obj_segp);
476
477 //if start point not in segment, move object to center of segment
478 if (get_seg_masks(vcvertptr, obj->pos, Segments.vcptr(obj->segnum), 0).centermask != sidemask_t{})
479 {
480 auto n{find_object_seg(LevelSharedSegmentState, LevelUniqueSegmentState, obj)};
481 if (n == segment_none)
482 {
483 //Int3();
484 if (obj->type == OBJ_PLAYER && (n = find_point_seg(LevelSharedSegmentState, LevelUniqueSegmentState, obj_previous_position, obj_segp)) != segment_none)
485 {
486 obj->pos = obj_previous_position;
487 obj_relink(vmobjptr, Segments.vmptr, obj, n);
488 }
489 else {
490 obj->pos = compute_segment_center(vcvertptr, obj_segp);
491 obj->pos.x += obj;
492 }
493 if (obj->type == OBJ_WEAPON)
494 obj->flags |= OF_SHOULD_BE_DEAD;
495 }
496 return window_event_result::ignored;
497 }
498
499 //calulate new sim time
500 {
501 //vms_vector moved_vec;
502 vms_vector moved_vec_n;
503 const auto actual_dist{vm_vec_normalized_dir(moved_vec_n, obj->pos, save_pos)};
504
505 if (fate == fvi_hit_type::Wall && vm_vec_build_dot(moved_vec_n,frame_vec) < 0)
506 { //moved backwards
507
508 //don't change position or sim_time
509
510 obj->pos = save_pos;
511
512 //iseg = obj->segnum; //don't change segment
513
514 obj_relink(vmobjptr, Segments.vmptr, obj, Segments.vmptridx(save_seg));
515
516 moved_time = 0;
517 }
518 else {
519 const auto attempted_dist{vm_vec_mag(frame_vec)};
520 const auto old_sim_time{sim_time};
521 sim_time = fixmuldiv(sim_time,attempted_dist-actual_dist,attempted_dist);
522
523 moved_time = old_sim_time - sim_time;
524
525 if (sim_time < 0 || sim_time>old_sim_time) {
526 sim_time = old_sim_time;
527 //WHY DOES THIS HAPPEN??
528
529 moved_time = 0;
530 }
531 }
532 }
533
534
535 switch( fate ) {
536
537 case fvi_hit_type::Wall: {
538 fix hit_speed{0};
539
540 // Find hit speed
541
542 const auto moved_v{vm_vec_build_sub(obj->pos, save_pos)};
543 auto wall_part{vm_vec_build_dot(moved_v,hit_info.hit_wallnorm)};
544
545 if ((wall_part != 0 && moved_time>0 && (hit_speed=-fixdiv(wall_part,moved_time))>0) || obj->type == OBJ_WEAPON || obj->type == OBJ_DEBRIS)
546 result = collide_object_with_wall(
547 #if DXX_BUILD_DESCENT == 2
548 LevelSharedSegmentState.DestructibleLights,
549 #endif
550 Robot_info, obj, hit_speed, Segments.vmptridx(WallHitSeg), WallHitSide, hit_info.hit_pnt);
551 /*
552 * Due to the nature of this loop, it's possible that a local player may receive scrape damage multiple times in one frame.
553 * Check if we received damage and do not apply more damage (nor produce damage sounds/flashes/bumps, etc) for the rest of the loop.
554 * It's possible that other walls later in the loop would still be valid for scraping but due to the generalized outcome, this should be negligible (practical wall sliding is handled below).
555 * NOTE: Remote players will return false and never receive damage. But since we handle only one object (remote or local) per loop, this is no problem.
556 */
557 if (obj->type == OBJ_PLAYER && Player_ScrapeFrame == false)
558 Player_ScrapeFrame = scrape_player_on_wall(obj, Segments.vmptridx(WallHitSeg), WallHitSide, hit_info.hit_pnt);
559
560 Assert( WallHitSeg != segment_none );
561
562 if ( !(obj->flags&OF_SHOULD_BE_DEAD) ) {
563 #if DXX_BUILD_DESCENT == 2
564 if (!cheats.bouncyfire)
565 #endif
566 Assert(!(obj->mtype.phys_info.flags & PF_STICK && obj->mtype.phys_info.flags & PF_BOUNCE)); //can't be bounce and stick
567
568 #if DXX_BUILD_DESCENT == 1
569 /*
570 * Force fields are not supported in Descent 1. Use
571 * this as a placeholder to make the code match the
572 * force field handling in Descent 2.
573 */
574 const auto forcefield_bounce{false};
575 #elif DXX_BUILD_DESCENT == 2
576 const unique_segment &useg = vcsegptr(WallHitSeg);
577 auto &uside = useg.sides[WallHitSide];
578 const auto forcefield_bounce{(TmapInfo[get_texture_index(uside.tmap_num)].flags & tmapinfo_flag::force_field)}; //bounce off a forcefield
579 bool check_vel{};
580 #endif
581
582 if (!forcefield_bounce && (obj->mtype.phys_info.flags & PF_STICK)) { //stop moving
583
584 LevelUniqueStuckObjectState.add_stuck_object(vcwallptr, obj, Segments.vmptr(WallHitSeg), WallHitSide);
585
586 obj->mtype.phys_info.velocity = {};
587 obj_stopped = 1;
588 try_again = 0;
589 }
590 else { // Slide object along wall
591
592 wall_part = vm_vec_build_dot(hit_info.hit_wallnorm,obj->mtype.phys_info.velocity);
593
594 // if wall_part, make sure the value is sane enough to get usable velocity computed
595 if (wall_part < 0 && wall_part > -f1_0) wall_part = -f1_0;
596 if (wall_part > 0 && wall_part < f1_0) wall_part = f1_0;
597
598 if (forcefield_bounce || (obj->mtype.phys_info.flags & PF_BOUNCE)) { //bounce off wall
599 wall_part *= 2; //Subtract out wall part twice to achieve bounce
600
601 #if DXX_BUILD_DESCENT == 2
602 if (forcefield_bounce) {
603 check_vel = 1; //check for max velocity
604 if (obj->type == OBJ_PLAYER)
605 wall_part *= 2; //player bounce twice as much
606 }
607
608 if ( obj->mtype.phys_info.flags & PF_BOUNCES_TWICE) {
609 Assert(obj->mtype.phys_info.flags & PF_BOUNCE);
610 if (obj->mtype.phys_info.flags & PF_BOUNCED_ONCE)
611 obj->mtype.phys_info.flags &= ~(PF_BOUNCE+PF_BOUNCED_ONCE+PF_BOUNCES_TWICE);
612 else
613 obj->mtype.phys_info.flags |= PF_BOUNCED_ONCE;
614 }
615 bounced = 1; //this object bounced
616 #endif
617 }
618
619 vm_vec_scale_add2(obj->mtype.phys_info.velocity,hit_info.hit_wallnorm,-wall_part);
620
621 #if DXX_BUILD_DESCENT == 2
622 if (check_vel) {
623 fix vel = vm_vec_mag_quick(obj->mtype.phys_info.velocity);
624
625 if (vel > MAX_OBJECT_VEL)
626 vm_vec_scale(obj->mtype.phys_info.velocity,fixdiv(MAX_OBJECT_VEL,vel));
627 }
628
629 if (bounced && obj->type == OBJ_WEAPON)
630 {
631 /* Copy `objp.orient.uvec` into a temporary and pass the temporary,
632 * since it is undefined behavior to access `objp.orient` after the old
633 * object is destroyed until the new value is constructed.
634 */
635 auto old_uvec{obj->orient.uvec};
636 reconstruct_at(obj->orient, vm_vector_to_matrix_u, obj->mtype.phys_info.velocity, std::move(old_uvec));
637 }
638 #endif
639
640 try_again = 1;
641 }
642 }
643
644 break;
645 }
646
647 case fvi_hit_type::Object: {
648 // Mark the hit object so that on a retry the fvi code
649 // ignores this object.
650
651 Assert(hit_info.hit_object != object_none);
652 const auto old_vel{obj->mtype.phys_info.velocity};
653 // Calculcate the hit point between the two objects.
654 {
655 const auto &&hit = obj.absolute_sibling(hit_info.hit_object);
656 const auto &ppos0 = hit->pos;
657 const auto &ppos1 = obj->pos;
658 const fix size0{hit->size};
659 const fix size1{obj->size};
660 Assert(size0+size1 != 0); // Error, both sizes are 0, so how did they collide, anyway?!?
661 auto pos_hit{vm_vec_scale_add(ppos0, vm_vec_build_sub(ppos1, ppos0), fixdiv(size0, size0 + size1))};
662
663 collide_two_objects(Robot_info, obj, hit, pos_hit);
664 }
665
666 // Let object continue its movement
667 if ( !(obj->flags&OF_SHOULD_BE_DEAD) ) {
668 //obj->pos = save_pos;
669
670 if ((obj->mtype.phys_info.flags & PF_PERSISTENT) || old_vel == obj->mtype.phys_info.velocity)
671 {
672 //if (Objects[hit_info.hit_object].type == OBJ_POWERUP)
673 if (ignore_obj_list.push_back(hit_info.hit_object))
674 try_again = 1;
675 }
676 }
677
678 break;
679 }
680 case fvi_hit_type::None:
681 break;
682
683 case fvi_hit_type::BadP0:
684 #ifndef NDEBUG
685 Int3(); // Unexpected collision type: start point not in specified segment.
686 #endif
687 break;
688 }
689 } while ( try_again );
690
691 // Pass retry count info to AI.
692 if (obj->control_source == object::control_type::ai)
693 {
694 if (count > 0) {
695 obj->ctype.ai_info.ail.retry_count = count-1;
696 #ifndef NDEBUG
697 Total_retries += count-1;
698 Total_sims++;
699 #endif
700 }
701 }
702
703 // After collision with objects and walls, set velocity from actual movement
704 if (!obj_stopped
705 #if DXX_BUILD_DESCENT == 2
706 && !bounced
707 #endif
708 && ((obj->type == OBJ_PLAYER) || (obj->type == OBJ_ROBOT) || (obj->type == OBJ_DEBRIS))
709 && (fate == fvi_hit_type::Wall || fate == fvi_hit_type::Object || fate == fvi_hit_type::BadP0)
710 )
711 {
712 const auto moved_vec{vm_vec_build_sub(obj->pos, start_pos)};
713 obj->mtype.phys_info.velocity = vm_vec_copy_scale(moved_vec, fixdiv(F1_0, FrameTime));
714 }
715
716 fix_illegal_wall_intersection(obj);
717
718 //Assert(check_point_in_seg(&obj->pos,obj->segnum,0).centermask==0);
719
720 //if (obj->control_source == object::control_type::flying)
721 if (obj->mtype.phys_info.flags & PF_LEVELLING)
722 do_physics_align_object( obj );
723
724 //hack to keep player from going through closed doors
725 if (obj->type==OBJ_PLAYER && obj->segnum!=orig_segnum && (!cheats.ghostphysics) ) {
726
727 const cscusegment orig_segp{vcsegptr(orig_segnum)};
728 const auto &&sidenum = find_connect_side(vcsegptridx(obj->segnum), orig_segp);
729 if (sidenum != side_none)
730 {
731
732 if (! (WALL_IS_DOORWAY(GameBitmaps, Textures, vcwallptr, orig_segp, sidenum) & WALL_IS_DOORWAY_FLAG::fly))
733 {
734 //bump object back
735
736 auto &s = orig_segp.s.sides[sidenum];
737 const auto &&vertex_list{create_abs_vertex_lists(orig_segp, s, sidenum).vertex_list};
738
739 //let's pretend this wall is not triangulated
740 const auto b{begin(vertex_list)};
741 const auto vertnum{*std::min_element(b, std::next(b, 4))};
742
743 const fix dist{vm_dist_to_plane(start_pos, s.normals[0], vcvertptr(vertnum))};
744 obj->pos = vm_vec_scale_add(start_pos, s.normals[0], obj->size - dist);
745 update_object_seg(vmobjptr, LevelSharedSegmentState, LevelUniqueSegmentState, obj);
746 }
747 }
748 }
749
750 //--WE ALWYS WANT THIS IN, MATT AND MIKE DECISION ON 12/10/94, TWO MONTHS AFTER FINAL #ifndef NDEBUG
751 //if end point not in segment, move object to last pos, or segment center
752 if (get_seg_masks(vcvertptr, obj->pos, vcsegptr(obj->segnum), 0).centermask != sidemask_t{})
753 {
754 if (find_object_seg(LevelSharedSegmentState, LevelUniqueSegmentState, obj) == segment_none)
755 {
756 segnum_t n;
757 const auto &&obj_segp = Segments.vmptridx(obj->segnum);
758 if (obj->type == OBJ_PLAYER && (n = find_point_seg(LevelSharedSegmentState, LevelUniqueSegmentState, obj_previous_position, obj_segp)) != segment_none)
759 {
760 obj->pos = obj_previous_position;
761 obj_relink(vmobjptr, Segments.vmptr, obj, Segments.vmptridx(n));
762 }
763 else {
764 obj->pos = compute_segment_center(vcvertptr, obj_segp);
765 obj->pos.x += obj;
766 }
767 if (obj->type == OBJ_WEAPON)
768 obj->flags |= OF_SHOULD_BE_DEAD;
769 }
770 }
771
772 return result;
773 //--WE ALWYS WANT THIS IN, MATT AND MIKE DECISION ON 12/10/94, TWO MONTHS AFTER FINAL #endif
774 }
775 }
776
777 namespace dcx {
778
779 //make sure matrix is orthogonal
780 void check_and_fix_matrix(vms_matrix &m)
781 {
782 /* Copy `m.fvec`, `m.uvec` into temporaries and pass the temporaries, since
783 * it is undefined behavior to access `m` after the old object is destroyed
784 * until the new value is constructed.
785 */
786 auto old_fvec{m.fvec};
787 auto old_uvec{m.uvec};
788 reconstruct_at(m, vm_vector_to_matrix_u, std::move(old_fvec), std::move(old_uvec));
789 }
790
791 //Applies an instantaneous force on an object, resulting in an instantaneous
792 //change in velocity.
793 void phys_apply_force(object_base &obj, const vms_vector &force_vec)
794 {
795 if (obj.movement_source != object::movement_type::physics)
796 return;
797
798 // Put in by MK on 2/13/96 for force getting applied to Omega blobs, which have 0 mass,
799 // in collision with crazy reactor robot thing on d2levf-s.
800 if (obj.mtype.phys_info.mass == 0)
801 return;
802
803 //Add in acceleration due to force
804 vm_vec_scale_add2(obj.mtype.phys_info.velocity, force_vec, fixdiv(f1_0, obj.mtype.phys_info.mass));
805 }
806
807 namespace {
808
809 // ----------------------------------------------------------------
810 // Do *dest = *delta unless:
811 // *delta is pretty small
812 // and they are of different signs.
813 static void physics_set_rotvel_and_saturate(fix &dest, fix delta)
814 {
815 if ((delta ^ dest) < 0) {
816 if (abs(delta) < F1_0/8) {
817 dest = delta/4;
818 } else
819 dest = delta;
820 } else {
821 dest = delta;
822 }
823 }
824
825 }
826
827 // ------------------------------------------------------------------------------------------------------
828 // Note: This is the old ai_turn_towards_vector code.
829 // phys_apply_rot used to call ai_turn_towards_vector until I fixed it, which broke phys_apply_rot.
830 void physics_turn_towards_vector(const vms_vector &goal_vector, object_base &obj, fix rate)
831 {
832 // Make this object turn towards the goal_vector. Changes orientation, doesn't change direction of movement.
833 // If no one moves, will be facing goal_vector in 1 second.
834
835 // Detect null vector.
836 if (goal_vector == vms_vector{})
837 return;
838
839 // Make morph objects turn more slowly.
840 if (obj.control_source == object::control_type::morph)
841 rate *= 2;
842
843 const auto dest_angles{vm_extract_angles_vector(goal_vector)};
844 const auto cur_angles{vm_extract_angles_vector(obj.orient.fvec)};
845
846 fix delta_p{dest_angles.p - cur_angles.p};
847 fix delta_h{dest_angles.h - cur_angles.h};
848
849 if (delta_p > F1_0/2) delta_p = dest_angles.p - cur_angles.p - F1_0;
850 if (delta_p < -F1_0/2) delta_p = dest_angles.p - cur_angles.p + F1_0;
851 if (delta_h > F1_0/2) delta_h = dest_angles.h - cur_angles.h - F1_0;
852 if (delta_h < -F1_0/2) delta_h = dest_angles.h - cur_angles.h + F1_0;
853
854 delta_p = fixdiv(delta_p, rate);
855 delta_h = fixdiv(delta_h, rate);
856
857 if (abs(delta_p) < F1_0/16) delta_p *= 4;
858 if (abs(delta_h) < F1_0/16) delta_h *= 4;
859
860 auto &rotvel_ptr = obj.mtype.phys_info.rotvel;
861 physics_set_rotvel_and_saturate(rotvel_ptr.x, delta_p);
862 physics_set_rotvel_and_saturate(rotvel_ptr.y, delta_h);
863 rotvel_ptr.z = 0;
864 }
865
866 }
867
868 namespace dsx {
869
870 // -----------------------------------------------------------------------------
871 // Applies an instantaneous whack on an object, resulting in an instantaneous
872 // change in orientation.
873 void phys_apply_rot(object &obj, const vms_vector &force_vec)
874 {
875 fix rate;
876
877 if (obj.movement_source != object::movement_type::physics)
878 return;
879
880 #if DXX_BUILD_DESCENT == 2
881 auto &Robot_info = LevelSharedRobotInfoState.Robot_info;
882 #endif
883 const auto vecmag{vm_vec_mag(force_vec)};
884 if (vecmag < F1_0/32)
885 rate = 4*F1_0;
886 else if (vecmag < obj.mtype.phys_info.mass >> 11)
887 rate = 4*F1_0;
888 else {
889 rate = fixdiv(obj.mtype.phys_info.mass, vecmag / 8);
890 if (obj.type == OBJ_ROBOT) {
891 if (rate < F1_0/4)
892 rate = F1_0/4;
893 #if DXX_BUILD_DESCENT == 1
894 obj.ctype.ai_info.SKIP_AI_COUNT = 2;
895 #elif DXX_BUILD_DESCENT == 2
896 // Changed by mk, 10/24/95, claw guys should not slow down when attacking!
897 if (!Robot_info[get_robot_id(obj)].thief && !Robot_info[get_robot_id(obj)].attack_type) {
898 if (obj.ctype.ai_info.SKIP_AI_COUNT * FrameTime < 3*F1_0/4) {
899 fix tval{fixdiv(F1_0, 8*FrameTime)};
900 auto addval{f2i(tval)};
901
902 if ( (d_rand() * 2) < (tval & 0xffff))
903 addval++;
904 obj.ctype.ai_info.SKIP_AI_COUNT += addval;
905 }
906 }
907 #endif
908 } else {
909 if (rate < F1_0/2)
910 rate = F1_0/2;
911 }
912 }
913
914 // Turn amount inversely proportional to mass. Third parameter is seconds to do 360 turn.
915 physics_turn_towards_vector(force_vec, obj, rate);
916 }
917
918 }
919
920 namespace dcx {
921
922 //this routine will set the thrust for an object to a value that will
923 //(hopefully) maintain the object's current velocity
924 void set_thrust_from_velocity(object_base &obj)
925 {
926 Assert(obj.movement_source == object::movement_type::physics);
927 auto &phys_info = obj.mtype.phys_info;
928 phys_info.thrust = vm_vec_copy_scale(phys_info.velocity,
929 fixmuldiv(phys_info.mass, phys_info.drag, F1_0 - phys_info.drag)
930 );
931 }
932
933 }