#include "game_types.h"

/* Physics_BounceWithCollision @ 0x08019FC0 (real 180B) -- bounce dispatch with SVC-171 table store. Mirrors src/matched/Physics_BounceWithCollision.c. */
/* Looks up slot -1 (missing returns -1), folds flag bits into the mode
   (2/4/4, with the bit-8 reshape), runs the response + SVC 171, stores hits
   into the slot table (zeroing the tail word), and returns r+32 (Copy on
   negative). A re-entrant trampoline tail (same span) feeds CalcReflect. */
extern int Object_Find(int x);
extern int Physics_CollisionResponse(int a);
extern int Float_Copy(int x);
extern int Physics_CalcReflect(int x);
extern int SWI_171(int service, void *sp); /* swi #171 */

int Physics_BounceWithCollision(int a, int b)
{
    int slot = Object_Find(-1);
    int mode = 0;
    int resp, r;
    int args[3];
    int *tab;
    if (slot == 20)
        return -1;
    if ((b & 2) != 0)
        mode = 2;
    if ((b & 512) != 0)
        mode |= 4;
    if ((b & 1024) != 0)
        mode |= 4;
    if ((b & 8) != 0)
        mode = (mode & ~5) | 8;
    resp = Physics_CollisionResponse(a);
    args[0] = a;
    args[1] = mode;
    args[2] = resp;
    r = SWI_171(1, args);
    if (r < 0)
        return Float_Copy(r);
    tab = (int *)0x02001518;
    *(int *)((char *)tab + slot * 8) = r;
    *(int *)((char *)tab + slot * 8 + 4) = 0;
    return r + 32;
}

/* Trailing trampoline (same ROM span): re-enters with an incoming value. */
int Physics_BounceWithCollision_Resume(int x, int b)
{
    return Physics_CalcReflect(Physics_BounceWithCollision(x, b));
}
