code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2016 EDuke32 developers and contributors

This file is part of EDuke32.

EDuke32 is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

#ifndef menus_h_
#define menus_h_

#include "compat.h"

#ifdef __cplusplus
extern "C" {
#endif

#if defined EDUKE32_TOUCH_DEVICES
# define EDUKE32_SIMPLE_MENU
# define EDUKE32_ANDROID_MENU
#endif

// #define EDUKE32_SIMPLE_MENU

enum MenuIndex_t {
    MENU_NULL           = INT32_MIN, // sentinel for "do nothing"
    MENU_CLOSE          = -2, // sentinel for "close the menu"/"no menu"
    MENU_PREVIOUS       = -1, // sentinel for "go to previous menu"
    MENU_MAIN           = 0,
    MENU_MAIN_INGAME    = 50,
    MENU_EPISODE        = 100,
    MENU_USERMAP        = 101,
    MENU_SKILL          = 110,
    MENU_GAMESETUP      = 200,
    MENU_OPTIONS        = 202,
    MENU_VIDEOSETUP     = 203,
    MENU_KEYBOARDSETUP  = 204,
    MENU_MOUSESETUP     = 205,
    MENU_JOYSTICKSETUP  = 206,
    MENU_JOYSTICKBTNS   = 207,
    MENU_JOYSTICKAXES   = 208,
    MENU_KEYBOARDKEYS   = 209,
    MENU_MOUSEBTNS      = 210,
    MENU_JOYSTICKADV    = 212,
    MENU_JOYSTICKAXIS   = 213,
    MENU_TOUCHSETUP     = 214,
    MENU_TOUCHSENS      = 215,
    MENU_TOUCHBUTTONS   = 216,
    MENU_CONTROLS       = 220,
    MENU_POLYMOST       = 230,
    MENU_COLCORR        = 231,
    MENU_COLCORR_INGAME = 232,
    MENU_SCREENSETUP    = 233,
    MENU_DISPLAYSETUP   = 234,
    MENU_POLYMER        = 240,
    MENU_LOAD           = 300,
    MENU_SAVE           = 350,
    MENU_STORY          = 400,
    MENU_F1HELP         = 401,
    MENU_F1HELP2        = 402,
    MENU_QUIT           = 500,
    MENU_QUITTOTITLE    = 501,
    MENU_QUIT_INGAME    = 502,
    MENU_NETSETUP       = 600,
    MENU_NETWAITMASTER  = 601,
    MENU_NETWAITVOTES   = 603,
    MENU_SOUND          = 700,
    MENU_SOUND_INGAME   = 701,
    MENU_SOUND_DEVSETUP = 702,
    MENU_SOUND_SF2      = 703,
    MENU_CDPLAYER       = 704,
    MENU_SAVESETUP      = 750,
    MENU_SAVECLEANVERIFY = 751,
    MENU_CHEATS         = 800,
    MENU_CHEATENTRY     = 801,
    MENU_CHEAT_WARP     = 802,
    MENU_CHEAT_SKILL    = 803,
    MENU_CREDITS        = 960,
    MENU_CREDITS2       = 961,
    MENU_CREDITS3       = 962,
    MENU_CREDITS4       = 963,
    MENU_CREDITS5       = 964,
    MENU_CREDITS6       = 965,
    MENU_CREDITS7       = 966,
    MENU_CREDITS8       = 967,
    MENU_CREDITS9       = 968,
    MENU_CREDITS10      = 969,
    MENU_CREDITS11      = 970,
    MENU_CREDITS12      = 971,
    MENU_CREDITS13      = 972,
    MENU_CREDITS14      = 973,
    MENU_CREDITS15      = 974,
    MENU_CREDITS16      = 975,
    MENU_CREDITS17      = 976,
    MENU_CREDITS18      = 977,
    MENU_CREDITS19      = 978,
    MENU_CREDITS20      = 979,
    MENU_CREDITS21      = 980,
    MENU_CREDITS22      = 981,
    MENU_CREDITS23      = 982,
    MENU_CREDITS24      = 983,
    MENU_CREDITS25      = 984,
    MENU_CREDITS26      = 985,
    MENU_CREDITS27      = 986,
    MENU_CREDITS28      = 987,
    MENU_CREDITS29      = 988,
    MENU_CREDITS30      = 989,
    MENU_CREDITS31      = 990,
    MENU_CREDITS32      = 991,
    MENU_CREDITS33      = 992,
    MENU_LOADVERIFY     = 1000,
    MENU_LOADDELVERIFY  = 1100,
    MENU_NEWVERIFY      = 1500,
    MENU_SAVEVERIFY     = 2000,
    MENU_SAVEDELVERIFY  = 2100,
    MENU_JOYDEFAULTVERIFY = 2203,
    MENU_ADULTPASSWORD  = 10001,
    MENU_RESETPLAYER    = 15000,
    MENU_BUYDUKE        = 20000,
    MENU_NETWORK        = 20001,
    MENU_PLAYER         = 20002,
    MENU_MACROS         = 20004,
    MENU_NETHOST        = 20010,
    MENU_NETOPTIONS     = 20011,
    MENU_NETUSERMAP     = 20012,
    MENU_NETJOIN        = 20020,
    MENU_DHHUNTING      = 30000,
    MENU_DHTARGET       = 30001,
    MENU_DHWEAPON       = 30002,
    MENU_DHTROPHIES     = 30003,
};

typedef int32_t MenuID_t;

typedef enum MenuAnimationType_t
{ // Note: This enum is for logical categories, not visual types.
    MA_None,
    MA_Return,
    MA_Advance,
} MenuAnimationType_t;

// a subset of screentext parameters, restricted because menus require accessibility
typedef struct MenuFont_t
{
//    int32_t xspace, yline;
    vec2_t emptychar, between;
    int32_t zoom;
    int32_t cursorLeftPosition, cursorCenterPosition, cursorScale, cursorScale2, cursorScale3;
    int32_t textflags;
    int16_t tilenum;
    // selected shade glows, deselected shade is used by Blood, disabled shade is used by SW
    int8_t shade_deselected, shade_disabled;
    uint8_t pal;
    uint8_t pal_selected, pal_deselected, pal_disabled;
    uint8_t pal_selected_right, pal_deselected_right, pal_disabled_right;

    int32_t get_yline() const { return mulscale16(emptychar.y, zoom); }
} MenuFont_t;

typedef enum MenuEntryType_t
{
    Dummy,
    Link,
    Option,
    Custom2Col,
    RangeInt32,
    RangeFloat,
#ifdef MENU_ENABLE_RANGEDOUBLE
    RangeDouble,
#endif
    String,
    Spacer,
} MenuEntryType_t;

typedef struct MenuEntryFormat_t
{
    int32_t marginBottom;
    int32_t indent;
    int32_t width; // 0: center, >0: width of the label column (left-aligned options), <0: -width of everything (right-aligned)
} MenuEntryFormat_t;

typedef struct MenuMenuFormat_t
{
    vec2_t pos;
    int32_t bottomcutoff; // >0: the bottom edge of the menu before automatic scrolling kicks in, <0: -total height for vertical justification
} MenuMenuFormat_t;

typedef struct MenuLink_t
{
    // traits
    MenuID_t linkID;
    MenuAnimationType_t animation;
} MenuLink_t;
typedef struct MenuOptionSet_t
{
    // traits
    char const **optionNames;
    int32_t *optionValues; // If NULL, the identity of currentOption is assumed.

    // pop-up list appearance
    MenuMenuFormat_t *menuFormat;
    MenuEntryFormat_t *entryFormat;
    MenuFont_t *font;

    // traits
    int32_t numOptions;

    // pop-up list state
    int32_t currentEntry;
    int32_t scrollPos;

    // appearance
    uint8_t features; // bit 1 = disable left/right arrows, bit 2 = disable list

    int32_t getMarginBottom() const { return mulscale16(entryFormat->marginBottom, font->zoom); }
    int32_t getIndent() const { return mulscale16(entryFormat->indent, font->zoom); }
} MenuOptionSet_t;
typedef struct MenuOption_t
{
    // appearance
    MenuFont_t *font;

    // traits
    MenuOptionSet_t *options; // so that common sets such as Yes/No, On/Off can be reused

    // effect
    int32_t *data;

    // state
    int32_t currentOption;
} MenuOption_t;
typedef struct MenuCustom2Col_t
{
    // effect
    uint8_t *column[2];
    char const **key;

    // appearance
    MenuFont_t *font;

    // effect
    size_t numvalid;

    // appearance
    int32_t columnWidth;

    // state
    int8_t screenOpen;
} MenuCustom2Col_t;

enum MenuRangeFlags_t
{
    DisplayTypeInteger = 1,
    DisplayTypePercent = 2,
    DisplayTypeNormalizedDecimal = 3,
    DisplayTypeMask = (1<<0)|(1<<1),

    EnforceIntervals = 1<<7,
};
typedef struct MenuRangeInt32_t
{
    // effect
    int32_t *variable;

    // appearance
    MenuFont_t *font;

    // traits
    int32_t min;
    int32_t max;
    int32_t onehundredpercent; // 0 implies max
    int32_t steps;

    uint8_t flags;
} MenuRangeInt32_t;
typedef struct MenuRangeFloat_t
{
    // effect
    float *variable;

    // appearance
    MenuFont_t *font;

    // traits
    float min;
    float max;
    float onehundredpercent; // 0 implies 1.0
    int32_t steps;

    uint8_t flags;
} MenuRangeFloat_t;
#ifdef MENU_ENABLE_RANGEDOUBLE
typedef struct MenuRangeDouble_t
{
    // effect
    double *variable;

    // appearance
    MenuFont_t *font;

    // traits
    double min;
    double max;
    double onehundredpercent; // 0 implies 1.0
    int32_t steps;

    uint8_t flags;
} MenuRangeDouble_t;
#endif
typedef struct MenuString_t
{
    // state
    char* editfield;

    // effect
    char* variable;

    // appearance
    MenuFont_t *font;

    // effect
    int32_t bufsize;
    int32_t flags;
} MenuString_t;
typedef struct MenuSpacer_t
{
    int32_t height;
} MenuSpacer_t;

// For internal use only.
enum MenuEntryFlags_t
{
    MEF_Disabled = 1<<0,
    MEF_LookDisabled = 1<<1,
    MEF_Hidden = 1<<2,
};

typedef struct MenuEntry_t
{
    // traits
    const char *name;

    // appearance
    MenuFont_t *font;
    MenuEntryFormat_t *format;

    void *entry;
    MenuEntryType_t type;

    // state
    int32_t flags;
    int32_t ytop, ybottom;

    int32_t getMarginBottom() const { return mulscale16(format->marginBottom, font->zoom); }
    int32_t getIndent() const { return mulscale16(format->indent, font->zoom); }
    int32_t getHeight() const
    {
        return type == Spacer ? mulscale16(((MenuSpacer_t *)entry)->height, font->zoom) : font->get_yline();
    }
} MenuEntry_t;

typedef enum MenuType_t
{
    Menu,
    Panel,
    Verify,
    Message,
    TextForm,
    FileSelect,
    CdPlayer,
} MenuType_t;

typedef struct MenuMenu_t
{
    const char *title;

    MenuMenuFormat_t *format;

    MenuEntry_t **entrylist;
    int32_t numEntries;

    // state
    int32_t currentEntry, currentColumn;
    int32_t scrollPos;
} MenuMenu_t;
typedef struct MenuPanel_t
{
    const char *title;

    MenuID_t previousID;
    MenuAnimationType_t previousAnimation;
    MenuID_t nextID;
    MenuAnimationType_t nextAnimation;
} MenuPanel_t;
typedef struct MenuVerify_t
{
    vec2_t cursorpos;

    MenuID_t linkID;
    MenuAnimationType_t animation;
} MenuVerify_t;
typedef struct MenuMessage_t
{
    vec2_t cursorpos;

    MenuID_t linkID;
    MenuAnimationType_t animation;
} MenuMessage_t;
enum MenuTextFormFlags_t
{
    MTF_Password = 1<<0,
};
typedef struct MenuTextForm_t
{
    // state
    char *input;

    // traits
    const char *instructions;
    int32_t bufsize;
    uint8_t flags;
} MenuTextForm_t;
typedef struct MenuFileSelect_t
{
    const char *title;

    // appearance
    MenuMenuFormat_t *format[2];
    MenuFont_t *font[2];

    // traits
    const char * startdir;
    const char *pattern;
    char *destination;

    // state
    BUILDVFS_FIND_REC *findhigh[2];
    int32_t scrollPos[2];

    // appearance
    int32_t marginBottom[2];

    // state
    fnlist_t fnlist;
    int32_t currentList;

    int32_t getMarginBottom(size_t index) const { return mulscale16(marginBottom[index], font[index]->zoom); }
} MenuFileSelect_t;

typedef struct Menu_t
{
    void *object;
    MenuID_t menuID;
    MenuID_t parentID;
    MenuAnimationType_t parentAnimation;
    MenuType_t type;
} Menu_t;

typedef struct MenuAnimation_t
{
    int32_t(*out)(struct MenuAnimation_t *);
    int32_t(*in)(struct MenuAnimation_t *);

    Menu_t *previous;
    Menu_t *current;

    int32_t start;
    int32_t length;
} MenuAnimation_t;

extern MenuAnimation_t m_animation;

extern MenuID_t g_currentMenu;
extern Menu_t *m_currentMenu;

extern int32_t g_quitDeadline;
extern int32_t voting;
int Menu_Change(MenuID_t cm);
void Menu_AnimateChange(int32_t cm, MenuAnimationType_t animtype);
int32_t Menu_IsTextInput(Menu_t *cm);
int G_CheckPlayerColor(int color);
void Menu_Init(void);
void Menu_Open(uint8_t playerID);
void Menu_Close(uint8_t playerID);
void M_DisplayMenus(void);

extern MenuFont_t MF_Redfont, MF_Bluefont, MF_Minifont;

#define M_MOUSETIMEOUT 210
extern int32_t m_mouselastactivity;

#if defined EDUKE32_TOUCH_DEVICES
# define MOUSEALPHA 0
# define CURSORALPHA (255/3)
# define MOUSEACTIVECONDITIONAL(condition) (condition)
# define MOUSEWATCHPOINTCONDITIONAL(condition) (condition)
#else
extern int32_t m_mousewake_watchpoint, m_menuchange_watchpoint;
// alpha increments of 3 --> 255 / 3 = 85 --> round up to power of 2 --> 128 --> divide by 2 --> 64 alphatabs required
// use 16 anyway :P
# define MOUSEUSEALPHA (videoGetRenderMode() != REND_CLASSIC || numalphatabs >= 15)
# define MOUSEALPHA (MOUSEUSEALPHA ? clamp(((int32_t) totalclock - m_mouselastactivity - 90)*3, 0, 255) : 0)
# define CURSORALPHA (MOUSEUSEALPHA ? clamp(((int32_t) totalclock - m_mouselastactivity - 90)*2 + (255/3), (255/3), 255) : 255/3)
# define MOUSEACTIVECONDITION ((int32_t) totalclock - m_mouselastactivity < M_MOUSETIMEOUT)
# define MOUSEACTIVECONDITIONAL(condition) (MOUSEACTIVECONDITION && (condition))
# define MOUSEINACTIVECONDITIONAL(condition) (!MOUSEACTIVECONDITION && (condition))
# define MOUSEWATCHPOINTCONDITIONAL(condition) ((condition) || m_mousewake_watchpoint || m_menuchange_watchpoint == 3)
#endif

#ifdef __cplusplus
}
#endif

#endif

repo_name: orochi/nblood

license: mit


code:
BUILD SOURCE CODE LICENSE TERMS:                             06/20/2000

[1] I give you permission to make modifications to my Build source and
       distribute it, BUT:

[2] Any derivative works based on my Build source may be distributed ONLY
       through the INTERNET.

[3] Distribution of any derivative works MUST be done completely FREE of
       charge - no commercial exploitation whatsoever.

[4] Anything you distribute which uses a part of my Build Engine source
       code MUST include:

   [A] The following message somewhere in the archive:

       // "Build Engine & Tools" Copyright (c) 1993-1997 Ken Silverman
       // Ken Silverman's official web site: "http://www.advsys.net/ken"
       // See the included license file "BUILDLIC.TXT" for license info.

   [B] This text file "BUILDLIC.TXT" along with it.

   [C] Any source files that you modify must include this message as well:

       // This file has been modified from Ken Silverman's original release

[5] The use of the Build Engine for commercial purposes will require an
       appropriate license arrangement with me. Contact information is
       on my web site.

[6] I take no responsibility for damage to your system.

[7] Technical support: Before contacting me with questions, please read
       and do ALL of the following!

   [A] Look through ALL of my text files. There are 7 of them (including this
          one). I like to think that I wrote them for a reason. You will find
          many of your answers in the history section of BUILD.TXT and
          BUILD2.TXT (they're located inside SRC.ZIP).

   [B] If that doesn't satisfy you, then try going to:

             "http://www.advsys.net/ken/buildsrc"

          where I will maintain a Build Source Code FAQ (or perhaps I might
          just provide a link to a good FAQ).

   [C] I am willing to respond to questions, but ONLY if they come at a rate
          that I can handle.

             PLEASE TRY TO AVOID ASKING DUPLICATE QUESTIONS!

          As my line of defense, I will post my current policy about
          answering Build source questions (right below the E-mail address
          on my web site.) You can check there to see if I'm getting
          overloaded with questions or not.

          If I'm too busy, it might say something like this:

               I'm too busy to answer Build source questions right now.
               Sorry, but don't expect a reply from me any time soon.

          If I'm open for Build source questions, please state your question
             clearly and don't include any unsolicited attachments unless
             they're really small (like less than 50k). Assume that I have
             a 28.8k modem. Also, don't leave out important details just
             to make your question appear shorter - making me guess what
             you're asking doesn't save me time!

----------------------------------------------------------------------------
-Ken S. (official web site: http://www.advsys.net/ken)


code:
                    GNU GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.


code:
// Copyright: 2020 Nuke.YKT, EDuke32 developers
// License: GPLv2
#include "build.h"
#include "colmatch.h"
#include "vfs.h"
#include "crc32.h"
#include "reality.h"
#include "../duke3d.h"
#include "../gamedef.h"

// int rt_gamestate = 2, rt_gamestatus = 0;

buildvfs_kfd rt_group = buildvfs_kfd_invalid;
static bool rt_group_init;

static boardinfo_t boardinfo[RT_BOARDNUM];

uint16_t rt_palette[RT_PALNUM][256];

static void RT_LoadPalette(void);

int rt_vtxnum;

rt_vertex_t *rt_sectvtx;
rt_walltype *rt_wall;
rt_sectortype *rt_sector;

int rt_boardnum;

char *rt_rom;

int rt_romcountry; // 0 - USA, 1 - EU

int rt_romoffset = 0;

int rt_levelnum;
// int rt_level7unlock, rt_level18unlock, rt_level28unlock, rt_level29unlock, rt_level33unlock;

struct {
    int usaoffset, euoffset;
} rt_offsettable[GO_MAXOFFSETS] = {
    0xa4500, 0xa4530,
    0xb1784, 0xb17b4,
    0x8f6f8, 0x8f728,
    0xb4784, 0xb47b4,
    0xbba50-0x80105e50, 0xbba80-0x80105e80,
    0xc0880, 0xc08b0,
    0x7bc6e0, 0x7bc710,
    0x7bd580, 0x7bd5b0,
    0x7bbfc0, 0x7bbff0,
    0x5fe770, 0x5fe7a0,
    0x60b330, 0x60b360,
    0xb4990, 0xb49c0,
    0xb4be8, 0xb4c18,
    0xb4e40, 0xb4e70,
    0xb5098, 0xb50c8,
    0x8a4a8, 0x8a4d8,
    0x90bf0, 0x90c20,
    0xc2270, 0xc22a0,
    0x3e9550, 0x3e9580,
    0x895b0, 0x895e0,
};

#define RTROMSIZE 8388608
buildvfs_kfd RT_InitGRP(const char *filename)
{
    auto grp = openfrompath(filename, BO_RDONLY|BO_BINARY, BS_IREAD);
    if (grp != buildvfs_kfd_invalid)
    {
        rt_group = grp;
        rt_rom = (char*)Xmalloc(RTROMSIZE);
        if (!rt_rom)
            return -1;
        int byteorder = 0;

        lseek(rt_group, 0, SEEK_SET);
        if (read(rt_group, rt_rom, RTROMSIZE) != RTROMSIZE)
        {
            Xfree(rt_rom);
            rt_rom = nullptr;
            initprintf("Error reading ROM file");
            return -1;
        }
        if (!memcmp("DUKE", &rt_rom[32], 4))
            byteorder = 0;
        else if (!memcmp("UDEK", &rt_rom[32], 4))
            byteorder = 1;
        else if (!memcmp("EKUD", &rt_rom[32], 4))
            byteorder = 2;
        else
        {
            initprintf("Invalid ROM file");
            return -1;
        }
        switch (byteorder)
        {
        case 0:
        default:
            break;
        case 1:
            for (int i = 0; i < RTROMSIZE / 2; i++)
            {
                uint16_t *ptr = (uint16_t*)&rt_rom[i * 2];
                *ptr = B_SWAP16(*ptr);
            }
            break;
        case 2:
            for (int i = 0; i < RTROMSIZE / 4; i++)
            {
                uint32_t *ptr = (uint32_t*)&rt_rom[i * 4];
                *ptr = B_SWAP32(*ptr);
            }
            break;
        }
        if (memcmp(&rt_rom[32], "DUKE NUKEM", 10) != 0)
        {
            Xfree(rt_rom);
            rt_rom = nullptr;
            initprintf("Invalid ROM file");
            return -1;
        }
        switch (rt_rom[62])
        {
        case 'E':
            rt_romcountry = 0;
            break;
        case 'P':
            rt_romcountry = 1;
            break;
        default:
            Xfree(rt_rom);
            rt_rom = nullptr;
            initprintf("Invalid ROM file");
            return -1;
        }
        rt_group_init = true;

        return rt_group;
    }

    return -1;
}

void RT_ROMSeek(int offset)
{
    if (offset >= 0 && offset <= RTROMSIZE)
        rt_romoffset = offset;
}

int RT_ROMRead(void *ptr, int count)
{
    count = min(count, RTROMSIZE - rt_romoffset);
    memcpy(ptr, &rt_rom[rt_romoffset], count);
    rt_romoffset += count;
    return count;
}

int RT_ROMGetOffset(int offset)
{
    if (offset < 0 || offset >= GO_MAXOFFSETS)
        return 0;
    switch (rt_romcountry)
    {
    case 0:
        return rt_offsettable[offset].usaoffset;
    case 1:
        return rt_offsettable[offset].euoffset;
    default:
        break;
    }
    return 0;
}

void RT_Init(void)
{
    int boardOffset = RT_ROMGetOffset(GO_BOARDOFFSET);
    if (!rt_group_init)
        G_GameExit("RT_Init: No GRP initialized");

    paletteLoadFromDisk_replace = RT_LoadPalette;

    RT_ROMSeek(boardOffset);
    if (RT_ROMRead(boardinfo, sizeof(boardinfo)) != sizeof(boardinfo))
    {
        initprintf("RT_Init: file read error");
        return;
    }
    for (auto &b : boardinfo)
    {
        b.datastart = B_BIG32(b.datastart);
        b.dataend = B_BIG32(b.dataend);
        b.sectoroffset = B_BIG32(b.sectoroffset);
        b.walloffset = B_BIG32(b.walloffset);
        b.spriteoffset = B_BIG32(b.spriteoffset);
        b.numsector = B_BIG32(b.numsector);
        b.numsprites = B_BIG32(b.numsprites);
        b.numwall = B_BIG32(b.numwall);
        b.posx = B_BIG32(b.posx);
        b.posy = B_BIG32(b.posy);
        b.posz = B_BIG32(b.posz);
        b.ang = B_BIG32(b.ang);
        for (int j = 0; j < 6; j++)
        {
            int t = *(int*)&b.sky[j];
            *(int*)&b.sky[j] = B_BIG32(t);
        }
    }

    duke64 = true;

#ifdef USE_OPENGL
    // FIXME
    PolymostProcessVoxels_Callback = RT_GLInit;
#endif

    RT_BuildAngleTable();

    static int const wchoice[14] = {
        13, 12, 2, 3, 7, 4, 10, 6, 14, 8, 5, 1, 9, 0
    };

    for (int i = 0; i < 14; i++)
    {
        g_player[0].wchoice[i] = wchoice[i];
    }

    globalflags |= GLOBAL_NO_GL_TILESHADES;

#define DN64WSGRP "dn64widescreen.pk3"
#define DN64WSDEF "duke64_widescreen.def"

    if (initgroupfile(DN64WSGRP) != -1)
    {
        G_AddDefModule(DN64WSDEF);
    }
#undef DN64WSGRP
#undef DN64WSDEF
}

struct {
    int volume, level;
    const char *filename;
} rt_musicdefs[] = {
    MAXVOLUMES, 0, "grabbag.mid",
    MAXVOLUMES, 1, "briefing.mid",
    0, 0, "stalker.mid",
    0, 1, "dethtoll.mid",
    0, 2, "streets.mid",
    0, 3, "watrwld1.mid",
    0, 4, "thecall.mid",
    0, 5, "snake1.mid",
    0, 6, "snake1.mid",
    0, 7, "prepd.mid",
    0, 8, "futurmil.mid",
    0, 9, "storm.mid",
    0, 10, "gutwrnch.mid",
    0, 11, "robocrep.mid",
    0, 12, "stalag.mid",
    0, 13, "pizzed.mid",
    0, 14, "alienz.mid",
    0, 15, "xplasma.mid",
    0, 16, "alfredh.mid",
    0, 17, "alfredh.mid",
    0, 18, "intents.mid",
    0, 19, "inhiding.mid",
    0, 20, "fatcmdr.mid",
    0, 21, "names.mid",
    0, 22, "subway.mid",
    0, 23, "invader.mid",
    0, 24, "gotham.mid",
    0, 25, "233c.mid",
    0, 26, "lordofla.mid",
    0, 27, "urban.mid",
    0, 28, "restrict.mid",
    0, 29, "whomp.mid",
};

const char* rt_level_names[] = {
    "HOLLYWOOD HOLOCAUST",
    "GUN CRAZY",
    "DEATH ROW",
    "TOXIC DUMP",
    "LAUNCH FACILITY",
    "THE ABYSS",
    "BATTLELORD",
    "DUKE-BURGER",
    "SPACEPORT",
    "INCUBATOR",
    "WARP FACTOR",
    "FUSION STATION",
    "OCCUPIED TERRITORY",
    "TIBERIUS STATION",
    "LUNAR REACTOR",
    "DARK SIDE",
    "DREADNOUGHT",
    "OVERLORD",
    "LUNATIC FRINGE",
    "RAW MEAT",
    "BANK ROLL",
    "FLOOD ZONE",
    "L.A. RUMBLE",
    "MOVIE SET",
    "RABID TRANSIT",
    "FAHRENHEIT",
    "HOTEL HELL",
    "STADIUM",
    "AREA 51",
    "FREEWAY",
    "CASTLE DUKENSTEIN",
    "PIRACY",
    "SHAFT",
    "NOCTIS LABYRINTHUS"
};

#define RT_QUOTES 131

int RT_PrepareScript(void)
{
    const int rt_scriptoffset = RT_ROMGetOffset(GO_SCRIPTOFFSET);
    const int rt_actoroffset = RT_ROMGetOffset(GO_ACTOROFFSET);
    const int rt_scriptsize = 0x34a1;
    int32_t *rt_script = (int32_t*)Xmalloc(rt_scriptsize*4);
    int16_t *rt_actorscrptr = (int16_t*)Xmalloc(6144*2);
    if (rt_script == nullptr)
    {
        initprintf("RT_PrepareScript: can't allocate memory\n");
        return 1;
    }

    RT_ROMSeek(rt_scriptoffset);
    if (RT_ROMRead(rt_script, rt_scriptsize*4) != rt_scriptsize*4)
    {
        initprintf("RT_PrepareScript: file read error\n");
        return 1;
    }

    RT_ROMSeek(rt_actoroffset);
    if (RT_ROMRead(rt_actorscrptr, 6144*2) != 6144*2)
    {
        initprintf("RT_PrepareScript: file read error\n");
        return 1;
    }

    g_scriptcrc = Bcrc32(NULL, 0, 0L);
    g_scriptcrc = Bcrc32(rt_script, rt_scriptsize*4, g_scriptcrc);

    g_scriptSize = rt_scriptsize;
    Xfree(apScript);
    apScript = (intptr_t *)Xcalloc(1, g_scriptSize * sizeof(intptr_t));
    for (int i = 0; i < rt_scriptsize; i++)
    {
        apScript[i] = B_BIG32(rt_script[i]);
        if (apScript[i] > 50000000)
        {
            apScript[i] = (apScript[i]-50000000)/4;
        }
    }
    Xfree(rt_script);

    for (int i = 0; i < 6144; i++)
    {
        int ptr = (uint16_t)B_BIG16(rt_actorscrptr[i]);
        if (ptr)
            g_tile[i].execPtr = &apScript[ptr];
    }

    for (int i = 0; i <= MAXVOLUMES; i++)
    {
        for (int j = 0; j < MAXLEVELS; j++)
        {
            g_mapInfo[i * MAXLEVELS + j].filename = (char*)Xcalloc(1, 1);
            if (i == 0 && j < ARRAY_SIZE(rt_level_names))
                g_mapInfo[i * MAXLEVELS + j].name = Xstrdup(rt_level_names[j]);
            else
                g_mapInfo[i * MAXLEVELS + j].name = (char*)Xcalloc(1, 1);
        }
    }

    g_maxPlayerHealth = g_player[0].ps->max_player_health = g_player[0].ps->max_shield_amount = 100;

    g_player[0].ps->max_ammo_amount[1] = 192;
    g_player[0].ps->max_ammo_amount[2] = 50;
    g_player[0].ps->max_ammo_amount[3] = 400;
    g_player[0].ps->max_ammo_amount[4] = 48;
    g_player[0].ps->max_ammo_amount[5] = 50;
    g_player[0].ps->max_ammo_amount[6] = 66;
    g_player[0].ps->max_ammo_amount[7] = 99;
    g_player[0].ps->max_ammo_amount[8] = 50;
    g_player[0].ps->max_ammo_amount[9] = 10;
    g_player[0].ps->max_ammo_amount[10] = 99;
    g_player[0].ps->max_ammo_amount[11] = 0;
    g_player[0].ps->max_ammo_amount[12] = 36;
    g_player[0].ps->max_ammo_amount[13] = 20;
    g_player[0].ps->max_ammo_amount[14] = 25;

    const int quote_offset = RT_ROMGetOffset(GO_QUOTEOFFSET);
    const int quote_delta = RT_ROMGetOffset(GO_QUOTEDELTA);
    const int quote_count = 131;

    int32_t *quote_table = (int32_t*)Xmalloc(quote_count * 4);
    RT_ROMSeek(quote_offset);
    if (RT_ROMRead(quote_table, quote_count*4) != quote_count*4)
    {
        initprintf("RT_PrepareScript: file read error\n");
        return 1;
    }
    for (int i = 0; i < quote_count; i++)
    {
        int const offset = B_BIG32(quote_table[i]) + quote_delta;
        C_AllocQuote(i);
        RT_ROMSeek(offset);
        RT_ROMRead(apStrings[i], MAXQUOTELEN-1);
        for (int j = 0; j < MAXQUOTELEN; j++)
        {
            if (apStrings[i][j] == 0)
            {
                for (; j < MAXQUOTELEN; j++)
                    apStrings[i][j] = 0;
                break;
            }
        }
    }
    Xfree(quote_table);

    for (int i = 0; i < ARRAY_SIZE(rt_musicdefs); i++)
    {
        C_DefineMusic(rt_musicdefs[i].volume, rt_musicdefs[i].level, rt_musicdefs[i].filename);
    }

    return 0;
}

static void RT_LoadPalette(void)
{
    const int paletteOffset = RT_ROMGetOffset(GO_PALETTEOFFSET);
    for (int p = 0; p < RT_PALNUM; p++)
    {
        RT_ROMSeek(paletteOffset + 520 * p + 8);
        if (RT_ROMRead(rt_palette[p], 512) != 512)
        {
            initprintf("RT_LoadPalette: file read error");
            return;
        }
        for (int i = 0; i < 256; i++)
        {
            rt_palette[p][i] = B_BIG16(rt_palette[p][i]);
        }
    }
    for (int i = 0; i < 256; i++)
    {
        int t = rt_palette[0][i];
        int r = (t >> 11) & 31;
        int g = (t >> 6) & 31;
        int b = (t >> 1) & 31;
        r = (r << 3) + (r >> 2);
        g = (g << 3) + (g >> 2);
        b = (b << 3) + (b >> 2);
        palette[i*3+0] = r;
        palette[i*3+1] = g;
        palette[i*3+2] = b;
    }

    //for (int i = 1; i < MAXBASEPALS; i++)
    //{
    //    basepaltable[i] = palette;
    //}

    numshades = 32;

    palookup[0] = (char*)Xaligned_alloc(16, (numshades+1) * 256);
    for (int i = 0; i <= numshades; i++)
    {
        for (int j = 0; j < 256; j++)
        {
            palookup[0][i * 256 + j] = j;
        }
    }

    for (int i = 1; i < MAXPALOOKUPS; i++)
    {
        palookup[i] = palookup[0];
    }

#ifdef USE_OPENGL
    for (int i = 0; i < MAXPALOOKUPS; i++)
    {
        palookupfogfactor[i] = 1.f;
    }
#endif

    blendtable[0] = (char*)Xcalloc(1, 256 * 256);

    paletteInitClosestColorMap(palette);

    paletteloaded |= PALETTE_MAIN | PALETTE_SHADE | PALETTE_TRANSLUC;
}

void RT_LoadBoard(int boardnum)
{
    const uint32_t baseOffset = 0x8035a800;
    rt_boardnum = boardnum;
    auto board = &boardinfo[boardnum];
    uint32_t siz = board->dataend - board->datastart;
    char *boardbuf = (char*)Xmalloc(siz);
    RT_ROMSeek(board->datastart);
    if (RT_ROMRead(boardbuf, siz) != siz)
    {
        initprintf("RT_LoadBoard: file read error");
        return;
    }

    int numsprites = board->numsprites;
    numsectors = board->numsector;
    numwalls = board->numwall;

    rt_sky_color[0].x = board->sky[0];
    rt_sky_color[1].x = board->sky[3];
    rt_sky_color[0].y = board->sky[1];
    rt_sky_color[1].y = board->sky[4];
    rt_sky_color[0].z = board->sky[2];
    rt_sky_color[1].z = board->sky[5];

    RT_MS_Reset();

    initspritelists();

    Bmemset(show2dsector, 0, sizeof(show2dsector));
    Bmemset(show2dsprite, 0, sizeof(show2dsprite));
    Bmemset(show2dwall, 0, sizeof(show2dwall));
    Bmemset(editwall, 0, sizeof(editwall));
#ifdef USE_STRUCT_TRACKERS
    Bmemset(sectorchanged, 0, sizeof(sectorchanged));
    Bmemset(spritechanged, 0, sizeof(spritechanged));
    Bmemset(wallchanged, 0, sizeof(wallchanged));
#endif

#ifdef USE_OPENGL
    Polymost_prepare_loadboard();
#endif

    g_player[0].ps->pos.x = board->posx * 2;
    g_player[0].ps->pos.y = board->posy * 2;
    g_player[0].ps->pos.z = board->posz * 32;
    g_player[0].ps->cursectnum = 4; // ???
    g_player[0].ps->over_shoulder_on = 0;
    g_player[0].ps->q16ang = fix16_from_int(board->ang);

    if (rt_sector)
        Xfree(rt_sector);
    if (rt_wall)
        Xfree(rt_wall);

    rt_sector = (rt_sectortype*)Xmalloc(sizeof(rt_sectortype) * numsectors);
    rt_wall = (rt_walltype*)Xmalloc(sizeof(rt_walltype) * numwalls);
    rt_spritetype* rt_sprite = (rt_spritetype*)Xmalloc(sizeof(rt_spritetype) * numsprites);

    RNCDecompress(&boardbuf[board->sectoroffset-baseOffset], (char*)rt_sector);
    RNCDecompress(&boardbuf[board->walloffset-baseOffset], (char*)rt_wall);
    RNCDecompress(&boardbuf[board->spriteoffset-baseOffset], (char*)rt_sprite);

    int vtxnum = 0;

    for (int i = 0; i < numsectors; i++)
    {
        sector[i].ceilingz = B_BIG32(rt_sector[i].ceilingz);
        sector[i].floorz = B_BIG32(rt_sector[i].floorz);
        sector[i].wallptr = B_BIG16(rt_sector[i].wallptr);
        sector[i].wallnum = B_BIG16(rt_sector[i].wallnum);
        sector[i].ceilingstat = B_BIG16(rt_sector[i].ceilingstat);
        sector[i].floorstat = B_BIG16(rt_sector[i].floorstat);
        sector[i].ceilingpicnum = B_BIG16(rt_sector[i].ceilingpicnum);
        sector[i].ceilingheinum = B_BIG16(rt_sector[i].ceilingheinum);
        sector[i].floorpicnum = B_BIG16(rt_sector[i].floorpicnum);
        sector[i].floorheinum = B_BIG16(rt_sector[i].floorheinum);
        sector[i].lotag = B_BIG16(rt_sector[i].lotag);
        sector[i].hitag = B_BIG16(rt_sector[i].hitag);
        sector[i].extra = B_BIG16(rt_sector[i].extra);
        rt_sector[i].floorvertexptr = B_BIG16(rt_sector[i].floorvertexptr);
        rt_sector[i].ceilingvertexptr = B_BIG16(rt_sector[i].ceilingvertexptr);
        sector[i].ceilingshade = rt_sector[i].ceilingshade;
        sector[i].ceilingpal = rt_sector[i].ceilingpal;
        sector[i].ceilingxpanning = rt_sector[i].ceilingxpanning;
        sector[i].ceilingypanning = rt_sector[i].ceilingypanning;
        sector[i].floorshade = rt_sector[i].floorshade;
        sector[i].floorpal = rt_sector[i].floorpal;
        sector[i].floorxpanning = rt_sector[i].floorxpanning;
        sector[i].floorypanning = rt_sector[i].floorypanning;
        sector[i].visibility = rt_sector[i].visibility;
        sector[i].fogpal = 0;

        vtxnum += rt_sector[i].floorvertexnum + rt_sector[i].ceilingvertexnum;
    }

    for (int i = 0; i < numwalls; i++)
    {
        wall[i].x = B_BIG32(rt_wall[i].x);
        wall[i].y = B_BIG32(rt_wall[i].y);
        wall[i].point2 = B_BIG16(rt_wall[i].point2);
        wall[i].nextwall = B_BIG16(rt_wall[i].nextwall);
        wall[i].nextsector = B_BIG16(rt_wall[i].nextsector);
        wall[i].cstat = B_BIG16(rt_wall[i].cstat);
        wall[i].picnum = B_BIG16(rt_wall[i].picnum);
        wall[i].overpicnum = B_BIG16(rt_wall[i].overpicnum);
        wall[i].lotag = B_BIG16(rt_wall[i].lotag);
        wall[i].hitag = B_BIG16(rt_wall[i].hitag);
        wall[i].extra = B_BIG16(rt_wall[i].extra);
        wall[i].shade = rt_wall[i].shade;
        wall[i].pal = rt_wall[i].pal;
        wall[i].xrepeat = rt_wall[i].xrepeat;
        wall[i].yrepeat = rt_wall[i].yrepeat;
        wall[i].xpanning = rt_wall[i].xpanning;
        wall[i].ypanning = rt_wall[i].ypanning;
        rt_wall[i].sectnum = B_BIG16(rt_wall[i].sectnum);
    }

    for (int i = 0; i < numsprites; i++)
    {
        sprite[i].x = B_BIG32(rt_sprite[i].x);
        sprite[i].y = B_BIG32(rt_sprite[i].y);
        sprite[i].z = B_BIG32(rt_sprite[i].z);
        sprite[i].cstat = B_BIG16(rt_sprite[i].cstat);
        sprite[i].picnum = B_BIG16(rt_sprite[i].picnum);
        sprite[i].sectnum = B_BIG16(rt_sprite[i].sectnum);
        sprite[i].statnum = B_BIG16(rt_sprite[i].statnum);
        sprite[i].ang = B_BIG16(rt_sprite[i].ang);
        sprite[i].owner = B_BIG16(rt_sprite[i].owner);
        sprite[i].xvel = B_BIG16(rt_sprite[i].xvel);
        sprite[i].yvel = B_BIG16(rt_sprite[i].yvel);
        sprite[i].zvel = B_BIG16(rt_sprite[i].zvel);
        sprite[i].lotag = B_BIG16(rt_sprite[i].lotag);
        sprite[i].hitag = B_BIG16(rt_sprite[i].hitag);
        sprite[i].extra = B_BIG16(rt_sprite[i].extra);
        sprite[i].shade = rt_sprite[i].shade;
        sprite[i].pal = rt_sprite[i].pal;
        sprite[i].xrepeat = rt_sprite[i].xrepeat;
        sprite[i].yrepeat = rt_sprite[i].yrepeat;
        sprite[i].xoffset = rt_sprite[i].xoffset;
        sprite[i].yoffset = rt_sprite[i].yoffset;
        sprite[i].clipdist = rt_sprite[i].clipdist;
        sprite[i].blend = 0;
    }
    for (int i = 0; i < numsprites; i++)
    {
        insertsprite(sprite[i].sectnum, sprite[i].statnum);
    }
    updatesector(g_player[0].ps->pos.x, g_player[0].ps->pos.y, &g_player[0].ps->cursectnum);
    g_loadedMapVersion = 7;
#ifdef YAX_ENABLE
    yax_update(1);
#endif

    calc_sector_reachability();

    if (rt_sectvtx)
        Xfree(rt_sectvtx);

    rt_vtxnum = vtxnum * 3;
    rt_sectvtx = (rt_vertex_t*)Xmalloc(sizeof(rt_vertex_t) * vtxnum * 3);
    RNCDecompress(boardbuf, (char*)rt_sectvtx);

    for (int i = 0; i < vtxnum * 3; i++)
    {
        rt_sectvtx[i].x = B_BIG16(rt_sectvtx[i].x);
        rt_sectvtx[i].y = B_BIG16(rt_sectvtx[i].y);
        rt_sectvtx[i].z = B_BIG16(rt_sectvtx[i].z);
        rt_sectvtx[i].u = B_BIG16(rt_sectvtx[i].u);
        rt_sectvtx[i].v = B_BIG16(rt_sectvtx[i].v);
    }

    Xfree(boardbuf);
    Xfree(rt_sprite);

    if (boardnum == 27)
        RT_LoadBOSS2MDL();

    memset(explosions, 0, sizeof(explosions));
    memset(smoke, 0, sizeof(smoke));

    ud.statusbarflags |= STATUSBAR_NOFULL | STATUSBAR_NOOVERLAY | STATUSBAR_NOFRAGBAR;
    if (ud.screen_size > 4)
        ud.screen_size = 4;
}

int RT_NextLevel(void)
{
#if 0
    if (ud.multimode > 1 && !ud.coop && dukematch_mode != 1)
    {
        if (rt_levelnum == 1 && rt_level7unlock)
            ud.secretlevel = 1;
        else
        {
            if ((rt_levelnum == 15 && rt_level18unlock)
                || (rt_levelnum == 23 && rt_level28unlock)
                || (rt_levelnum == 26 && rt_level29unlock)
                || (rt_levelnum == 32 && rt_level33unlock))
                ud.secretlevel = 1;
        }
    }
#endif
    int nextlevel = rt_levelnum;
    if (!ud.secretlevel)
    {
        switch (rt_levelnum)
        {
        case 6:
            nextlevel = 8;
            break;
        case 7:
            nextlevel = 2;
            break;
        case 17:
            nextlevel = 19;
            break;
        case 18:
            nextlevel = 16;
            break;
        case 27:
            nextlevel = 30;
            break;
        case 28:
            nextlevel = 24;
            break;
        case 29:
            nextlevel = 27;
            break;
        case 32:
            nextlevel = 0;
            break;
        case 33:
            nextlevel = 0;
            break;
        default:
            nextlevel++;
            break;
        }
    }
    else
    {
        switch (rt_levelnum)
        {
        case 1:
            // rt_level7unlock = 1;
            nextlevel = 7;
            break;
        case 7:
            nextlevel = 2;
            break;
        case 15:
            // rt_level18unlock = 1;
            nextlevel = 18;
            break;
        case 18:
            nextlevel = 16;
            break;
        case 23:
            // rt_level28unlock = 1;
            nextlevel = 28;
            break;
        case 26:
            // rt_level29unlock = 1;
            nextlevel = 29;
            break;
        case 28:
            nextlevel = 24;
            break;
        case 29:
            nextlevel = 27;
            break;
        case 32:
            // rt_level33unlock = 1;
            nextlevel = 33;
            break;
        case 33:
            nextlevel = 33;
            break;
        }
    }
    return nextlevel;
}


code:
// Copyright: 2020 Nuke.YKT, EDuke32 developers
// License: GPLv2

#pragma once

#include "vfs.h"
#include "reality_defs.h"
#include "reality_player.h"
#include "reality_render.h"
#include "reality_sbar.h"
#include "reality_screens.h"
#include "reality_sound.h"
#include "reality_music.h"
#include "reality_util.h"

enum {
    GO_SCRIPTOFFSET = 0,
    GO_ACTOROFFSET,
    GO_BOARDOFFSET,
    GO_QUOTEOFFSET,
    GO_QUOTEDELTA,
    GO_PALETTEOFFSET,
    GO_MUSICCTLOFFSET,
    GO_MUSICTBLOFFSET,
    GO_MUSICSEQOFFSET,
    GO_SOUNDCTLOFFSET,
    GO_SOUNDTBLOFFSET,
    GO_SOUNDVOOFFSET,
    GO_SOUNDPEOFFSET,
    GO_SOUNDPSFFSET,
    GO_SOUNDMOFFSET,
    GO_SOUNDRATEOFFSET,
    GO_TILEINFOOFFSET,
    GO_TILEDATAOFFSET,
    GO_BOSSMDLOFFSET,
    GO_BOSSTRISOFFSET,
    GO_MAXOFFSETS
};

extern buildvfs_kfd rt_group;
// extern int rt_gamestate, rt_gamestatus;
extern uint16_t rt_palette[RT_PALNUM][256];
extern int rt_vtxnum;
extern rt_vertex_t *rt_sectvtx;
extern rt_walltype *rt_wall;
extern rt_sectortype *rt_sector;
extern int rt_boardnum;
extern int rt_levelnum;
extern const char* rt_level_names[];

buildvfs_kfd RT_InitGRP(const char *filename);
void RT_Init(void);
void RT_ROMSeek(int offset);
int RT_ROMRead(void *ptr, int count);
int RT_ROMGetOffset(int offset);
int RT_PrepareScript(void);
void RT_LoadBoard(int boardnum);
void RT_Execute(int spriteNum, int playerNum, int playerDist);
int RT_NextLevel(void);


code:
// Copyright: 2020 Nuke.YKT, EDuke32 developers
// License: GPLv2
#pragma once

#include "compat.h"

#define RT_TILENUM 2851
#define RT_BOARDNUM 34
#define RT_PALNUM 12

#define RT_TILE8BIT 0x8000

enum rt_con_t {
    RT_CON_DEFINELEVELNAME,     // 0
    RT_CON_ACTOR,               // 1
    RT_CON_ADDAMMO,             // 2
    RT_CON_IFRND,               // 3
    RT_CON_ENDA,                // 4
    RT_CON_IFCANSEE,            // 5
    RT_CON_IFHITWEAPON,         // 6
    RT_CON_ACTION,              // 7
    RT_CON_IFPDISTL,            // 8
    RT_CON_IFPDISTG,            // 9
    RT_CON_ELSE,                // 10
    RT_CON_STRENGTH,            // 11
    RT_CON_BREAK,               // 12
    RT_CON_SHOOT,               // 13
    RT_CON_PALFROM,             // 14
    RT_CON_SOUND,               // 15
    RT_CON_FALL,                // 16
    RT_CON_STATE,               // 17
    RT_CON_ENDS,                // 18
    RT_CON_DEFINE,              // 19
    RT_CON_COMMENT,             // 20
    RT_CON_IFAI,                // 21
    RT_CON_KILLIT,              // 22
    RT_CON_ADDWEAPON,           // 23
    RT_CON_AI,                  // 24
    RT_CON_ADDPHEALTH,          // 25
    RT_CON_IFDEAD,              // 26
    RT_CON_IFSQUISHED,          // 27
    RT_CON_SIZETO,              // 28
    RT_CON_LEFTBRACE,           // 29
    RT_CON_RIGHTBRACE,          // 30
    RT_CON_SPAWN,               // 31
    RT_CON_MOVE,                // 32
    RT_CON_IFWASWEAPON,         // 33
    RT_CON_IFACTION,            // 34
    RT_CON_IFACTIONCOUNT,       // 35
    RT_CON_RESETACTIONCOUNT,    // 36
    RT_CON_DEBRIS,              // 37
    RT_CON_PSTOMP,              // 38
    RT_CON_BLOCKCOMMENT,        // 39
    RT_CON_CSTAT,               // 40
    RT_CON_IFMOVE,              // 41
    RT_CON_RESETPLAYER,         // 42
    RT_CON_IFONWATER,           // 43
    RT_CON_IFINWATER,           // 44
    RT_CON_IFCANSHOOTTARGET,    // 45
    RT_CON_IFCOUNT,             // 46
    RT_CON_RESETCOUNT,          // 47
    RT_CON_ADDINVENTORY,        // 48
    RT_CON_IFACTORNOTSTAYPUT,   // 49
    RT_CON_HITRADIUS,           // 50
    RT_CON_IFP,                 // 51
    RT_CON_COUNT,               // 52
    RT_CON_IFACTOR,             // 53
    RT_CON_MUSIC,               // 54
    RT_CON_INCLUDE,             // 55
    RT_CON_IFSTRENGTH,          // 56
    RT_CON_DEFINESOUND,         // 57
    RT_CON_GUTS,                // 58
    RT_CON_IFSPAWNEDBY,         // 59
    RT_CON_GAMESTARTUP,         // 60
    RT_CON_WACKPLAYER,          // 61
    RT_CON_IFGAPZL,             // 62
    RT_CON_IFHITSPACE,          // 63
    RT_CON_IFOUTSIDE,           // 64
    RT_CON_IFMULTIPLAYER,       // 65
    RT_CON_OPERATE,             // 66
    RT_CON_IFINSPACE,           // 67
    RT_CON_DEBUG,               // 68
    RT_CON_ENDOFGAME,           // 69
    RT_CON_IFBULLETNEAR,        // 70
    RT_CON_IFRESPAWN,           // 71
    RT_CON_IFFLOORDISTL,        // 72
    RT_CON_IFCEILINGDISTL,      // 73
    RT_CON_SPRITEPAL,           // 74
    RT_CON_IFPINVENTORY,        // 75
    RT_CON_BETANAME,            // 76
    RT_CON_CACTOR,              // 77
    RT_CON_IFPHEALTHL,          // 78
    RT_CON_DEFINEQUOTE,         // 79
    RT_CON_QUOTE,               // 80
    RT_CON_IFINOUTERSPACE,      // 81
    RT_CON_IFNOTMOVING,         // 82
    RT_CON_RESPAWNHITAG,        // 83
    RT_CON_TIP,                 // 84
    RT_CON_IFSPRITEPAL,         // 85
    RT_CON_MONEY,               // 86
    RT_CON_SOUNDONCE,           // 87
    RT_CON_ADDKILLS,            // 88
    RT_CON_STOPSOUND,           // 89
    RT_CON_IFAWAYFROMWALL,      // 90
    RT_CON_IFCANSEETARGET,      // 91
    RT_CON_GLOBALSOUND,         // 92
    RT_CON_LOTSOFGLASS,         // 93
    RT_CON_IFGOTWEAPONCE,       // 94
    RT_CON_GETLASTPAL,          // 95
    RT_CON_PKICK,               // 96
    RT_CON_MIKESND,             // 97
    RT_CON_USERACTOR,           // 98
    RT_CON_SIZEAT,              // 99
    RT_CON_ADDSTRENGTH,         // 100
    RT_CON_CSTATOR,             // 101
    RT_CON_MAIL,                // 102
    RT_CON_PAPER,               // 103
    RT_CON_TOSSWEAPON,          // 104
    RT_CON_SLEEPTIME,           // 105
    RT_CON_NULLOP,              // 106
    RT_CON_DEFINEVOLUMENAME,    // 107
    RT_CON_DEFINESKILLNAME,     // 108
    RT_CON_IFNOSOUNDS,          // 109
    RT_CON_CLIPDIST,            // 110
    RT_CON_IFANGDIFFL,          // 111
};

#pragma pack(push, 1)

struct tileinfo_t {
    int32_t fileoff;
    int32_t waloff;
    int32_t picanm;
    int16_t sizx;
    int16_t sizy;
    uint16_t filesiz;
    int16_t dimx;
    int16_t dimy;
    uint16_t flags;
    int16_t tile;
    uint8_t pad[2];
};

struct boardinfo_t {
    uint32_t datastart;
    uint32_t dataend;
    uint32_t sectoroffset;
    uint32_t walloffset;
    uint32_t spriteoffset;
    uint32_t numsector;
    uint32_t numsprites;
    uint32_t numwall;
    uint32_t posx;
    uint32_t posy;
    uint32_t posz;
    uint32_t ang;
    float sky[6];
};

struct rt_sectortype {
    int32_t ceilingz;
    int32_t floorz;
    int16_t wallptr;
    int16_t wallnum;
    int16_t ceilingstat;
    int16_t floorstat;
    int16_t ceilingpicnum;
    int16_t ceilingheinum;
    int16_t floorpicnum;
    int16_t floorheinum;
    int16_t lotag;
    int16_t hitag;
    int16_t extra;
    int16_t floorvertexptr;
    int16_t ceilingvertexptr;
    int8_t ceilingshade;
    uint8_t ceilingpal;
    uint8_t ceilingxpanning;
    uint8_t ceilingypanning;
    int8_t floorshade;
    uint8_t floorpal;
    uint8_t floorxpanning;
    uint8_t floorypanning;
    uint8_t visibility;
    uint8_t floorvertexnum;
    uint8_t ceilingvertexnum;
    uint8_t pad2[3];
};

struct rt_walltype {
    int32_t x, y;
    int16_t point2;
    int16_t nextwall;
    int16_t nextsector;
    int16_t cstat;
    int16_t picnum;
    int16_t overpicnum;
    int16_t lotag;
    int16_t hitag;
    int16_t extra;
    int16_t sectnum;
    int8_t shade;
    uint8_t pal;
    uint8_t xrepeat;
    uint8_t yrepeat;
    uint8_t xpanning;
    uint8_t ypanning;
    uint8_t pad2[2];
};

struct rt_spritetype {
    int32_t x, y, z;
    int16_t cstat;
    int16_t picnum;
    int16_t sectnum;
    int16_t statnum;
    int16_t ang;
    int16_t owner;
    int16_t xvel;
    int16_t yvel;
    int16_t zvel;
    int16_t lotag;
    int16_t hitag;
    int16_t extra;
    int8_t shade;
    uint8_t pal;
    uint8_t clipdist;
    uint8_t xrepeat;
    uint8_t yrepeat;
    uint8_t xoffset;
    uint8_t yoffset;
    uint8_t filler;
};

struct rt_vertex_t {
    int16_t x, y, z, u, v;
};

#pragma pack(pop)


code:
// Copyright: 2020 Nuke.YKT, EDuke32 developers
// License: GPLv2
#include "compat.h"
#include "multivoc.h"
#include "reality.h"
#include "../duke3d.h"

extern int MV_Channels, MV_MixRate;

#define RTSEMITONE 1.05946309

//
// Uses info and snippets from this code:
// https://github.com/jombo23/N64-Tools/blob/master/N64%20Midi%20Tool/N64MidiLibrary/MidiParse.cpps
//

rt_CTL_t *musicCtl;
char *seqBuffer;
uint32_t seqDivision;
uint32_t seqTempo;

struct trackinfo_t {
    int status;
    uint32_t counter;
    uint8_t lastcmd;
    char *ptr;
    char *seq;
    char *altPattern;
    int altOffset;
    int altLength;
};

trackinfo_t tracks[16];

#define RTMUSICVOICES 64

struct channel_t {
    int volume;
    int pan;
    int program;
    int sustain;
};

enum {
    VS_FREE = 0,
    VS_RELEASED,
    VS_ACTIVE
};

enum {
    VE_ATTACK = 0,
    VE_DECAY,
    VE_SUSTAIN,
    VE_RELEASE
};

struct voice_t {
    int status;
    int vel;
    rt_sound_t *rsnd;
    rt_soundinstance_t decodeState;
    int duration;
    double phase;
    double step;
    int16_t *ptr;
    uint32_t length;
    channel_t *chan;
    int note;
    double envVol;
    double envStep;
    double envTarget;
    int envTimer;
    int envState;
};

channel_t channel[16];

voice_t voicePool[RTMUSICVOICES];

float pantable[128];

voice_t *RT_FindFreeVoice(void)
{
    for (int i = 0; i < RTMUSICVOICES; i++)
    {
        auto voice = &voicePool[i];
        if (voice->status == VS_FREE)
        {
            return voice;
        }
    }
    for (int i = 0; i < RTMUSICVOICES; i++)
    {
        auto voice = &voicePool[i];
        if (voice->status == VS_RELEASED)
        {
            return voice;
        }
    }
    return nullptr;
}

void RT_LoadRTSound(rt_sound_t *snd)
{
    if (snd->ptr)
        return;
    RT_ROMSeek(snd->wave->base);
    int l = snd->wave->len;
    snd->lock = 200;
    g_cache.allocateBlock((intptr_t *)&snd->ptr, l, &snd->lock);
    RT_ROMRead(snd->ptr, l);
}

void RT_ChanNoteOn(channel_t *chan, int note, int vel, int duration, int perc)
{
    auto voice = RT_FindFreeVoice();
    if (!voice)
        return;

    rt_instrument_t *inst = perc ? musicCtl->bank[0]->perc : musicCtl->bank[0]->inst[chan->program];
    rt_sound_t *rsnd = nullptr;

    for (int i = 0; i < inst->sound_count; i++)
    {
        if (inst->sounds[i]->key->keymin <= note && inst->sounds[i]->key->keymax >= note
            && inst->sounds[i]->key->velocitymin <= vel && inst->sounds[i]->key->velocitymax >= vel)
            rsnd = inst->sounds[i];
    }

    if (!rsnd)
        return;

    RT_LoadRTSound(rsnd);

    auto snd = &voice->decodeState;
    memset(snd, 0, sizeof(rt_soundinstance_t));
    snd->status = 1;
    snd->ptr = snd->snd = rsnd->ptr;
    snd->rtsound = rsnd;
    if (rsnd->wave->adpcm && rsnd->wave->adpcm->loop)
    {
        snd->loop = rsnd->wave->adpcm->loop->count;
        snd->loop_start = rsnd->wave->adpcm->loop->start;
        snd->loop_end = rsnd->wave->adpcm->loop->end;
    }

    voice->vel = vel;
    voice->rsnd = rsnd;
    voice->chan = chan;
    voice->note = note;
    voice->duration = duration;
    voice->status = VS_ACTIVE;
    voice->envState = VE_ATTACK;
    voice->envVol = 0.0;
    voice->envTarget = rsnd->env->attack_volume;
    voice->envTimer = MV_MixRate * (rsnd->env->attack_time / 1000000.0);
    voice->envStep = (double)(voice->envTarget - voice->envVol) / (double)voice->envTimer;

    voice->step = pow(RTSEMITONE, note - rsnd->key->keybase + rsnd->key->detune / 100.0) * musicCtl->bank[0]->rate / MV_MixRate;
}

void RT_ChanNoteOff(channel_t *chan, int note)
{
    for (int i = 0; i < RTMUSICVOICES; i++)
    {
        auto voice = &voicePool[i];
        if (voice->status == VS_ACTIVE && voice->chan == chan && voice->note == note)
        {
            voice->status = VS_RELEASED;

            voice->envState = VE_RELEASE;
            voice->envTarget = 0.0;
            voice->envTimer = MV_MixRate * (voice->rsnd->env->release_time / 1000000.0);
            voice->envStep = (double)(voice->envTarget - voice->envVol) / (double)voice->envTimer;
        }
    }
}

uint8_t RT_ReadMidiByte(trackinfo_t *track)
{
    uint8_t b;
    if (track->altPattern)
    {
        b = track->altPattern[track->altOffset++];
        if (track->altOffset == track->altLength)
        {
            track->altPattern = nullptr;
            track->altOffset = 0;
            track->altLength = 0;
        }
    }
    else
    {
        b = *track->ptr++;
        if (b == 0xfe && *track->ptr != 0xfe)
        {
            uint8_t repeatFirstByte = *track->ptr++;
            uint16_t repeatDistanceFromBeginningMarker = (repeatFirstByte << 8) | (*track->ptr++);
            uint8_t repeatCount = *track->ptr++;
            track->altPattern = track->ptr - 4 - repeatDistanceFromBeginningMarker;
            track->altOffset = 0;
            track->altLength = repeatCount;
            b = track->altPattern[track->altOffset++];
        }
        else if (b == 0xfe && *track->ptr == 0xfe)
        {
            track->ptr++;
        }
        if (track->altOffset == track->altLength && track->altPattern)
        {
            track->altPattern = nullptr;
            track->altOffset = 0;
            track->altLength = 0;
        }
    }
    return b;
}

uint32_t RT_ReadMidiDelay(trackinfo_t *track)
{
    uint8_t b;
    uint32_t ret = 0;
    do
    {
        b = RT_ReadMidiByte(track);
        ret <<= 7;
        ret |= (b & 0x7f);
    } while (b & 0x80);
    return ret;
}

void RT_TrackAdvance(trackinfo_t *track)
{
    if (!track->status)
        return;
    while(track->counter == 0)
    {
        uint8_t cmd = RT_ReadMidiByte(track);
        uint8_t b1, b2;
        if ((cmd & 0x80) == 0)
        {
            b1 = cmd;
            cmd = track->lastcmd;
        }
        else
        {
            b1 = RT_ReadMidiByte(track);
        }
        track->lastcmd = cmd;
        if (cmd == 0xff)
        {
            uint8_t metacmd = b1;
            switch (metacmd)
            {
            case 0x51: // Tempo
            {
                uint8_t b1 = RT_ReadMidiByte(track);
                uint8_t b2 = RT_ReadMidiByte(track);
                uint8_t b3 = RT_ReadMidiByte(track);
                seqTempo = (b1 << 16) | (b2 << 8) | b3;
                break;
            }
            case 0x2e: // Loop start
                RT_ReadMidiByte(track);
                RT_ReadMidiByte(track);
                break;
            case 0x2d: // Loop start
            {
                track->ptr += 2;
                uint8_t b1 = *track->ptr++;
                uint8_t b2 = *track->ptr++;
                uint8_t b3 = *track->ptr++;
                uint8_t b4 = *track->ptr++;
                uint32_t offset;
                offset = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
                track->ptr -= offset;
                break;
            }
            case 0x2f: // EOT
                track->status = 0;
                return;
            }
        }
        else
        {
            uint8_t ch = cmd & 0x0f;
            auto chan = &channel[ch];
            switch (cmd & 0xf0)
            {
            case 0xb0: // Control
                b2 = RT_ReadMidiByte(track);
                switch (b1)
                {
                case 7:
                    chan->volume = b2;
                    break;
                case 10:
                    chan->pan = b2;
                    break;
                }
                break;
            case 0xc0: // Program change
                chan->program = b1;
                break;
            case 0x90: // Note On
            {
                b2 = RT_ReadMidiByte(track);
                int duration = RT_ReadMidiDelay(track);

                if (b2 == 0) // Note Off
                {
                    RT_ChanNoteOff(chan, b1);
                }
                else
                {
                    RT_ChanNoteOn(chan, b1, b2, duration, ch == 9);
                }

                break;
            }
            }
        }
        track->counter = RT_ReadMidiDelay(track);
    }
    track->counter--;
}

void RT_AdvanceNotes(void)
{
    for (int i = 0; i < RTMUSICVOICES; i++)
    {
        auto voice = &voicePool[i];
        if (voice->status == VS_ACTIVE && voice->duration)
        {
            if (--voice->duration == 0)
            {
                voice->status = VS_RELEASED;

                voice->envState = VE_RELEASE;
                voice->envTarget = 0.0;
                voice->envTimer = MV_MixRate * (voice->rsnd->env->release_time / 1000000.0);
                voice->envStep = (double)(voice->envTarget - voice->envVol) / (double)voice->envTimer;
            }
        }
    }
}

int serviceTimer = 0;

void RT_MusicService(void)
{
    auto routinebuf = MV_GetMusicRoutineBuffer();
    int16_t *buffer = (int16_t*)routinebuf.buffer;
    int sampless = routinebuf.size / (MV_Channels *2);

    for (int j = 0; j < sampless; j++)
    {
        while (serviceTimer >= MV_MixRate)
        {
            for (int j = 0; j < 16; j++)
            {
                if (!tracks[j].seq)
                    continue;
                RT_TrackAdvance(&tracks[j]);
            }
            RT_AdvanceNotes();
            serviceTimer -= MV_MixRate;
        }
        serviceTimer += (1000000LL * seqDivision / seqTempo);
        int left = 0, right = 0;
        for (int i = 0; i < RTMUSICVOICES; i++)
        {
            auto voice = &voicePool[i];
            if (voice->status)
            {
                if (voice->length == 0)
                {
                    RT_SoundDecode((const char**)&voice->ptr, &voice->length, &voice->decodeState);
                    if (voice->length == 0)
                    {
                        voice->status = VS_FREE;
                        continue;
                    }
                }
                float volume = voice->vel * voice->chan->volume * voice->rsnd->sample_volume / (128.f * 128.f * 256.f) * 0.5f;
                volume *= voice->envVol / 128.f;
                volume *= ud.config.MusicVolume / 256.f;
                int pan = voice->chan->pan + (voice->rsnd->sample_pan - 64);
                if (pan < 0)
                    pan = 0;
                if (pan > 127)
                    pan = 127;
                int s1 = *voice->ptr;
                int s2 = 0;
                if (voice->length <= 1)
                    s2 = s1; // FIXME
                else
                    s2 = *(voice->ptr + 1);
                int64_t cphase = (int64_t)voice->phase;
                double interp = voice->phase - cphase;
                left += (s2 * interp + s1 * (1.0 - interp)) * volume * pantable[127 - pan];
                right += (s2 * interp + s1 * (1.0 - interp)) * volume * pantable[pan];
                voice->phase += voice->step;
                int todo = (int64_t)voice->phase - cphase;
                while (todo > 0)
                {
                    int samples = min<int>(todo, voice->length);
                    voice->length -= samples;
                    voice->ptr += samples;
                    voice->phase -= samples;
                    todo -= samples;
                    if (voice->length == 0)
                    {
                        RT_SoundDecode((const char**)&voice->ptr, &voice->length, &voice->decodeState);
                        if (voice->length == 0)
                        {
                            voice->status = VS_FREE;
                            break;
                        }
                    }
                }

                if (--voice->envTimer <= 0)
                {
                    if (voice->envState == VE_ATTACK)
                    {
                        voice->envState = VE_DECAY;
                        voice->envVol = voice->envTarget;
                        voice->envTarget = voice->rsnd->env->decay_volume;
                        voice->envTimer = MV_MixRate * (voice->rsnd->env->decay_time / 1000000.0);
                        voice->envStep = (double)(voice->envTarget - voice->envVol) / (double)voice->envTimer;
                    }
                    else if (voice->envState == VE_DECAY)
                    {
                        voice->envState = VE_SUSTAIN;
                        voice->envVol = voice->envTarget;
                        voice->envStep = 0;
                        voice->envTimer = 0;
                    }
                    else if (voice->envState == VE_RELEASE)
                    {
                        voice->status = VS_FREE;
                    }
                }
                else
                {
                    voice->envVol += voice->envStep;
                }
            }
        }
        *buffer++ = clamp(left, INT16_MIN, INT16_MAX);
        *buffer++ = clamp(right, INT16_MIN, INT16_MAX);
    }
}

void RT_MusicInit(void)
{
    static const uint32_t musicCtlOffset = RT_ROMGetOffset(GO_MUSICCTLOFFSET);
    static const uint32_t musicTblOffset = RT_ROMGetOffset(GO_MUSICTBLOFFSET);
    musicCtl = RT_LoadCTL(musicCtlOffset, musicTblOffset);
    static const uint32_t musicSeqOffset = RT_ROMGetOffset(GO_MUSICSEQOFFSET);
    uint32_t offset;
    RT_ROMSeek(musicSeqOffset + 4);
    RT_ROMRead(&offset, sizeof(uint32_t));
    offset = B_BIG32(offset);
    uint32_t siz;
    RT_ROMSeek(musicSeqOffset + 8);
    RT_ROMRead(&siz, sizeof(uint32_t));
    siz = B_BIG32(siz);
    seqBuffer = (char*)Xmalloc(siz);
    if (!seqBuffer)
        return;
    RT_ROMSeek(musicSeqOffset + offset);
    RT_ROMRead(seqBuffer, siz);
    for (int i = 0; i < 16; i++)
    {
        uint32_t trackOffset = *(uint32_t*)&seqBuffer[i * 4];
        trackOffset = B_BIG32(trackOffset);
        tracks[i].seq = trackOffset ? seqBuffer + trackOffset : nullptr;
    }
    seqDivision = *(uint32_t*)&seqBuffer[64];
    seqDivision = B_BIG32(seqDivision);

    for (int i = 0; i < 128; i++)
    {
        pantable[i] = sinf((fPI / 2.f) * i / 128.f);
    }
}

int rt_musicactive = 0;

void RT_PlaySong(void)
{
    if (!musicCtl || !seqBuffer || rt_musicactive)
        return;

    memset(voicePool, 0, sizeof(voicePool));
    memset(channel, 0, sizeof(channel));
    seqTempo = 650050;
    for (int i = 0; i < 16; i++)
    {
        auto track = &tracks[i];
        auto seq = track->seq;
        memset(track, 0, sizeof(trackinfo_t));
        track->ptr = track->seq = seq;
        if (track->ptr)
        {
            track->counter = RT_ReadMidiDelay(track);
            track->status = 1;
        }
        track->altPattern = nullptr;
    }
    MV_HookMusicRoutine(RT_MusicService);
    rt_musicactive = 1;
}

void RT_PauseSong(bool paused)
{
    if (!rt_musicactive)
        return;
    if (paused)
        MV_UnhookMusicRoutine();
    else
        MV_HookMusicRoutine(RT_MusicService);
}

void RT_StopSong(void)
{
    if (!rt_musicactive)
        return;
    MV_UnhookMusicRoutine();
    rt_musicactive = 0;
}


code:
// Copyright: 2020 Nuke.YKT, EDuke32 developers
// License: GPLv2
#pragma once

void RT_MusicInit(void);
void RT_PlaySong(void);
void RT_StopSong(void);
void RT_PauseSong(bool paused);