diff --git a/.gitignore b/.gitignore index 347bb6f4..391fe2dd 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,10 @@ dist/ *.dsg build.xml nbproject/ +.gradle +gradle/ +gradlew +gradlew.bat # Intellij *.iml diff --git a/classic.cfg b/classic.cfg new file mode 100644 index 00000000..a1758871 --- /dev/null +++ b/classic.cfg @@ -0,0 +1,43 @@ +mouse_sensitivity 5 +sfx_volume 8 +music_volume 8 +show_messages 1 +key_right 77 +key_left 75 +key_up 72 +key_down 80 +key_strafeleft 51 +key_straferight 52 +key_fire 29 +key_use 57 +key_strafe 56 +key_speed 54 +use_mouse 1 +mouseb_fire 0 +mouseb_strafe 1 +mouseb_forward 2 +use_joystick 0 +joyb_fire 0 +joyb_strafe 1 +joyb_use 3 +joyb_speed 2 +screenblocks 10 +detaillevel 0 +snd_channels 8 +snd_musicdevice 3 +snd_sfxdevice 3 +snd_sbport 0 +snd_sbirq 0 +snd_sbdma 0 +snd_mport 0 +usegamma 0 +chatmacro0 "No" +chatmacro1 "I'm ready to kick butt!" +chatmacro2 "I'm OK." +chatmacro3 "I'm not looking too good!" +chatmacro4 "Help!" +chatmacro5 "You suck!" +chatmacro6 "Next time, scumbag..." +chatmacro7 "Come here!" +chatmacro8 "I'll take care of it." +chatmacro9 "Yes" diff --git a/src/automap/IAutoMap.java b/src/automap/IAutoMap.java index 1bd0618f..7faef524 100644 --- a/src/automap/IAutoMap.java +++ b/src/automap/IAutoMap.java @@ -5,30 +5,30 @@ import static doom.SourceCode.AM_Map.AM_Stop; import doom.event_t; -public interface IAutoMap { +public interface IAutoMap { + // Used by ST StatusBar stuff. - public final int AM_MSGHEADER =(('a'<<24)+('m'<<16)); - public final int AM_MSGENTERED= (AM_MSGHEADER | ('e'<<8)); - public final int AM_MSGEXITED= (AM_MSGHEADER | ('x'<<8)); + public final int AM_MSGHEADER = (('a' << 24) + ('m' << 16)); + public final int AM_MSGENTERED = (AM_MSGHEADER | ('e' << 8)); + public final int AM_MSGEXITED = (AM_MSGHEADER | ('x' << 8)); // Color ranges for automap. Actual colors are bit-depth dependent. - - public final int REDRANGE= 16; - public final int BLUERANGE =8; - public final int GREENRANGE =16; - public final int GRAYSRANGE =16; - public final int BROWNRANGE =16; - public final int YELLOWRANGE =1; - - public final int YOURRANGE =0; - public final int WALLRANGE =REDRANGE; - public final int TSWALLRANGE =GRAYSRANGE; - public final int FDWALLRANGE =BROWNRANGE; - public final int CDWALLRANGE =YELLOWRANGE; - public final int THINGRANGE =GREENRANGE; - public final int SECRETWALLRANGE =WALLRANGE; - public final int GRIDRANGE =0; - + public final int REDRANGE = 16; + public final int BLUERANGE = 8; + public final int GREENRANGE = 16; + public final int GRAYSRANGE = 16; + public final int BROWNRANGE = 16; + public final int YELLOWRANGE = 1; + + public final int YOURRANGE = 0; + public final int WALLRANGE = REDRANGE; + public final int TSWALLRANGE = GRAYSRANGE; + public final int FDWALLRANGE = BROWNRANGE; + public final int CDWALLRANGE = YELLOWRANGE; + public final int THINGRANGE = GREENRANGE; + public final int SECRETWALLRANGE = WALLRANGE; + public final int GRIDRANGE = 0; + // Called by main loop. @AM_Map.C(AM_Responder) public boolean Responder(event_t ev); @@ -38,8 +38,8 @@ public interface IAutoMap { // Called by main loop, // called instead of view drawer if automap active. - public void Drawer (); - + public void Drawer(); + // Added to be informed of gamma changes - Good Sign 2017/04/05 public void Repalette(); diff --git a/src/automap/Map.java b/src/automap/Map.java index b52f7d92..02e3de59 100644 --- a/src/automap/Map.java +++ b/src/automap/Map.java @@ -169,33 +169,61 @@ // DESCRIPTION: the automap code // // ----------------------------------------------------------------------------- - -import static data.Defines.*; -import static data.Limits.*; -import static data.Tables.*; +import static data.Defines.MAPBLOCKUNITS; +import static data.Defines.PLAYERRADIUS; +import static data.Defines.pw_allmap; +import static data.Defines.pw_invisibility; +import static data.Limits.MAXINT; +import static data.Limits.MAXPLAYERS; +import static data.Tables.finecosine; +import static data.Tables.finesine; +import static data.Tables.toBAMIndex; import doom.DoomMain; import doom.SourceCode.AM_Map; import static doom.SourceCode.AM_Map.AM_Responder; -import static doom.englsh.*; +import static doom.englsh.AMSTR_FOLLOWOFF; +import static doom.englsh.AMSTR_FOLLOWON; +import static doom.englsh.AMSTR_GRIDOFF; +import static doom.englsh.AMSTR_GRIDON; +import static doom.englsh.AMSTR_MARKEDSPOT; +import static doom.englsh.AMSTR_MARKSCLEARED; import doom.event_t; import doom.evtype_t; import doom.player_t; import g.Signals.ScanCode; -import static g.Signals.ScanCode.*; +import static g.Signals.ScanCode.SC_0; +import static g.Signals.ScanCode.SC_C; +import static g.Signals.ScanCode.SC_DOWN; +import static g.Signals.ScanCode.SC_EQUALS; +import static g.Signals.ScanCode.SC_F; +import static g.Signals.ScanCode.SC_G; +import static g.Signals.ScanCode.SC_LEFT; +import static g.Signals.ScanCode.SC_M; +import static g.Signals.ScanCode.SC_MINUS; +import static g.Signals.ScanCode.SC_RIGHT; +import static g.Signals.ScanCode.SC_TAB; +import static g.Signals.ScanCode.SC_UP; import java.awt.Rectangle; import java.lang.reflect.Array; import java.util.Arrays; import java.util.EnumMap; import java.util.EnumSet; import m.cheatseq_t; -import static m.fixed_t.*; +import static m.fixed_t.FRACBITS; +import static m.fixed_t.FRACUNIT; +import static m.fixed_t.FixedDiv; +import static m.fixed_t.FixedMul; import p.mobj_t; -import static rr.line_t.*; +import static rr.line_t.ML_DONTDRAW; +import static rr.line_t.ML_MAPPED; +import static rr.line_t.ML_SECRET; import rr.patch_t; -import static utils.GenericCopy.*; -import static v.DoomGraphicSystem.*; +import static utils.GenericCopy.malloc; +import static utils.GenericCopy.memcpy; +import static utils.GenericCopy.memset; +import static v.DoomGraphicSystem.V_NOSCALESTART; import v.graphics.Plotter; -import static v.renderers.DoomScreen.*; +import static v.renderers.DoomScreen.FG; public class Map implements IAutoMap { @@ -219,13 +247,13 @@ enum Color { YELLOWS(8, (byte) 160 /*(256 - 32)*/), BLACK(1, (byte) 0), WHITE(1, (byte) 4), - GRAYS_DARKER_25(13, (byte)(GRAYS.value + 4)), - DARK_GREYS(8, (byte)(GRAYS.value + GRAYS.range / 2)), - DARK_REDS(8, (byte)(REDS.value + REDS.range / 2)); + GRAYS_DARKER_25(13, (byte) (GRAYS.value + 4)), + DARK_GREYS(8, (byte) (GRAYS.value + GRAYS.range / 2)), + DARK_REDS(8, (byte) (REDS.value + REDS.range / 2)); final static int NUM_LITES = 8; - final static int[] LITE_LEVELS_FULL_RANGE = { 0, 4, 7, 10, 12, 14, 15, 15 }; - final static int[] LITE_LEVELS_HALF_RANGE = { 0, 2, 3, 5, 6, 6, 7, 7 }; + final static int[] LITE_LEVELS_FULL_RANGE = {0, 4, 7, 10, 12, 14, 15, 15}; + final static int[] LITE_LEVELS_HALF_RANGE = {0, 2, 3, 5, 6, 6, 7, 7}; final byte[] liteBlock; final byte value; final int range; @@ -239,10 +267,10 @@ enum Color { this.liteBlock = null; } } - + static { - for (Color c: values()) { - switch(c.range) { + for (Color c : values()) { + switch (c.range) { case 16: for (int i = 0; i < NUM_LITES; ++i) { c.liteBlock[i] = (byte) (c.value + LITE_LEVELS_FULL_RANGE[i]); @@ -259,38 +287,37 @@ enum Color { // For use if I do walls with outsides/insides // Automap colors - final static Color - BACKGROUND = Color.BLACK, - YOURCOLORS = Color.WHITE, - WALLCOLORS = Color.REDS, - TELECOLORS = Color.DARK_REDS, - TSWALLCOLORS = Color.GRAYS, - FDWALLCOLORS = Color.BROWNS, - CDWALLCOLORS = Color.YELLOWS, - THINGCOLORS = Color.GREENS, - SECRETWALLCOLORS = Color.REDS, - GRIDCOLORS = Color.DARK_GREYS, - MAPPOWERUPSHOWNCOLORS = Color.GRAYS, - CROSSHAIRCOLORS = Color.GRAYS; + final static Color BACKGROUND = Color.BLACK, + YOURCOLORS = Color.WHITE, + WALLCOLORS = Color.REDS, + TELECOLORS = Color.DARK_REDS, + TSWALLCOLORS = Color.GRAYS, + FDWALLCOLORS = Color.BROWNS, + CDWALLCOLORS = Color.YELLOWS, + THINGCOLORS = Color.GREENS, + SECRETWALLCOLORS = Color.REDS, + GRIDCOLORS = Color.DARK_GREYS, + MAPPOWERUPSHOWNCOLORS = Color.GRAYS, + CROSSHAIRCOLORS = Color.GRAYS; final static EnumSet GENERATE_LITE_LEVELS_FOR = EnumSet.of( - TELECOLORS, - WALLCOLORS, - FDWALLCOLORS, - CDWALLCOLORS, - TSWALLCOLORS, - SECRETWALLCOLORS, - MAPPOWERUPSHOWNCOLORS, - THINGCOLORS + TELECOLORS, + WALLCOLORS, + FDWALLCOLORS, + CDWALLCOLORS, + TSWALLCOLORS, + SECRETWALLCOLORS, + MAPPOWERUPSHOWNCOLORS, + THINGCOLORS ); - + final static Color THEIR_COLORS[] = { Color.GREENS, Color.GRAYS, Color.BROWNS, Color.REDS }; - + // drawing stuff public static final ScanCode AM_PANDOWNKEY = SC_DOWN; public static final ScanCode AM_PANUPKEY = SC_UP; @@ -321,7 +348,7 @@ enum Color { // how much zoom-out per tic // pulls out to 0.5x in 1 second public static final int M_ZOOMOUT = ((int) (FRACUNIT / 1.02)); - + final EnumMap fixedColorSources = new EnumMap<>(Color.class); final EnumMap litedColorSources = new EnumMap<>(Color.class); @@ -340,24 +367,24 @@ public Map(final DoomMain DOOM) { finit_width = DOOM.vs.getScreenWidth(); finit_height = DOOM.vs.getScreenHeight() - 32 * DOOM.vs.getSafeScaling(); } - + @Override public final void Repalette() { GENERATE_LITE_LEVELS_FOR.stream() - .forEach((c) -> { - if (c.liteBlock != null) { - litedColorSources.put(c, DOOM.graphicSystem.convertPalettedBlock(c.liteBlock)); - } - }); - + .forEach((c) -> { + if (c.liteBlock != null) { + litedColorSources.put(c, DOOM.graphicSystem.convertPalettedBlock(c.liteBlock)); + } + }); + Arrays.stream(Color.values()) - .forEach((c) -> { - V converted = DOOM.graphicSystem.convertPalettedBlock(c.value); - @SuppressWarnings("unchecked") - V extended = (V) Array.newInstance(converted.getClass().getComponentType(), Color.NUM_LITES); - memset(extended, 0, Color.NUM_LITES, converted, 0, 1); - fixedColorSources.put(c, extended); - }); + .forEach((c) -> { + V converted = DOOM.graphicSystem.convertPalettedBlock(c.value); + @SuppressWarnings("unchecked") + V extended = (V) Array.newInstance(converted.getClass().getComponentType(), Color.NUM_LITES); + memset(extended, 0, Color.NUM_LITES, converted, 0, 1); + fixedColorSources.put(c, extended); + }); } /** translates between frame-buffer and map distances */ @@ -379,7 +406,7 @@ private int CXMTOF(int x) { private int CYMTOF(int y) { return (f_y + (f_h - MTOF((y) - m_y))); } - + // the following is crap public static final short LINE_NEVERSEE = ML_DONTDRAW; @@ -414,20 +441,20 @@ private int CYMTOF(int y) { protected void initVectorGraphics() { int R = ((8 * PLAYERRADIUS) / 7); - player_arrow = - new mline_t[] { + player_arrow + = new mline_t[]{ new mline_t(-R + R / 8, 0, R, 0), // ----- new mline_t(R, 0, R - R / 2, R / 4), // ---- new mline_t(R, 0, R - R / 2, -R / 4), new mline_t(-R + R / 8, 0, -R - R / 8, R / 4), // >--- new mline_t(-R + R / 8, 0, -R - R / 8, -R / 4), new mline_t(-R + 3 * R / 8, 0, -R + R / 8, R / 4), // >>-- - new mline_t(-R + 3 * R / 8, 0, -R + R / 8, -R / 4) }; + new mline_t(-R + 3 * R / 8, 0, -R + R / 8, -R / 4)}; NUMPLYRLINES = player_arrow.length; - cheat_player_arrow = - new mline_t[] { + cheat_player_arrow + = new mline_t[]{ new mline_t(-R + R / 8, 0, R, 0), // ----- new mline_t(R, 0, R - R / 2, R / 6), // ---- new mline_t(R, 0, R - R / 2, -R / 6), @@ -444,22 +471,22 @@ protected void initVectorGraphics() { new mline_t(R / 6, R / 4, R / 6, -R / 7), // >>-ddt new mline_t(R / 6, -R / 7, R / 6 + R / 32, -R / 7 - R / 32), new mline_t(R / 6 + R / 32, -R / 7 - R / 32, - R / 6 + R / 10, -R / 7) }; + R / 6 + R / 10, -R / 7)}; NUMCHEATPLYRLINES = cheat_player_arrow.length; R = (FRACUNIT); - triangle_guy = - new mline_t[] { new mline_t(-.867 * R, -.5 * R, .867 * R, -.5 * R), + triangle_guy + = new mline_t[]{new mline_t(-.867 * R, -.5 * R, .867 * R, -.5 * R), new mline_t(.867 * R, -.5 * R, 0, R), - new mline_t(0, R, -.867 * R, -.5 * R) }; + new mline_t(0, R, -.867 * R, -.5 * R)}; NUMTRIANGLEGUYLINES = triangle_guy.length; - thintriangle_guy = - new mline_t[] { new mline_t(-.5 * R, -.7 * R, R, 0), + thintriangle_guy + = new mline_t[]{new mline_t(-.5 * R, -.7 * R, R, 0), new mline_t(R, 0, -.5 * R, .7 * R), - new mline_t(-.5 * R, .7 * R, -.5 * R, -.7 * R) }; + new mline_t(-.5 * R, .7 * R, -.5 * R, -.7 * R)}; NUMTHINTRIANGLEGUYLINES = thintriangle_guy.length; } @@ -486,7 +513,7 @@ protected void initVectorGraphics() { protected int f_w; protected int f_h; - + protected Rectangle f_rect; /** used for funky strobing effect */ @@ -494,7 +521,6 @@ protected void initVectorGraphics() { /** pseudo-frame buffer */ //protected V fb; - /** * I've made this awesome change to draw map lines on the renderer * - Good Sign 2017/04/05 @@ -566,15 +592,14 @@ protected void initVectorGraphics() { /** specifies whether to follow the player around */ protected boolean followplayer = true; - protected char[] cheat_amap_seq = { 0xb2, 0x26, 0x26, 0x2e, 0xff }; // iddt + protected char[] cheat_amap_seq = {0xb2, 0x26, 0x26, 0x2e, 0xff}; // iddt protected cheatseq_t cheat_amap = new cheatseq_t(cheat_amap_seq, 0); // MAES: STROBE cheat. It's not even cheating, strictly speaking. - - private final char cheat_strobe_seq[] = { 0x6e, 0xa6, 0xea, 0x2e, 0x6a, 0xf6, - 0x62, 0xa6, 0xff // vestrobe - }; + private final char cheat_strobe_seq[] = {0x6e, 0xa6, 0xea, 0x2e, 0x6a, 0xf6, + 0x62, 0xa6, 0xff // vestrobe +}; private final cheatseq_t cheat_strobe = new cheatseq_t(cheat_strobe_seq, 0); @@ -582,7 +607,6 @@ protected void initVectorGraphics() { // extern boolean viewactive; // extern byte screens[][DOOM.vs.getScreenWidth()*DOOM.vs.getScreenHeight()]; - /** * Calculates the slope and slope according to the x-axis of a line segment * in map coordinates (with the upright y-axis n' all) so that it can be @@ -591,20 +615,21 @@ protected void initVectorGraphics() { * @param ml * @param is */ - public final void getIslope(mline_t ml, islope_t is) { int dx, dy; dy = ml.ay - ml.by; dx = ml.bx - ml.ax; - if (dy == 0) + if (dy == 0) { is.islp = (dx < 0 ? -MAXINT : MAXINT); - else + } else { is.islp = FixedDiv(dx, dy); - if (dx == 0) + } + if (dx == 0) { is.slp = (dy < 0 ? -MAXINT : MAXINT); - else + } else { is.slp = FixedDiv(dy, dx); + } } @@ -620,10 +645,10 @@ public final void activateNewScale() { m_y -= m_h / 2; m_x2 = m_x + m_w; m_y2 = m_y + m_h; - + plotter.setThickness( - Math.min(MTOF(FRACUNIT), DOOM.graphicSystem.getScalingX()), - Math.min(MTOF(FRACUNIT), DOOM.graphicSystem.getScalingY()) + Math.min(MTOF(FRACUNIT), DOOM.graphicSystem.getScalingX()), + Math.min(MTOF(FRACUNIT), DOOM.graphicSystem.getScalingY()) ); } @@ -656,15 +681,14 @@ private void restoreScaleAndLoc() { scale_ftom = FixedDiv(FRACUNIT, scale_mtof); plotter.setThickness( - Math.min(MTOF(FRACUNIT), Color.NUM_LITES), - Math.min(MTOF(FRACUNIT), Color.NUM_LITES) + Math.min(MTOF(FRACUNIT), Color.NUM_LITES), + Math.min(MTOF(FRACUNIT), Color.NUM_LITES) ); } /** * adds a marker at the current location */ - public final void addMark() { markpoints[markpointnum].x = m_x + m_w / 2; markpoints[markpointnum].y = m_y + m_h / 2; @@ -676,7 +700,6 @@ public final void addMark() { * Determines bounding box of all vertices, sets global variables * controlling zoom range. */ - public final void findMinMaxBoundaries() { int a; // fixed_t int b; @@ -685,15 +708,17 @@ public final void findMinMaxBoundaries() { max_x = max_y = -MAXINT; for (int i = 0; i < DOOM.levelLoader.numvertexes; i++) { - if (DOOM.levelLoader.vertexes[i].x < min_x) + if (DOOM.levelLoader.vertexes[i].x < min_x) { min_x = DOOM.levelLoader.vertexes[i].x; - else if (DOOM.levelLoader.vertexes[i].x > max_x) + } else if (DOOM.levelLoader.vertexes[i].x > max_x) { max_x = DOOM.levelLoader.vertexes[i].x; + } - if (DOOM.levelLoader.vertexes[i].y < min_y) + if (DOOM.levelLoader.vertexes[i].y < min_y) { min_y = DOOM.levelLoader.vertexes[i].y; - else if (DOOM.levelLoader.vertexes[i].y > max_y) + } else if (DOOM.levelLoader.vertexes[i].y > max_y) { max_y = DOOM.levelLoader.vertexes[i].y; + } } max_w = max_x - min_x; @@ -724,15 +749,17 @@ public final void changeWindowLoc() { m_x += m_paninc.x; m_y += m_paninc.y; - if (m_x + m_w / 2 > max_x) + if (m_x + m_w / 2 > max_x) { m_x = max_x - m_w / 2; - else if (m_x + m_w / 2 < min_x) + } else if (m_x + m_w / 2 < min_x) { m_x = min_x - m_w / 2; + } - if (m_y + m_h / 2 > max_y) + if (m_y + m_h / 2 > max_y) { m_y = max_y - m_h / 2; - else if (m_y + m_h / 2 < min_y) + } else if (m_y + m_h / 2 < min_y) { m_y = min_y - m_h / 2; + } m_x2 = m_x + m_w; m_y2 = m_y + m_h; @@ -754,12 +781,14 @@ public final void initVariables() { m_h = FTOM(f_h); // find player to center on initially - if (!DOOM.playeringame[pnum = DOOM.consoleplayer]) + if (!DOOM.playeringame[pnum = DOOM.consoleplayer]) { for (pnum = 0; pnum < MAXPLAYERS; pnum++) { - System.out.println(pnum); - if (DOOM.playeringame[pnum]) + //System.out.println(pnum); + if (DOOM.playeringame[pnum]) { break; + } } + } plr = DOOM.players[pnum]; m_x = plr.mo.x - m_w / 2; m_y = plr.mo.y - m_h / 2; @@ -800,8 +829,9 @@ public final void unloadPics() { public final void clearMarks() { int i; - for (i = 0; i < AM_NUMMARKPOINTS; i++) + for (i = 0; i < AM_NUMMARKPOINTS; i++) { markpoints[i].x = -1; // means empty + } markpointnum = 0; } @@ -818,18 +848,18 @@ public final void LevelInit() { f_rect = new Rectangle(0, 0, f_w, f_h); // scanline=new byte[f_h*f_w]; - this.clearMarks(); this.findMinMaxBoundaries(); scale_mtof = FixedDiv(min_scale_mtof, MINIMUM_SCALE); - if (scale_mtof > max_scale_mtof) + if (scale_mtof > max_scale_mtof) { scale_mtof = min_scale_mtof; + } scale_ftom = FixedDiv(FRACUNIT, scale_mtof); - + plotter.setThickness( - Math.min(MTOF(FRACUNIT), DOOM.graphicSystem.getScalingX()), - Math.min(MTOF(FRACUNIT), DOOM.graphicSystem.getScalingY()) + Math.min(MTOF(FRACUNIT), DOOM.graphicSystem.getScalingX()), + Math.min(MTOF(FRACUNIT), DOOM.graphicSystem.getScalingY()) ); } @@ -848,8 +878,9 @@ public final void Stop() { @Override public final void Start() { - if (!stopped) + if (!stopped) { Stop(); + } stopped = false; if (lastlevel != DOOM.gamemap || lastepisode != DOOM.gameepisode) { @@ -876,7 +907,6 @@ public final void minOutWindowScale() { /** * set the window scale to the minimum size */ - public final void maxOutWindowScale() { scale_mtof = max_scale_mtof; scale_ftom = FixedDiv(FRACUNIT, scale_mtof); @@ -893,7 +923,6 @@ public final void maxOutWindowScale() { /** * Handle events (user inputs) in automap mode */ - @Override @AM_Map.C(AM_Responder) public final boolean Responder(event_t ev) { @@ -910,25 +939,29 @@ public final boolean Responder(event_t ev) { } else if (ev.isType(evtype_t.ev_keydown)) { rc = true; if (ev.isKey(AM_PANRIGHTKEY)) { // pan right - if (!followplayer) + if (!followplayer) { m_paninc.x = FTOM(F_PANINC); - else + } else { rc = false; + } } else if (ev.isKey(AM_PANLEFTKEY)) { // pan left - if (!followplayer) + if (!followplayer) { m_paninc.x = -FTOM(F_PANINC); - else + } else { rc = false; + } } else if (ev.isKey(AM_PANUPKEY)) { // pan up - if (!followplayer) + if (!followplayer) { m_paninc.y = FTOM(F_PANINC); - else + } else { rc = false; + } } else if (ev.isKey(AM_PANDOWNKEY)) { // pan down - if (!followplayer) + if (!followplayer) { m_paninc.y = -FTOM(F_PANINC); - else + } else { rc = false; + } } else if (ev.isKey(AM_ZOOMOUTKEY)) { // zoom out mtof_zoommul = M_ZOOMOUT; ftom_zoommul = M_ZOOMIN; @@ -940,8 +973,9 @@ public final boolean Responder(event_t ev) { if (bigstate) { this.saveScaleAndLoc(); this.minOutWindowScale(); - } else + } else { this.restoreScaleAndLoc(); + } } else if (ev.isKey(AM_FOLLOWKEY)) { followplayer = !followplayer; f_oldloc.x = MAXINT; @@ -960,12 +994,12 @@ public final boolean Responder(event_t ev) { cheatstate = false; rc = false; } - + if (!DOOM.deathmatch && ev.ifKeyAsciiChar(cheat_amap::CheckCheat)) { rc = false; cheating = (cheating + 1) % 3; } - + /** * MAES: brought back strobe effect * Good Sign: setting can be saved/loaded from config @@ -976,17 +1010,21 @@ public final boolean Responder(event_t ev) { } else if (ev.isType(evtype_t.ev_keyup)) { rc = false; if (ev.isKey(AM_PANRIGHTKEY)) { - if (!followplayer) + if (!followplayer) { m_paninc.x = 0; + } } else if (ev.isKey(AM_PANLEFTKEY)) { - if (!followplayer) + if (!followplayer) { m_paninc.x = 0; + } } else if (ev.isKey(AM_PANUPKEY)) { - if (!followplayer) + if (!followplayer) { m_paninc.y = 0; + } } else if (ev.isKey(AM_PANDOWNKEY)) { - if (!followplayer) + if (!followplayer) { m_paninc.y = 0; + } } else if (ev.isKey(AM_ZOOMOUTKEY) || ev.isKey(AM_ZOOMINKEY)) { mtof_zoommul = FRACUNIT; ftom_zoommul = FRACUNIT; @@ -1010,12 +1048,13 @@ private void changeWindowScale() { scale_mtof = FixedMul(scale_mtof, mtof_zoommul); scale_ftom = FixedDiv(FRACUNIT, scale_mtof); - if (scale_mtof < min_scale_mtof) + if (scale_mtof < min_scale_mtof) { this.minOutWindowScale(); - else if (scale_mtof > max_scale_mtof) + } else if (scale_mtof > max_scale_mtof) { this.maxOutWindowScale(); - else + } else { this.activateNewScale(); + } } @@ -1036,7 +1075,6 @@ private void doFollowPlayer() { // m_y = FTOM(MTOF(plr.mo.y - m_h/2)); // m_x = plr.mo.x - m_w/2; // m_y = plr.mo.y - m_h/2; - } } @@ -1062,29 +1100,33 @@ private void updateLightLev() { */ @Override public final void Ticker() { - if (!DOOM.automapactive || DOOM.menuactive) + if (!DOOM.automapactive || DOOM.menuactive) { return; + } amclock++; - if (followplayer) + if (followplayer) { this.doFollowPlayer(); + } // Change the zoom if necessary - if (ftom_zoommul != FRACUNIT) + if (ftom_zoommul != FRACUNIT) { this.changeWindowScale(); + } // Change x,y location - if ((m_paninc.x | m_paninc.y) != 0) + if ((m_paninc.x | m_paninc.y) != 0) { this.changeWindowLoc(); + } // Update light level - if (DOOM.mapstrobe) + if (DOOM.mapstrobe) { updateLightLev(); + } } // private static int BUFFERSIZE=f_h*f_w; - /** * Automap clipping of lines. Based on Cohen-Sutherland clipping algorithm * but with a slightly faster reject and precalculated slopes. If the speed @@ -1109,32 +1151,36 @@ private boolean clipMline(mline_t ml, fline_t fl) { */ // do trivial rejects and outcodes - if (ml.ay > m_y2) + if (ml.ay > m_y2) { outcode1 = TOP; - else if (ml.ay < m_y) + } else if (ml.ay < m_y) { outcode1 = BOTTOM; + } - if (ml.by > m_y2) + if (ml.by > m_y2) { outcode2 = TOP; - else if (ml.by < m_y) + } else if (ml.by < m_y) { outcode2 = BOTTOM; + } - if ((outcode1 & outcode2) != 0) + if ((outcode1 & outcode2) != 0) { return false; // trivially outside - - if (ml.ax < m_x) + } + if (ml.ax < m_x) { outcode1 |= LEFT; - else if (ml.ax > m_x2) + } else if (ml.ax > m_x2) { outcode1 |= RIGHT; + } - if (ml.bx < m_x) + if (ml.bx < m_x) { outcode2 |= LEFT; - else if (ml.bx > m_x2) + } else if (ml.bx > m_x2) { outcode2 |= RIGHT; + } - if ((outcode1 & outcode2) != 0) + if ((outcode1 & outcode2) != 0) { return false; // trivially outside - + } // transform to frame-buffer coordinates. fl.ax = CXMTOF(ml.ax); fl.ay = CYMTOF(ml.ay); @@ -1145,16 +1191,18 @@ else if (ml.bx > m_x2) outcode1 = DOOUTCODE(fl.ax, fl.ay); outcode2 = DOOUTCODE(fl.bx, fl.by); - if ((outcode1 & outcode2) != 0) + if ((outcode1 & outcode2) != 0) { return false; + } while ((outcode1 | outcode2) != 0) { // may be partially inside box // find an outside point - if (outcode1 != 0) + if (outcode1 != 0) { outside = outcode1; - else + } else { outside = outcode2; + } // clip to each side if ((outside & TOP) != 0) { @@ -1189,8 +1237,9 @@ else if (ml.bx > m_x2) outcode2 = DOOUTCODE(fl.bx, fl.by); } - if ((outcode1 & outcode2) != 0) + if ((outcode1 & outcode2) != 0) { return false; // trivially outside + } } return true; @@ -1205,17 +1254,18 @@ else if (ml.bx > m_x2) * @param mx * @param my */ - private int DOOUTCODE(int mx, int my) { int oc = 0; - if ((my) < 0) + if ((my) < 0) { (oc) |= TOP; - else if ((my) >= f_h) + } else if ((my) >= f_h) { (oc) |= BOTTOM; - if ((mx) < 0) + } + if ((mx) < 0) { (oc) |= LEFT; - else if ((mx) >= f_w) + } else if ((mx) >= f_w) { (oc) |= RIGHT; + } return oc; } @@ -1233,10 +1283,10 @@ private void drawMline(mline_t ml, V colorSource) { // if ((fl.a.x==fl.b.x)&&(fl.a.y==fl.b.y)) singlepixel++; // draws the line using coords DOOM.graphicSystem - .drawLine(plotter - .setColorSource(colorSource, 0) - .setPosition(fl.ax, fl.ay), - fl.bx, fl.by); + .drawLine(plotter + .setColorSource(colorSource, 0) + .setPosition(fl.ax, fl.ay), + fl.bx, fl.by); } } @@ -1253,10 +1303,11 @@ private void drawGrid(V colorSource) { // Figure out start of vertical gridlines start = m_x; - if (((start - DOOM.levelLoader.bmaporgx) % (MAPBLOCKUNITS << FRACBITS)) != 0) - start += - (MAPBLOCKUNITS << FRACBITS) - - ((start - DOOM.levelLoader.bmaporgx) % (MAPBLOCKUNITS << FRACBITS)); + if (((start - DOOM.levelLoader.bmaporgx) % (MAPBLOCKUNITS << FRACBITS)) != 0) { + start + += (MAPBLOCKUNITS << FRACBITS) + - ((start - DOOM.levelLoader.bmaporgx) % (MAPBLOCKUNITS << FRACBITS)); + } end = m_x + m_w; // draw vertical gridlines @@ -1270,10 +1321,11 @@ private void drawGrid(V colorSource) { // Figure out start of horizontal gridlines start = m_y; - if (((start - DOOM.levelLoader.bmaporgy) % (MAPBLOCKUNITS << FRACBITS)) != 0) - start += - (MAPBLOCKUNITS << FRACBITS) - - ((start - DOOM.levelLoader.bmaporgy) % (MAPBLOCKUNITS << FRACBITS)); + if (((start - DOOM.levelLoader.bmaporgy) % (MAPBLOCKUNITS << FRACBITS)) != 0) { + start + += (MAPBLOCKUNITS << FRACBITS) + - ((start - DOOM.levelLoader.bmaporgy) % (MAPBLOCKUNITS << FRACBITS)); + } end = m_y + m_h; // draw horizontal gridlines @@ -1293,7 +1345,6 @@ private void drawGrid(V colorSource) { * Determines visible lines, draws them. This is LineDef based, not LineSeg * based. */ - private void drawWalls() { final V teleColorSource = litedColorSources.get(TELECOLORS); @@ -1309,20 +1360,22 @@ private void drawWalls() { l.bx = DOOM.levelLoader.lines[i].v2x; l.by = DOOM.levelLoader.lines[i].v2y; if ((cheating | (DOOM.levelLoader.lines[i].flags & ML_MAPPED)) != 0) { - if (((DOOM.levelLoader.lines[i].flags & LINE_NEVERSEE) & ~cheating) != 0) + if (((DOOM.levelLoader.lines[i].flags & LINE_NEVERSEE) & ~cheating) != 0) { continue; + } if (DOOM.levelLoader.lines[i].backsector == null) { drawMline(l, wallColorSource); } else { if (DOOM.levelLoader.lines[i].special == 39) { // teleporters drawMline(l, teleColorSource); } else if ((DOOM.levelLoader.lines[i].flags & ML_SECRET) != 0) // secret - // door + // door { - if (cheating != 0) + if (cheating != 0) { drawMline(l, secretWallColorSource); - else + } else { drawMline(l, wallColorSource); + } } else if (DOOM.levelLoader.lines[i].backsector.floorheight != DOOM.levelLoader.lines[i].frontsector.floorheight) { drawMline(l, fdWallColorSource); // floor level change } else if (DOOM.levelLoader.lines[i].backsector.ceilingheight != DOOM.levelLoader.lines[i].frontsector.ceilingheight) { @@ -1331,12 +1384,12 @@ private void drawWalls() { drawMline(l, tsWallColorSource); } } - } - // If we have allmap... + } // If we have allmap... else if (plr.powers[pw_allmap] != 0) { // Some are never seen even with that! - if ((DOOM.levelLoader.lines[i].flags & LINE_NEVERSEE) == 0) + if ((DOOM.levelLoader.lines[i].flags & LINE_NEVERSEE) == 0) { drawMline(l, litedColorSources.get(MAPPOWERUPSHOWNCOLORS)); + } } } @@ -1360,7 +1413,6 @@ else if (plr.powers[pw_allmap] != 0) { * @param a * angle_t -> this should be a LUT-ready BAM. */ - private void rotate(int x, int y, int a) { // int tmpx; @@ -1430,16 +1482,16 @@ public final void drawPlayers() { V colorSource; // System.out.println(Long.toHexString(plr.mo.angle)); - if (!DOOM.netgame) { - if (cheating != 0) + if (cheating != 0) { drawLineCharacter(cheat_player_arrow, NUMCHEATPLYRLINES, 0, - toBAMIndex(plr.mo.angle), fixedColorSources.get(Color.WHITE), plr.mo.x, - plr.mo.y); - else + toBAMIndex(plr.mo.angle), fixedColorSources.get(Color.WHITE), plr.mo.x, + plr.mo.y); + } else { drawLineCharacter(player_arrow, NUMPLYRLINES, 0, - toBAMIndex(plr.mo.angle), fixedColorSources.get(Color.WHITE), plr.mo.x, - plr.mo.y); + toBAMIndex(plr.mo.angle), fixedColorSources.get(Color.WHITE), plr.mo.x, + plr.mo.y); + } return; } @@ -1447,16 +1499,19 @@ public final void drawPlayers() { their_color++; p = DOOM.players[i]; - if ((DOOM.deathmatch && !DOOM.singledemo) && p != plr) + if ((DOOM.deathmatch && !DOOM.singledemo) && p != plr) { continue; + } - if (!DOOM.playeringame[i]) + if (!DOOM.playeringame[i]) { continue; + } - if (p.powers[pw_invisibility] != 0) + if (p.powers[pw_invisibility] != 0) { colorSource = fixedColorSources.get(Color.CLOSE_TO_BLACK); - else + } else { colorSource = fixedColorSources.get(THEIR_COLORS[their_color]); + } drawLineCharacter(player_arrow, NUMPLYRLINES, 0, (int) p.mo.angle, colorSource, p.mo.x, p.mo.y); } @@ -1472,7 +1527,7 @@ final void drawThings(Color colors, int colorrange) { t = DOOM.levelLoader.sectors[i].thinglist; while (t != null) { drawLineCharacter(thintriangle_guy, NUMTHINTRIANGLEGUYLINES, - 16 << FRACBITS, toBAMIndex(t.angle), colorSource, t.x, t.y); + 16 << FRACBITS, toBAMIndex(t.angle), colorSource, t.x, t.y); t = (mobj_t) t.snext; } } @@ -1491,8 +1546,9 @@ public final void drawMarks() { // h = 6; // because something's wrong with the wad, i guess fx = CXMTOF(markpoints[i].x); fy = CYMTOF(markpoints[i].y); - if (fx >= f_x && fx <= f_w - w && fy >= f_y && fy <= f_h - h) + if (fx >= f_x && fx <= f_w - w && fy >= f_y && fy <= f_h - h) { DOOM.graphicSystem.DrawPatchScaled(FG, marknums[i], DOOM.vs, fx, fy, V_NOSCALESTART); + } } } @@ -1509,24 +1565,26 @@ private void drawCrosshair(V colorSource) { @Override public final void Drawer() { - if (!DOOM.automapactive) + if (!DOOM.automapactive) { return; + } // System.out.println("Drawing map"); - if (overlay < 1) + if (overlay < 1) { DOOM.graphicSystem.FillRect(FG, f_rect, BACKGROUND.value); // BACKGROUND - - if (grid) + } + if (grid) { drawGrid(fixedColorSources.get(GRIDCOLORS)); - + } + drawWalls(); drawPlayers(); - if (cheating == 2) + if (cheating == 2) { drawThings(THINGCOLORS, THINGRANGE); + } drawCrosshair(fixedColorSources.get(CROSSHAIRCOLORS)); drawMarks(); //DOOM.videoRenderer.MarkRect(f_x, f_y, f_w, f_h); - } -} \ No newline at end of file +} diff --git a/src/automap/fline_t.java b/src/automap/fline_t.java index 70c1461a..659b45d6 100644 --- a/src/automap/fline_t.java +++ b/src/automap/fline_t.java @@ -1,8 +1,7 @@ package automap; -public class fline_t -{ - +public class fline_t { + /* * public fline_t(){ a=new fpoint_t(); @@ -13,19 +12,19 @@ public fline_t(fpoint_t a, fpoint_t b){ this.a=a; this.b=b; } -*/ - public fline_t(int ax, int ay, int bx, int by){ - this.ay=ay; - this.ax=ax; - this.by=by; - this.bx=bx; + */ + public fline_t(int ax, int ay, int bx, int by) { + this.ay = ay; + this.ax = ax; + this.by = by; + this.bx = bx; } - + public fline_t() { // TODO Auto-generated constructor stub } - public int ax,ay,bx,by; + public int ax, ay, bx, by; /* public fpoint_t a, b; diff --git a/src/automap/fpoint_t.java b/src/automap/fpoint_t.java index 98c84dfb..80616a1f 100644 --- a/src/automap/fpoint_t.java +++ b/src/automap/fpoint_t.java @@ -1,16 +1,16 @@ package automap; -public class fpoint_t -{ +public class fpoint_t { + int x, y; - - public fpoint_t(){ - this(0,0); + + public fpoint_t() { + this(0, 0); } - - public fpoint_t(int x, int y){ - this.x=x; - this.y=y; + + public fpoint_t(int x, int y) { + this.x = x; + this.y = y; } - + } diff --git a/src/automap/islope_t.java b/src/automap/islope_t.java index 519a69f3..d928174b 100644 --- a/src/automap/islope_t.java +++ b/src/automap/islope_t.java @@ -1,7 +1,7 @@ package automap; -public class islope_t -{ +public class islope_t { + /** fixed_t */ int slp, islp; } diff --git a/src/automap/mline_t.java b/src/automap/mline_t.java index c902724d..45234446 100644 --- a/src/automap/mline_t.java +++ b/src/automap/mline_t.java @@ -1,14 +1,13 @@ package automap; /** used only in automap */ +public class mline_t { -public class mline_t -{ - public mline_t(){ - this(0,0,0,0); + public mline_t() { + this(0, 0, 0, 0); } - - public int ax,ay,bx,by; + + public int ax, ay, bx, by; public mline_t(int ax, int ay, int bx, int by) { this.ax = ax; @@ -16,14 +15,14 @@ public mline_t(int ax, int ay, int bx, int by) { this.bx = bx; this.by = by; } - + public mline_t(double ax, double ay, double bx, double by) { this.ax = (int) ax; this.ay = (int) ay; this.bx = (int) bx; this.by = (int) by; } - + /* public mline_t(mpoint_t a, mpoint_t b) { this.a = a; @@ -46,5 +45,5 @@ public mline_t(double ax,double ay,double bx,double by) { public String toString(){ return a.toString()+" - "+ b.toString(); } - */ + */ } diff --git a/src/automap/mpoint_t.java b/src/automap/mpoint_t.java index 6d00face..0e8a5e5a 100644 --- a/src/automap/mpoint_t.java +++ b/src/automap/mpoint_t.java @@ -2,32 +2,32 @@ import m.fixed_t; -public class mpoint_t -{ - public mpoint_t(fixed_t x, fixed_t y) { +public class mpoint_t { + + public mpoint_t(fixed_t x, fixed_t y) { this.x = x.val; this.y = y.val; } - public mpoint_t(int x, int y) { - this.x = x; - this.y = y; - } - - public mpoint_t(double x, double y) { - this.x = (int) x; - this.y = (int) y; - } - - public mpoint_t(){ - this.x=0; - this.y=0; - } - - /** fixed_t */ - public int x,y; - - public String toString(){ - return (Integer.toHexString(x)+" , "+Integer.toHexString(y)); - } + public mpoint_t(int x, int y) { + this.x = x; + this.y = y; + } + + public mpoint_t(double x, double y) { + this.x = (int) x; + this.y = (int) y; + } + + public mpoint_t() { + this.x = 0; + this.y = 0; + } + + /** fixed_t */ + public int x, y; + + public String toString() { + return (Integer.toHexString(x) + " , " + Integer.toHexString(y)); + } }; diff --git a/src/awt/DisplayModePicker.java b/src/awt/DisplayModePicker.java index 16a74976..4936b2fd 100644 --- a/src/awt/DisplayModePicker.java +++ b/src/awt/DisplayModePicker.java @@ -8,7 +8,7 @@ import java.util.List; public class DisplayModePicker { - + protected GraphicsDevice device; protected DisplayMode default_mode; @@ -16,7 +16,7 @@ public DisplayModePicker(GraphicsDevice device) { this.device = device; this.default_mode = device.getDisplayMode(); } - + public DisplayMode pickClosest(int width, int height) { DisplayMode[] modes = device.getDisplayModes(); @@ -26,20 +26,20 @@ public DisplayMode pickClosest(int width, int height) { HeightComparator hc = new HeightComparator(); // Filter out those with too small dimensions. - for (DisplayMode dm: modes) { + for (DisplayMode dm : modes) { if (dm.getWidth() >= width && dm.getHeight() >= height) { picks.add(dm); } } - if (picks.size() > 0) { + if (!picks.isEmpty()) { Collections.sort(picks, wc.thenComparing(hc)); } // First one is the minimum that satisfies the desired criteria. return picks.get(0); } - + /** * Return offsets to center rasters too oddly shaped to fit entirely into * a standard display mode (unfortunately, this means most stuff > 640 x 400), diff --git a/src/awt/DoomFrame.java b/src/awt/DoomFrame.java index d4a8c080..d3443b05 100644 --- a/src/awt/DoomFrame.java +++ b/src/awt/DoomFrame.java @@ -6,9 +6,17 @@ import java.awt.Graphics2D; import java.awt.HeadlessException; import java.awt.Image; -import static java.awt.RenderingHints.*; +import static java.awt.RenderingHints.KEY_ALPHA_INTERPOLATION; +import static java.awt.RenderingHints.KEY_ANTIALIASING; +import static java.awt.RenderingHints.KEY_COLOR_RENDERING; +import static java.awt.RenderingHints.KEY_RENDERING; +import static java.awt.RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED; +import static java.awt.RenderingHints.VALUE_ANTIALIAS_OFF; +import static java.awt.RenderingHints.VALUE_COLOR_RENDER_SPEED; +import static java.awt.RenderingHints.VALUE_RENDER_SPEED; import java.util.function.Supplier; import java.util.logging.Level; +import java.util.logging.Logger; import javax.swing.JFrame; import mochadoom.Engine; import mochadoom.Loggers; @@ -17,29 +25,32 @@ * Common code for Doom's video frames */ public class DoomFrame> extends JFrame implements FullscreenOptions { + + private static final Logger LOGGER = Loggers.getLogger(DoomFrame.class.getName()); + private static final long serialVersionUID = -4130528877723831825L; - + /** * Canvas or JPanel */ private final Window content; - + /** * Graphics to draw image on */ private volatile Graphics2D g2d; - + /** * Provider of video content to display */ final Supplier imageSupplier; - + /** * Default window size. It might change upon entering full screen, so don't consider it absolute. Due to letter * boxing and screen doubling, stretching etc. it might be different that the screen buffer (typically, larger). */ final Dimension dim; - + /** * Very generic JFrame. Along that it only initializes various properties of Doom Frame. */ @@ -71,7 +82,7 @@ public void turnOn() { } else { getContentPane().setPreferredSize(content.getPreferredSize()); } - + setResizable(false); /** @@ -81,13 +92,17 @@ public void turnOn() { * JFrame's size is auto-set here. */ pack(); + + // center frame + setLocationRelativeTo(null); + setVisible(true); - + // Gently tell the eventhandler to wake up and set itself. requestFocus(); content.requestFocusInWindow(); } - + /** * Uninitialize graphics, so it can be reset on the next repaint */ @@ -107,12 +122,12 @@ public void update() { if (!content.isDisplayable()) { return; } - + /** * Work on a local copy of the stack - global one can become null at any moment */ final Graphics2D localG2d = getGraphics2D(); - + /** * If the game starts too fast, it is possible to raise an exception there * We don't want to bother player with "something bad happened" @@ -120,8 +135,7 @@ public void update() { * - Good Sign 2017/04/09 */ if (localG2d == null) { - Loggers.getLogger(DoomFrame.class.getName()) - .log(Level.INFO, "Starting or switching fullscreen, have no Graphics2d yet, skipping paint"); + LOGGER.log(Level.INFO, "Starting or switching fullscreen, have no Graphics2d yet, skipping paint"); } else { draw(g2d, imageSupplier.get(), dim, this); if (showFPS) { @@ -129,7 +143,7 @@ public void update() { final long now = System.currentTimeMillis(); final long lambda = now - lastTime; if (lambda >= 100L) { - setTitle(Engine.getEngine().getWindowTitle(frames * 1000.0/lambda)); + setTitle(Engine.getEngine().getWindowTitle(frames * 1000.0 / lambda)); frames = 0; lastTime = now; } @@ -146,16 +160,20 @@ private Graphics2D getGraphics2D() { Graphics2D localG2d; if ((localG2d = g2d) == null) { // add double-checked locking - synchronized(DoomFrame.class) { + synchronized (DoomFrame.class) { if ((localG2d = g2d) == null) { g2d = localG2d = (Graphics2D) content.getGraphics(); localG2d.setRenderingHint(KEY_ALPHA_INTERPOLATION, VALUE_ALPHA_INTERPOLATION_SPEED); localG2d.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_OFF); localG2d.setRenderingHint(KEY_RENDERING, VALUE_RENDER_SPEED); + localG2d.setRenderingHint(KEY_COLOR_RENDERING, VALUE_COLOR_RENDER_SPEED); + + // add fullscreen interpolation options + applyFullscreenOptions(localG2d); } } } - + return localG2d; } diff --git a/src/awt/DoomWindow.java b/src/awt/DoomWindow.java index 5714e02b..c57ce27b 100644 --- a/src/awt/DoomWindow.java +++ b/src/awt/DoomWindow.java @@ -27,6 +27,7 @@ * possible, and only gets a screen to render, no matter what depth it is. */ public interface DoomWindow> { + /** * Get current graphics device */ @@ -39,28 +40,28 @@ static GraphicsDevice getDefaultDevice() { * will bing all AWT listeners */ static DoomWindowController createCanvasWindowController( - final Supplier imageSource, - final Consumer doomEventConsume, - final int width, final int height + final Supplier imageSource, + final Consumer doomEventConsume, + final int width, final int height ) { final GraphicsDevice device = getDefaultDevice(); return new DoomWindowController<>(EventHandler.class, device, imageSource, doomEventConsume, - new CanvasWindow(getDefaultDevice().getDefaultConfiguration()), width, height); + new CanvasWindow(getDefaultDevice().getDefaultConfiguration()), width, height); } - + /** * Get an instance of JFrame to draw anything. This will try to create compatible Canvas and * will bing all AWT listeners */ static DoomWindowController createJPanelWindowController( - final Supplier imageSource, - final Consumer doomEventConsume, - final int width, final int height + final Supplier imageSource, + final Consumer doomEventConsume, + final int width, final int height ) { return new DoomWindowController<>(EventHandler.class, getDefaultDevice(), imageSource, - doomEventConsume, new JPanelWindow(), width, height); + doomEventConsume, new JPanelWindow(), width, height); } - + /** * Incomplete. Only checks for -geom format */ @@ -68,7 +69,7 @@ static DoomWindowController createJPanelWindowContro default boolean handleGeom() { int x = 0; int y = 0; - + // warning: char format, different type arg int xsign = ' '; int ysign = ' '; @@ -114,44 +115,46 @@ default boolean handleGeom() { } } } - + //this should parse two numbers. if (tk.countTokens() == 2) { x = xsign * Integer.parseInt(tk.nextToken()); y = ysign * Integer.parseInt(tk.nextToken()); } - + } catch (NumberFormatException e) { return false; } } - + return true; } - + final static class JPanelWindow extends JPanel implements DoomWindow { - private static final long serialVersionUID = 4031722796186278753L; - private JPanelWindow() { + private static final long serialVersionUID = 4031722796186278753L; + + private JPanelWindow() { init(); } - + private void init() { setDoubleBuffered(true); setOpaque(true); setBackground(Color.BLACK); } - + @Override public boolean isOptimizedDrawingEnabled() { return false; } } - + final static class CanvasWindow extends Canvas implements DoomWindow { - private static final long serialVersionUID = 1180777361390303859L; - private CanvasWindow(GraphicsConfiguration config) { + private static final long serialVersionUID = 1180777361390303859L; + + private CanvasWindow(GraphicsConfiguration config) { super(config); } } diff --git a/src/awt/DoomWindowController.java b/src/awt/DoomWindowController.java index ef3ccc2a..ef61c1fe 100644 --- a/src/awt/DoomWindowController.java +++ b/src/awt/DoomWindowController.java @@ -26,6 +26,7 @@ import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; +import java.util.logging.Logger; import m.Settings; import mochadoom.Engine; import mochadoom.Loggers; @@ -36,6 +37,9 @@ * That sort of things. */ public class DoomWindowController, H extends Enum & EventBase> implements FullscreenOptions { + + private static final Logger LOGGER = Loggers.getLogger(DoomWindow.class.getName()); + private static final long ALL_EVENTS_MASK = 0xFFFF_FFFF_FFFF_FFFFL; final GraphicsDevice device; @@ -54,13 +58,13 @@ public class DoomWindowController, H extends private boolean isFullScreen; DoomWindowController( - final Class handlerClass, - final GraphicsDevice device, - final Supplier imageSource, - final Consumer doomEventConsumer, - final E component, - final int defaultWidth, - final int defaultHeight + final Class handlerClass, + final GraphicsDevice device, + final Supplier imageSource, + final Consumer doomEventConsumer, + final E component, + final int defaultWidth, + final int defaultHeight ) { this.device = device; this.switcher = createFullSwitcher(device); @@ -74,19 +78,19 @@ public class DoomWindowController, H extends sizeInit(); doomFrame.turnOn(); } - + private void sizeInit() { try { if (!(Engine.getConfig().equals(Settings.fullscreen, Boolean.TRUE) && switchToFullScreen())) { updateSize(); } } catch (Exception e) { - Loggers.getLogger(DoomWindow.class.getName()).log(Level.SEVERE, + LOGGER.log(Level.SEVERE, String.format("Error creating DOOM AWT frame. Exiting. Reason: %s", e.getMessage()), e); throw e; } } - + public void updateFrame() { doomFrame.update(); } @@ -96,7 +100,7 @@ public EventObserver getObserver() { } public boolean switchFullscreen() { - Loggers.getLogger(DoomFrame.class.getName()).log(Level.WARNING, "FULLSCREEN SWITHED"); + LOGGER.log(Level.INFO, "Fullscreen switched"); // remove the frame from view doomFrame.dispose(); doomFrame = new DoomFrame<>(dimension, component, doomFrame.imageSupplier); @@ -149,10 +153,11 @@ private void updateSize() { public boolean isFullscreen() { return isFullScreen; } - + private class DimensionImpl extends java.awt.Dimension implements Dimension { - private static final long serialVersionUID = 4598094740125688728L; - private int offsetX, offsetY; + + private static final long serialVersionUID = 4598094740125688728L; + private int offsetX, offsetY; private int fitWidth, fitHeight; DimensionImpl(int width, int height) { @@ -162,7 +167,7 @@ private class DimensionImpl extends java.awt.Dimension implements Dimension { this.fitWidth = width; this.fitHeight = height; } - + @Override public int width() { return width; @@ -202,7 +207,7 @@ public int offsX() { public int offsY() { return offsetY; } - + private void setSize(DisplayMode mode) { if (isFullScreen) { this.width = mode.getWidth(); diff --git a/src/awt/EventBase.java b/src/awt/EventBase.java index 489fcc0b..db2d89bf 100644 --- a/src/awt/EventBase.java +++ b/src/awt/EventBase.java @@ -14,7 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package awt; import g.Signals; @@ -42,33 +41,38 @@ * @author Good Sign */ public interface EventBase & EventBase> extends IntSupplier { + static final Comparator EVENT_SORT = Comparator.comparingInt(IntSupplier::getAsInt); - + static & EventBase> H[] sortHandlers(H[] values) { Arrays.sort(values, EVENT_SORT); return values; } - + static & EventBase> Optional findById(H[] values, int eventId) { final int index = Arrays.binarySearch(values, (IntSupplier) () -> eventId, EVENT_SORT); if (index < 0) { return Optional.empty(); } - + return Optional.of(values[index]); } - + @SafeVarargs static & EventBase> Relation[] Relate(H src, H... dests) { + @SuppressWarnings("unchecked") final IntFunction[]> arrayer = Relation[]::new; return Arrays.stream(dests) - .map(dest -> new Relation<>(src, dest)) - .toArray(arrayer); + .map(dest -> new Relation<>(src, dest)) + .toArray(arrayer); } - + Set defaultEnabledActions(); + Map> allActions(); + Map> cooperations(); + Map> adjustments(); default boolean hasActions(final ActionMode... modes) { @@ -76,46 +80,44 @@ default boolean hasActions(final ActionMode... modes) { if (actions.isEmpty()) { return false; } - - for (final ActionMode m: modes) { + + for (final ActionMode m : modes) { if (!actions.contains(m)) { return false; } } - + return true; } - + enum KeyStateSatisfaction { SATISFIED_ATE, GENEOROUS_PASS, WANTS_MORE_ATE, WANTS_MORE_PASS } - + enum ActionMode { PERFORM, DEPEND, CAUSE, REVERT; } - + enum RelationAffection { ENABLES, DISABLES, COOPERATES; } - + enum RelationType { ENABLE(RelationAffection.ENABLES, ActionMode.PERFORM), ENABLE_DEPEND(RelationAffection.ENABLES, ActionMode.DEPEND), ENABLE_CAUSE(RelationAffection.ENABLES, ActionMode.CAUSE), ENABLE_REVERT(RelationAffection.ENABLES, ActionMode.REVERT), - DISABLE(RelationAffection.DISABLES, ActionMode.PERFORM), DISABLE_DEPEND(RelationAffection.DISABLES, ActionMode.DEPEND), DISABLE_CAUSE(RelationAffection.DISABLES, ActionMode.CAUSE), DISABLE_REVERT(RelationAffection.DISABLES, ActionMode.REVERT), - DEPEND(RelationAffection.COOPERATES, ActionMode.DEPEND), CAUSE(RelationAffection.COOPERATES, ActionMode.CAUSE), REVERT(RelationAffection.COOPERATES, ActionMode.REVERT); - + final RelationAffection affection; final ActionMode affectedMode; @@ -129,78 +131,85 @@ public String toString() { return String.format("%s on [%s]", affection, affectedMode); } } - + @FunctionalInterface interface ActionMapper & EventBase> { + void map(ActionMode mode, EventAction action); } - + @FunctionalInterface interface RelationMapper & EventBase> { + void map(RelationType type, Relation[] relations); } - + @FunctionalInterface interface EventAction & EventBase> { + void act(EventObserver obs, AWTEvent ev); } - - interface KeyStateCallback & EventBase> { + + interface KeyStateCallback & EventBase> { + KeyStateSatisfaction call(EventObserver observer); } - + final class KeyStateInterest & EventBase> { + private final Set interestSet; private final KeyStateCallback satisfiedCallback; public KeyStateInterest( - final KeyStateCallback satisfiedCallback, - final Signals.ScanCode interestFirstKey, - Signals.ScanCode... interestKeyChain + final KeyStateCallback satisfiedCallback, + final Signals.ScanCode interestFirstKey, + Signals.ScanCode... interestKeyChain ) { this.interestSet = EnumSet.of(interestFirstKey, interestKeyChain); this.satisfiedCallback = satisfiedCallback; } } - + final class KeyStateHolder & EventBase> { + private final Set holdingSet; private final LinkedHashSet> keyInterests; + @SuppressWarnings("unchecked") private final IntFunction[]> generator = KeyStateInterest[]::new; public KeyStateHolder() { this.holdingSet = EnumSet.noneOf(Signals.ScanCode.class); this.keyInterests = new LinkedHashSet<>(); } - + public void removeAllKeys() { holdingSet.clear(); } - + public boolean contains(Signals.ScanCode sc) { return holdingSet.contains(sc); } - + public void addInterest(KeyStateInterest interest) { this.keyInterests.add(interest); } - + public void removeInterest(KeyStateInterest interest) { this.keyInterests.remove(interest); } - + public boolean matchInterest(final KeyStateInterest check) { return holdingSet.containsAll(check.interestSet); } - + public boolean notifyKeyChange(EventObserver observer, Signals.ScanCode code, boolean press) { if (press) { holdingSet.add(code); - + final KeyStateInterest[] matched = keyInterests.stream() - .filter(this::matchInterest) - .toArray(this.generator); - + .filter(this::matchInterest) + .toArray(this.generator); + boolean ret = false; for (int i = 0; i < matched.length; ++i) { switch (matched[i].satisfiedCallback.call(observer)) { @@ -215,7 +224,7 @@ public boolean notifyKeyChange(EventObserver observer, Signals.ScanCode break; } } - + return ret; } else { holdingSet.remove(code); @@ -223,11 +232,12 @@ public boolean notifyKeyChange(EventObserver observer, Signals.ScanCode } } } - + /** * Enable/disable and remaps of actions is actually reflected here. It is only initial template in the Handler */ final class ActionStateHolder & EventBase> { + private final Map> enabledActions; private final Map>> actionsMap; private final Map>> cooperationMap; @@ -241,7 +251,7 @@ public boolean hasActionsEnabled(final Handler h, final ActionMode... modes) { return false; } - for (final ActionMode m: modes) { + for (final ActionMode m : modes) { if (!actions.contains(m)) { return false; } @@ -265,27 +275,27 @@ public ActionStateHolder(final Class hClass, final EventObserver> deepCopyMap(final Map> map) { if (map.isEmpty()) { return new EnumMap<>(RelationType.class); } - + // shallow copy first final EnumMap> copy = new EnumMap<>(map); // now values copy.replaceAll((r, l) -> EnumSet.copyOf(l)); return copy; } - + private Map populate(Class hClass, Handler[] values, Function mapper) { return Arrays.stream(values).collect( - () -> new EnumMap<>(hClass), - (m, h) -> m.put(h, mapper.apply(h)), - EnumMap::putAll + () -> new EnumMap<>(hClass), + (m, h) -> m.put(h, mapper.apply(h)), + EnumMap::putAll ); } - + public ActionStateHolder run(final Handler h, final ActionMode mode, final AWTEvent ev) { if (enabledActions.get(h).contains(mode)) { Optional.ofNullable(actionsMap.get(h).get(mode)).ifPresent(action -> action.act(observer, ev)); @@ -293,39 +303,39 @@ public ActionStateHolder run(final Handler h, final ActionMode mode, fi return this; } - + public Map> cooperations(final Handler h) { return cooperationMap.get(h); } - + public Map> adjustments(final Handler h) { return adjustmentMap.get(h); } - + public Set cooperations(final Handler h, final RelationType type) { return cooperationMap.get(h).getOrDefault(type, emptyEnumSet); } - + public Set adjustments(final Handler h, final RelationType type) { return adjustmentMap.get(h).getOrDefault(type, emptyEnumSet); } - + @SafeVarargs public final ActionStateHolder unmapCooperation(final Handler h, RelationType type, final Handler... targets) { final Set set = cooperationMap.get(h).get(type); if (set == null || set.isEmpty()) { return this; } - + if (targets.length == 0) { set.clear(); } else { set.removeAll(Arrays.asList(targets)); } - + return this; } - + @SafeVarargs public final ActionStateHolder mapCooperation(final Handler h, RelationType mode, final Handler... targets) { cooperationMap.get(h).compute(mode, (m, set) -> { @@ -335,14 +345,14 @@ public final ActionStateHolder mapCooperation(final Handler h, Relation set.addAll(Arrays.asList(targets)); return set; }); - + return this; } - + @SafeVarargs public final ActionStateHolder restoreCooperation(final Handler h, RelationType mode, final Handler... targets) { final Set orig = h.adjustments().get(mode); - + if (orig != null) { final Set a = EnumSet.copyOf(orig); final Set b = cooperationMap.get(h).get(mode); @@ -351,26 +361,26 @@ public final ActionStateHolder restoreCooperation(final Handler h, Rela } else { cooperationMap.get(h).remove(mode); } - + return this; } - + @SafeVarargs public final ActionStateHolder unmapAdjustment(final Handler h, RelationType type, final Handler... targets) { final Set set = adjustmentMap.get(h).get(type); if (set == null || set.isEmpty()) { return this; } - + if (targets.length == 0) { set.clear(); } else { set.removeAll(Arrays.asList(targets)); } - + return this; } - + @SafeVarargs public final ActionStateHolder mapAdjustment(final Handler h, RelationType mode, final Handler... targets) { adjustmentMap.get(h).compute(mode, (m, set) -> { @@ -380,14 +390,14 @@ public final ActionStateHolder mapAdjustment(final Handler h, RelationT set.addAll(Arrays.asList(targets)); return set; }); - + return this; } - + @SafeVarargs public final ActionStateHolder restoreAdjustment(final Handler h, RelationType mode, final Handler... targets) { final Set orig = h.adjustments().get(mode); - + if (orig != null) { final Set a = EnumSet.copyOf(orig); final Set b = adjustmentMap.get(h).get(mode); @@ -396,54 +406,55 @@ public final ActionStateHolder restoreAdjustment(final Handler h, Relat } else { adjustmentMap.get(h).remove(mode); } - + return this; } - + public ActionStateHolder enableAction(final Handler h, ActionMode mode) { enabledActions.get(h).add(mode); - + return this; } - + public ActionStateHolder disableAction(final Handler h, ActionMode mode) { enabledActions.get(h).remove(mode); - + return this; } - + public ActionStateHolder unmapAction(final Handler h, ActionMode mode) { actionsMap.get(h).remove(mode); - + return this; } - + public ActionStateHolder mapAction(final Handler h, ActionMode mode, EventAction remap) { actionsMap.get(h).put(mode, remap); - + return this; } - + public ActionStateHolder remapAction(final Handler h, ActionMode mode, EventAction remap) { actionsMap.get(h).replace(mode, remap); - + return this; } - + public ActionStateHolder restoreAction(final Handler h, ActionMode mode) { final EventAction a = h.allActions().get(mode); - + if (a != null) { actionsMap.get(h).put(mode, a); } else { actionsMap.get(h).remove(mode); } - + return this; } } - + final class Relation & EventBase> { + public final Handler sourceHandler; public final Handler targetHandler; diff --git a/src/awt/EventHandler.java b/src/awt/EventHandler.java index 31cf03dd..7a3fa3e1 100644 --- a/src/awt/EventHandler.java +++ b/src/awt/EventHandler.java @@ -14,12 +14,11 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package awt; import static awt.EventBase.Relate; import g.Signals; -import static g.Signals.ScanCode.*; +import static g.Signals.ScanCode.SC_PRTSCRN; import java.awt.Point; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; @@ -87,7 +86,6 @@ public enum EventHandler implements EventBase { } }); }, ActionMode.REVERT, ActionMode.PERFORM, ActionMode.DEPEND), - KEY_RELEASE(KeyEvent.KEY_RELEASED, mapper -> { mapper.map(ActionMode.PERFORM, EventObserver::sendKeyUps); /*mapper.map(ActionMode.DEPEND_BEFORE, (observer, event) -> { @@ -97,11 +95,9 @@ public enum EventHandler implements EventBase { } });*/ }, ActionMode.PERFORM/*, ActionMode.DEPEND*/), - KEY_TYPE(KeyEvent.KEY_TYPED, mapper -> { mapper.map(ActionMode.PERFORM, EventObserver::sendKeyUps); }, ActionMode.PERFORM), - MOUSE_PRESS(MouseEvent.MOUSE_PRESSED, mapper -> { mapper.map(ActionMode.REVERT, EventObserver::cancelMouse); mapper.map(ActionMode.PERFORM, (observer, ev) -> { @@ -113,8 +109,7 @@ public enum EventHandler implements EventBase { } }); }, ActionMode.REVERT, ActionMode.PERFORM), - - MOUSE_RELEASE(MouseEvent.MOUSE_RELEASED, mapper -> { + MOUSE_RELEASE(MouseEvent.MOUSE_RELEASED, mapper -> { mapper.map(ActionMode.PERFORM, (observer, ev) -> { observer.mouseEvent.buttonOff((MouseEvent) ev); observer.mouseEvent.x = observer.mouseEvent.y = 0; @@ -124,46 +119,35 @@ public enum EventHandler implements EventBase { } }); }, ActionMode.PERFORM), - MOUSE_CLICK(MouseEvent.MOUSE_CLICKED, mapper -> { // Set input method and mouse cursor, move cursor to the centre mapper.map(ActionMode.PERFORM, EventObserver::centreCursor); }), - MOUSE_MOVE(MouseEvent.MOUSE_MOVED, mapper -> { mapper.map(ActionMode.PERFORM, mouseMoveAction(false)); }, ActionMode.PERFORM), - MOUSE_DRAG(MouseEvent.MOUSE_DRAGGED, mapper -> { mapper.map(ActionMode.PERFORM, mouseMoveAction(true)); }, ActionMode.PERFORM), - WINDOW_ACTIVATE(WindowEvent.WINDOW_ACTIVATED, ActionMode.PERFORM, ActionMode.CAUSE), - WINDOW_DEICONIFY(WindowEvent.WINDOW_DEICONIFIED, ActionMode.PERFORM), - COMPONENT_RESIZE(ComponentEvent.COMPONENT_RESIZED, ActionMode.PERFORM), - MOUSE_ENTER(MouseEvent.MOUSE_ENTERED, mapper -> { // Set input method and mouse cursor, move cursor to the centre mapper.map(ActionMode.PERFORM, EventObserver::centreCursor); }), - WINDOW_OPEN(WindowEvent.WINDOW_OPENED, mapper -> { // Set input method and mouse cursor mapper.map(ActionMode.PERFORM, EventObserver::centreCursor); }, ActionMode.PERFORM), - - WINDOW_GAIN_FOCUS(WindowEvent.WINDOW_GAINED_FOCUS), - + WINDOW_GAIN_FOCUS(WindowEvent.WINDOW_GAINED_FOCUS, mapper -> { + mapper.map(ActionMode.PERFORM, EventObserver::modifyCursor); + }), WINDOW_LOSE_FOCUS(WindowEvent.WINDOW_LOST_FOCUS, mapper -> { mapper.map(ActionMode.PERFORM, EventObserver::restoreCursor); }, ActionMode.PERFORM), - COMPONENT_MOVE(ComponentEvent.COMPONENT_MOVED, ActionMode.PERFORM), - MOUSE_EXIT(MouseEvent.MOUSE_EXITED, ActionMode.PERFORM), - /** * We need to take charge of various scenarios such as what to do with mouse and keys when the * window lose focus, how to enter/return from alt-tab/full-screen switch, how to behave @@ -172,15 +156,15 @@ public enum EventHandler implements EventBase { RELATIONS(relationMapper -> { // Add keyDown for Print Screen because he doesn't send one relationMapper.map(RelationType.DEPEND, Relate(KEY_RELEASE, KEY_PRESS)); - + /** * After the window is opened, it must disable its own event, but capture all the keyboard and mouse input */ relationMapper.map(RelationType.DISABLE, Relate(WINDOW_OPEN, WINDOW_OPEN)); relationMapper.map(RelationType.ENABLE, Relate(WINDOW_OPEN, - WINDOW_LOSE_FOCUS, KEY_PRESS, KEY_RELEASE, KEY_TYPE, MOUSE_ENTER, MOUSE_MOVE, MOUSE_DRAG, MOUSE_PRESS, MOUSE_RELEASE + WINDOW_LOSE_FOCUS, KEY_PRESS, KEY_RELEASE, KEY_TYPE, MOUSE_ENTER, MOUSE_MOVE, MOUSE_DRAG, MOUSE_PRESS, MOUSE_RELEASE )); - + /** * On any activation/reconfiguration/resize/restore-from-something, request focus in window */ @@ -196,9 +180,9 @@ public enum EventHandler implements EventBase { */ relationMapper.map(RelationType.REVERT, Relate(WINDOW_LOSE_FOCUS, KEY_PRESS, MOUSE_PRESS)); relationMapper.map(RelationType.DISABLE, Relate(WINDOW_LOSE_FOCUS, WINDOW_LOSE_FOCUS, - KEY_PRESS, KEY_RELEASE, KEY_TYPE, MOUSE_MOVE, MOUSE_DRAG, MOUSE_PRESS, MOUSE_RELEASE, MOUSE_ENTER + KEY_PRESS, KEY_RELEASE, KEY_TYPE, MOUSE_MOVE, MOUSE_DRAG, MOUSE_PRESS, MOUSE_RELEASE, MOUSE_ENTER )); - + /** * The next set of rules is for active focus gain. It could be done in two ways: * natural, when window become visible topmost window with active borders, @@ -208,28 +192,28 @@ public enum EventHandler implements EventBase { * Enables back losing focus, disables itself and natural focus gain. */ relationMapper.map(RelationType.ENABLE, Relate(WINDOW_LOSE_FOCUS, - WINDOW_GAIN_FOCUS, MOUSE_CLICK + WINDOW_GAIN_FOCUS, MOUSE_CLICK )); relationMapper.map(RelationType.ENABLE, Relate(MOUSE_CLICK, - WINDOW_LOSE_FOCUS, KEY_PRESS, KEY_RELEASE, KEY_TYPE, MOUSE_ENTER, MOUSE_MOVE, MOUSE_DRAG, MOUSE_PRESS, MOUSE_RELEASE + WINDOW_LOSE_FOCUS, KEY_PRESS, KEY_RELEASE, KEY_TYPE, MOUSE_ENTER, MOUSE_MOVE, MOUSE_DRAG, MOUSE_PRESS, MOUSE_RELEASE )); relationMapper.map(RelationType.DISABLE, Relate(MOUSE_CLICK, WINDOW_GAIN_FOCUS, MOUSE_CLICK)); - + /** * For natural way, focus gain *must not* capture the mouse immediately, only after it enters the window. * Enables back losing focus, disables itself and clicky way of capture. */ relationMapper.map(RelationType.ENABLE, Relate(WINDOW_GAIN_FOCUS, - WINDOW_LOSE_FOCUS, KEY_PRESS, KEY_RELEASE, KEY_TYPE, MOUSE_ENTER + WINDOW_LOSE_FOCUS, KEY_PRESS, KEY_RELEASE, KEY_TYPE, MOUSE_ENTER )); relationMapper.map(RelationType.DISABLE, Relate(WINDOW_GAIN_FOCUS, WINDOW_GAIN_FOCUS)); - + /** * When the mouse returns to the window, it should be captured back, and the event disabled. */ relationMapper.map(RelationType.ENABLE, Relate(MOUSE_ENTER, MOUSE_MOVE, MOUSE_DRAG, MOUSE_PRESS, MOUSE_RELEASE)); relationMapper.map(RelationType.DISABLE, Relate(MOUSE_ENTER, MOUSE_ENTER)); - + /** * The last scenario is component move. Example of it - user drags the window by its head. * This way, first window is activated and gained focus, than component moved. Normally, the mouse would @@ -237,11 +221,11 @@ public enum EventHandler implements EventBase { * he then should manually click inside it to regain mouse capture - or alt-tab twice (regain window focus) */ relationMapper.map(RelationType.DISABLE, Relate(COMPONENT_MOVE, - MOUSE_MOVE, MOUSE_DRAG, MOUSE_PRESS, MOUSE_RELEASE, MOUSE_ENTER + MOUSE_MOVE, MOUSE_DRAG, MOUSE_PRESS, MOUSE_RELEASE, MOUSE_ENTER )); relationMapper.map(RelationType.ENABLE, Relate(COMPONENT_MOVE, MOUSE_CLICK)); }); - + public static void menuCaptureChanges(EventObserver observer, boolean capture) { if (capture) { observer.enableAction(MOUSE_MOVE, ActionMode.PERFORM); @@ -261,7 +245,7 @@ public static void menuCaptureChanges(EventObserver observer, bool observer.restoreCursor(null); } } - + public static void fullscreenChanges(EventObserver observer, boolean fullscreen) { /** * Clear any holding keys @@ -273,9 +257,9 @@ public static void fullscreenChanges(EventObserver observer, boole * (immediately after switch, or after return from alt-tab) */ observer.mapRelation(COMPONENT_RESIZE, RelationType.ENABLE, WINDOW_OPEN, - WINDOW_LOSE_FOCUS, KEY_PRESS, KEY_RELEASE, KEY_TYPE, MOUSE_ENTER, MOUSE_MOVE, MOUSE_DRAG, MOUSE_PRESS, MOUSE_RELEASE + WINDOW_LOSE_FOCUS, KEY_PRESS, KEY_RELEASE, KEY_TYPE, MOUSE_ENTER, MOUSE_MOVE, MOUSE_DRAG, MOUSE_PRESS, MOUSE_RELEASE ); - + /** * COMPONENT_MOVE is fired often in full-screen mode and does not mean that used did * something with the window frame, actually there is no frame, there is no sense - disable it @@ -286,14 +270,14 @@ public static void fullscreenChanges(EventObserver observer, boole * Remove full-screen COMPONENT_RESIZE relations, if they was added earlier */ observer.unmapRelation(COMPONENT_RESIZE, RelationType.ENABLE); - + /** * Immediately after return from full-screen mode, a bunch of events will occur, * some of them will cause mouse capture to be lost. Disable them. */ observer.disableAction(WINDOW_LOSE_FOCUS, ActionMode.PERFORM); observer.disableAction(COMPONENT_MOVE, ActionMode.PERFORM); - + /** * The last of the bunch of events should be WINDOW_ACTIVATE, add a function to him * to restore the proper reaction on events we have switched off. It also should remove @@ -306,7 +290,7 @@ public static void fullscreenChanges(EventObserver observer, boole }); } } - + private static EventAction mouseMoveAction(boolean isDrag) { return (observer, ev) -> { // Do not send robot-generated moves (centering) to the underlying DOOM's event engine @@ -322,7 +306,7 @@ private static EventAction mouseMoveAction(boolean isDrag) { } else { observer.mouseEvent.moveIn((MouseEvent) ev, centreX, centreY, isDrag); } - + if (observer.mouseEvent.processed) { observer.mouseEvent.resetNotify(); observer.feed(observer.mouseEvent); @@ -335,26 +319,25 @@ private static EventAction mouseMoveAction(boolean isDrag) { final Map> actions; final Map> adjustments; final Map> cooperations; - + private EventHandler(final Consumer> relationMapper) { this.eventId = -1; this.actions = Collections.emptyMap(); this.adjustments = Collections.emptyMap(); this.cooperations = Collections.emptyMap(); this.enabled = Collections.emptySet(); - relationMapper.accept((type, relations) -> - Stream.of(relations).forEach(relation -> - (type.affection == RelationAffection.COOPERATES - ? relation.sourceHandler.cooperations - : relation.sourceHandler.adjustments - ).compute(type, (t, set) -> { - (set == null ? (set = new HashSet<>()) : set).add(relation.targetHandler); - return set; - }) - ) + relationMapper.accept((type, relations) + -> Stream.of(relations).forEach(relation + -> (type.affection == RelationAffection.COOPERATES + ? relation.sourceHandler.cooperations + : relation.sourceHandler.adjustments).compute(type, (t, set) -> { + (set == null ? (set = new HashSet<>()) : set).add(relation.targetHandler); + return set; + }) + ) ); } - + private EventHandler(final int eventId, final ActionMode... enableModes) { this(eventId, null, enableModes); } @@ -364,22 +347,37 @@ private EventHandler(final int eventId, final Consumer(ActionMode.class); this.enabled = EnumSet.noneOf(ActionMode.class); this.enabled.addAll(Arrays.asList(enableModes)); - + this.adjustments = new EnumMap<>(RelationType.class); this.cooperations = new EnumMap<>(RelationType.class); - + if (actionMapper != null) { actionMapper.accept(actions::put); } } - + /** * Interface implementation */ - @Override public Set defaultEnabledActions() { return enabled; } - @Override public Map> allActions() { return actions; } - @Override public Map> cooperations() { return cooperations; } - @Override public Map> adjustments() { return adjustments; } + @Override + public Set defaultEnabledActions() { + return enabled; + } + + @Override + public Map> allActions() { + return actions; + } + + @Override + public Map> cooperations() { + return cooperations; + } + + @Override + public Map> adjustments() { + return adjustments; + } /** * A hack to make this Enum implementation sortable by primitive integers in another way then by ordinal() diff --git a/src/awt/EventObserver.java b/src/awt/EventObserver.java index 87573372..57d07678 100644 --- a/src/awt/EventObserver.java +++ b/src/awt/EventObserver.java @@ -14,7 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package awt; import awt.EventBase.ActionMode; @@ -37,6 +36,7 @@ import java.awt.Toolkit; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; +import java.awt.im.InputContext; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.Optional; @@ -46,8 +46,8 @@ import mochadoom.Loggers; /** - * Observer for AWTEvents. The description would be short in contrary to the description - * of EventHandler Enum. This class uses rules in Handler extends Enum & EventBase + * Observer for AWTEvents.The description would be short in contrary to the description + of EventHandler Enum. This class uses rules in Handler extends Enum & EventBase * to react on AWTEvent events given to him by some listener (or by fake, don't matter) and feeds them * to someone who needs them (DOOM's internal event handling system) * @@ -56,9 +56,10 @@ * and you need one part to react in one way, another part in another. * * @author Good Sign + * @param the type of the handler */ public class EventObserver & EventBase> { - + static final Optional MOUSE_ROBOT = createRobot(); private static final Logger LOGGER = Loggers.getLogger(EventObserver.class.getName()); @@ -81,8 +82,7 @@ private static Optional createRobot() { try { return Optional.of(new Robot()); } catch (AWTException e) { - Loggers.getLogger(EventObserver.class.getName()) - .log(Level.SEVERE, "AWT Robot could not be created, mouse input focus will be loose!", e); + LOGGER.log(Level.SEVERE, "AWT Robot could not be created, mouse input focus will be loose!", e); } return Optional.empty(); } @@ -103,7 +103,7 @@ private Cursor createHiddenCursor() { final BufferedImage transparent = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB); return tk.createCustomCursor(transparent, new Point(1, 1), "HiddenCursor"); } - + /** * This event here is used as a static scratch copy. When sending out * messages, its contents are to be actually copied (struct-like). @@ -119,40 +119,40 @@ private Cursor createHiddenCursor() { * Shared state of keys */ protected final KeyStateHolder keyStateHolder; - + /** * Component (Canvas or JPanel, for exaple) to deal with */ protected final Component component; - + /** * This one will be given all event_t's we produce there */ private final Consumer doomEventConsumer; - + /** * Will be used to find Handler by AWTEvent's id */ private final Handler[] eventSortedHandlers; - + /** * Shared state of actions */ private final ActionStateHolder actionStateHolder; - + /** * Presumably a system Cursor, that is to be used on cursor restore. */ private final Cursor initialCursor; /** - * Ivisible cursor on the systems who support changing cursors + * Invisible cursor on the systems who support changing cursors */ private final Cursor hiddenCursor; - + /** * To construct the Observer you only need to provide it with the class of Enum used - * to contain dictinary, the Component it will be working on and acceptor of event_t's + * to contain dictionary, the Component it will be working on and acceptor of event_t's */ public EventObserver(Class handlerClass, Component component, Consumer doomEventConsumer) { this.actionStateHolder = new ActionStateHolder<>(handlerClass, this); @@ -163,13 +163,13 @@ public EventObserver(Class handlerClass, Component component, Consumer< this.hiddenCursor = createHiddenCursor(); this.keyStateHolder = new KeyStateHolder<>(); } - + public EventObserver addInterest(EventBase.KeyStateInterest interest) { keyStateHolder.addInterest(interest); return this; } - public EventObserver removeInterest(EventBase.KeyStateInterest interest) { + public EventObserver removeInterest(EventBase.KeyStateInterest interest) { keyStateHolder.removeInterest(interest); return this; } @@ -184,14 +184,10 @@ public void observe(final AWTEvent ev) { if (!maybe.isPresent() || !actionStateHolder.hasActionsEnabled(handler = maybe.get(), ActionMode.PERFORM)) { return; } - - if (handler == EventHandler.WINDOW_ACTIVATE) { - int u = 8; - } - + // In case of debug. If level > FINE (most of cases) it will not affect anything Loggers.LogEvent(LOGGER, actionStateHolder, handler, ev); - + actionStateHolder.run(handler, ActionMode.PERFORM, ev); actionStateHolder.adjustments(handler).forEach((relation, affected) -> { switch (relation.affection) { @@ -205,14 +201,14 @@ public void observe(final AWTEvent ev) { actionStateHolder.disableAction(h, relation.affectedMode); }); default: - break; + break; } }); - + actionStateHolder.cooperations(handler, RelationType.CAUSE).forEach(h -> { actionStateHolder.run(h, ActionMode.CAUSE, ev); }); - + actionStateHolder.cooperations(handler, RelationType.REVERT).forEach(h -> { actionStateHolder.run(h, ActionMode.REVERT, ev); }); @@ -240,7 +236,10 @@ protected void restoreCursor(final AWTEvent event) { * Hide cursor */ protected void modifyCursor(final AWTEvent event) { - component.getInputContext().selectInputMethod(java.util.Locale.US); + InputContext inputContext = component.getInputContext(); + if (inputContext != null) { + inputContext.selectInputMethod(java.util.Locale.US); + } component.setCursor(hiddenCursor); } @@ -251,9 +250,9 @@ protected void modifyCursor(final AWTEvent event) { * - Good Sign 2017/04/24 */ protected void centreCursor(final AWTEvent event) { - final int centreX = component.getWidth() >> 1; - final int centreY = component.getHeight() >> 1; if (component.isShowing()) { + int centreX = component.getWidth() >> 1; + int centreY = component.getHeight() >> 1; MOUSE_ROBOT.ifPresent(rob -> mouseEvent.resetIn(rob, component.getLocationOnScreen(), centreX, centreY)); } modifyCursor(event); @@ -289,7 +288,7 @@ protected void sendKeyDowns(final AWTEvent ev) { feed(Signals.getScanCode((KeyEvent) ev).doomEventDown); discardInputEvent(ev); } - + /** * Consumes InputEvents so they will not pass further */ @@ -300,21 +299,21 @@ protected void discardInputEvent(final AWTEvent ev) { LOGGER.log(Level.SEVERE, null, ex); } } - + protected final void enableAction(final Handler h, ActionMode mode) { actionStateHolder.enableAction(h, mode); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, () -> String.format("ENABLE ACTION: %s [%s]", h, mode)); } } - + protected final void disableAction(final Handler h, ActionMode mode) { actionStateHolder.disableAction(h, mode); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, () -> String.format("DISABLE ACTION: %s [%s]", h, mode)); } } - + @SafeVarargs protected final void mapRelation(final Handler h, RelationType type, Handler... targets) { if (type.affection == EventBase.RelationAffection.COOPERATES) { @@ -326,7 +325,7 @@ protected final void mapRelation(final Handler h, RelationType type, Handler... LOGGER.log(Level.FINE, () -> String.format("RELATION MAPPING: %s -> [%s] {%s}", h, type, Arrays.toString(targets))); } } - + @SafeVarargs protected final void unmapRelation(final Handler h, RelationType type, Handler... targets) { if (type.affection == EventBase.RelationAffection.COOPERATES) { @@ -338,7 +337,7 @@ protected final void unmapRelation(final Handler h, RelationType type, Handler.. LOGGER.log(Level.FINE, () -> String.format("RELATION UNMAP: %s -> [%s] {%s}", h, type, Arrays.toString(targets))); } } - + @SafeVarargs protected final void restoreRelation(final Handler h, RelationType type, Handler... targets) { if (type.affection == EventBase.RelationAffection.COOPERATES) { @@ -350,28 +349,28 @@ protected final void restoreRelation(final Handler h, RelationType type, Handler LOGGER.log(Level.FINE, () -> String.format("RELATION RESTORE: %s -> [%s] {%s}", h, type, Arrays.toString(targets))); } } - + protected void mapAction(final Handler h, ActionMode mode, EventAction remap) { actionStateHolder.mapAction(h, mode, remap); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, () -> String.format("ACTION MAPPING (MAP): %s [%s]", h, mode)); } } - + protected void remapAction(final Handler h, ActionMode mode, EventAction remap) { actionStateHolder.remapAction(h, mode, remap); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, () -> String.format("ACTION MAPPING (REMAP): %s [%s]", h, mode)); } } - + protected void unmapAction(final Handler h, ActionMode mode) { actionStateHolder.unmapAction(h, mode); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, () -> String.format("UNMAP ACTION: %s [%s]", h, mode)); } } - + protected void restoreAction(final Handler h, ActionMode mode) { actionStateHolder.restoreAction(h, mode); if (LOGGER.isLoggable(Level.FINE)) { diff --git a/src/awt/FullscreenOptions.java b/src/awt/FullscreenOptions.java index d4f9add2..3f564fe8 100644 --- a/src/awt/FullscreenOptions.java +++ b/src/awt/FullscreenOptions.java @@ -20,7 +20,10 @@ import java.awt.Graphics2D; import java.awt.GraphicsDevice; import java.awt.Image; -import static java.awt.RenderingHints.*; +import static java.awt.RenderingHints.KEY_INTERPOLATION; +import static java.awt.RenderingHints.VALUE_INTERPOLATION_BICUBIC; +import static java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR; +import static java.awt.RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR; import java.awt.image.ImageObserver; import m.Settings; import mochadoom.Engine; @@ -31,40 +34,41 @@ * @author Good Sign */ public interface FullscreenOptions { + enum InterpolationMode { - Nearest, Bilinear, Biqubic; + Nearest, Bilinear, Bicubic; } - + enum StretchMode { Centre( - (w, defW, h, defH) -> Math.min(defW, w), - (w, defW, h, defH) -> Math.min(defH, h), - (w, defW, h, defH) -> Math.max(0, (w - defW) / 2), - (w, defW, h, defH) -> Math.max(0, (h - defH) / 2) + (w, defW, h, defH) -> Math.min(defW, w), + (w, defW, h, defH) -> Math.min(defH, h), + (w, defW, h, defH) -> Math.max(0, (w - defW) / 2), + (w, defW, h, defH) -> Math.max(0, (h - defH) / 2) ), Stretch( - (w, defW, h, defH) -> w, - (w, defW, h, defH) -> h, - (w, defW, h, defH) -> 0, - (w, defW, h, defH) -> 0 + (w, defW, h, defH) -> w, + (w, defW, h, defH) -> h, + (w, defW, h, defH) -> 0, + (w, defW, h, defH) -> 0 ), Fit( - (w, defW, h, defH) -> (int) (defW * minScale(w, defW, h, defH)), - (w, defW, h, defH) -> (int) (defH * minScale(w, defW, h, defH)), - (w, defW, h, defH) -> (w - (int) (defW * minScale(w, defW, h, defH))) / 2, - (w, defW, h, defH) -> (h - (int) (defH * minScale(w, defW, h, defH))) / 2 + (w, defW, h, defH) -> (int) (defW * minScale(w, defW, h, defH)), + (w, defW, h, defH) -> (int) (defH * minScale(w, defW, h, defH)), + (w, defW, h, defH) -> (w - (int) (defW * minScale(w, defW, h, defH))) / 2, + (w, defW, h, defH) -> (h - (int) (defH * minScale(w, defW, h, defH))) / 2 ), Aspect_4_3( - (w, defW, h, defH) -> Fit.widthFun.fit(w, defW, h, (int) (defH * 1.2f)), - (w, defW, h, defH) -> Fit.heightFun.fit(w, defW, h, (int) (defH * 1.2f)), - (w, defW, h, defH) -> Fit.offsXFun.fit(w, defW, h, (int) (defH * 1.2f)), - (w, defW, h, defH) -> Fit.offsYFun.fit(w, defW, h, (int) (defH * 1.2f)) + (w, defW, h, defH) -> Fit.widthFun.fit(w, defW, h, (int) (defH * 1.2f)), + (w, defW, h, defH) -> Fit.heightFun.fit(w, defW, h, (int) (defH * 1.2f)), + (w, defW, h, defH) -> Fit.offsXFun.fit(w, defW, h, (int) (defH * 1.2f)), + (w, defW, h, defH) -> Fit.offsYFun.fit(w, defW, h, (int) (defH * 1.2f)) ); - + final Fitter widthFun, heightFun, offsXFun, offsYFun; private StretchMode( - final Fitter widthFun, - final Fitter heightFun, - final Fitter offsXFun, - final Fitter offsYFun + final Fitter widthFun, + final Fitter heightFun, + final Fitter offsXFun, + final Fitter offsYFun ) { this.widthFun = widthFun; this.heightFun = heightFun; @@ -78,77 +82,84 @@ private static float minScale(int w, int defW, int h, int defH) { return Math.min(scaleX, scaleY); } } - + enum FullMode { Best, Native; } - + static FullMode FULLMODE = Engine.getConfig().getValue(Settings.fullscreen_mode, FullMode.class); static StretchMode STRETCH = Engine.getConfig().getValue(Settings.fullscreen_stretch, StretchMode.class); static InterpolationMode INTERPOLATION = Engine.getConfig().getValue(Settings.fullscreen_interpolation, InterpolationMode.class); - + interface Dimension { + int width(); + int height(); + int defWidth(); + int defHeight(); - + default int fitX() { return STRETCH.widthFun.fit(width(), defWidth(), height(), defHeight()); } - + default int fitY() { return STRETCH.heightFun.fit(width(), defWidth(), height(), defHeight()); } - + default int offsX() { return STRETCH.offsXFun.fit(width(), defWidth(), height(), defHeight()); } - + default int offsY() { return STRETCH.offsYFun.fit(width(), defWidth(), height(), defHeight()); } } - + interface Fitter { + int fit(int width, int defWidth, int height, int defHeight); } - - default void options(Graphics2D graphics) { - switch(INTERPOLATION) { + + default void applyFullscreenOptions(Graphics2D graphics) { + switch (INTERPOLATION) { case Nearest: graphics.setRenderingHint(KEY_INTERPOLATION, VALUE_INTERPOLATION_NEAREST_NEIGHBOR); break; case Bilinear: graphics.setRenderingHint(KEY_INTERPOLATION, VALUE_INTERPOLATION_BILINEAR); break; - case Biqubic: + case Bicubic: graphics.setRenderingHint(KEY_INTERPOLATION, VALUE_INTERPOLATION_BICUBIC); break; } } - + default void draw(Graphics2D graphics, Image image, Dimension dim, ImageObserver observer) { graphics.drawImage(image, dim.offsX(), dim.offsY(), dim.fitX(), dim.fitY(), observer); } - + default FullscreenFunction createFullSwitcher(final GraphicsDevice device) { - switch(FULLMODE) { + switch (FULLMODE) { case Best: return new FullscreenSwitch(device, new DisplayModePicker(device)); case Native: return (w, h) -> device.getDisplayMode(); } - - throw new Error("Enum reflection overuse?"); + + throw new Error(String.format("Unsupported mode: %s", String.valueOf(FULLMODE))); } - + @FunctionalInterface interface FullscreenFunction { + DisplayMode get(int width, int height); } - + static class FullscreenSwitch implements FullscreenFunction { + private final GraphicsDevice dev; private final DisplayModePicker dmp; private DisplayMode oldDisplayMode; @@ -171,7 +182,7 @@ public DisplayMode get(final int width, final int height) { displayMode = oldDisplayMode; oldDisplayMode = null; } - + return displayMode; } } diff --git a/src/awt/MsgBox.java b/src/awt/MsgBox.java index f533236c..96876a47 100644 --- a/src/awt/MsgBox.java +++ b/src/awt/MsgBox.java @@ -1,9 +1,14 @@ package awt; -import java.awt.*; - -import java.awt.event.*; - +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Panel; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; import javax.swing.JLabel; /** A convenient message box class to pop up here and there. @@ -11,80 +16,82 @@ * @author zyklon * */ - public class MsgBox extends Dialog implements ActionListener { - /** - * - */ - private static final long serialVersionUID = -872019680203708495L; - private Button ok, can; - private boolean isOk = false; - /* + /** + * + */ + private static final long serialVersionUID = -872019680203708495L; + private Button ok, can; + private boolean isOk = false; + + /* * * @param frame parent frame * * @param msg message to be displayed * * @param okcan true : ok cancel buttons, false : ok button only - */ - - public boolean isOk() { - return isOk; - } + */ + public boolean isOk() { + return isOk; + } - public MsgBox(Frame frame, String title, String msg, boolean okcan) { - super(frame, title, true); - setLayout(new BorderLayout()); - add("Center", new JLabel(msg)); - addOKCancelPanel(okcan); - createFrame(); - pack(); - setVisible(true); - this.can.requestFocus(); - } + public MsgBox(Frame frame, String title, String msg, boolean okcan) { + super(frame, title, true); + setLayout(new BorderLayout()); + add("Center", new JLabel(msg)); + addOKCancelPanel(okcan); + createFrame(); + pack(); + setVisible(true); + if (this.can != null) { + this.can.requestFocus(); + } + } - public MsgBox(Frame frame, String msg) { - this(frame, "Message", msg, false); - } + public MsgBox(Frame frame, String msg) { + this(frame, "Message", msg, false); + } - private void addOKCancelPanel(boolean okcan) { - Panel p = new Panel(); - p.setLayout(new FlowLayout()); - createOKButton(p); - if (okcan == true) - createCancelButton(p); - add("South", p); - } + private void addOKCancelPanel(boolean okcan) { + Panel p = new Panel(); + p.setLayout(new FlowLayout()); + createOKButton(p); + if (okcan == true) { + createCancelButton(p); + } + add("South", p); + } - private void createOKButton(Panel p) { - p.add(ok = new Button("OK")); - ok.addActionListener(this); - } + private void createOKButton(Panel p) { + p.add(ok = new Button("OK")); + ok.addActionListener(this); + } - private void createCancelButton(Panel p) { - p.add(can = new Button("Cancel")); - can.addActionListener(this); - } + private void createCancelButton(Panel p) { + p.add(can = new Button("Cancel")); + can.addActionListener(this); + } - private void createFrame() { - Dimension d = getToolkit().getScreenSize(); - setLocation(d.width / 3, d.height / 3); - } + private void createFrame() { + Dimension d = getToolkit().getScreenSize(); + setLocation(d.width / 3, d.height / 3); + } - public void actionPerformed(ActionEvent ae) { - if (ae.getSource() == ok) { - isOk = true; - setVisible(false); - } else if (ae.getSource() == can) { - setVisible(false); - } - } + public void actionPerformed(ActionEvent ae) { + if (ae.getSource() == ok) { + isOk = true; + setVisible(false); + } else if (can != null && ae.getSource() == can) { + setVisible(false); + } + } - /* + /* * public static void main(String args[]) { //Frame f = new Frame(); * //f.setSize(200,200); //f.setVisible(true); MsgBox message = new MsgBox * (null , "Hey you user, are you sure ?", true); if (message.isOk) * System.out.println("Ok pressed"); if (!message.isOk) * System.out.println("Cancel pressed"); message.dispose(); } - */ -} \ No newline at end of file + */ +} diff --git a/src/boom/Compatibility.java b/src/boom/Compatibility.java index 920248dc..c7fb2ce5 100644 --- a/src/boom/Compatibility.java +++ b/src/boom/Compatibility.java @@ -5,87 +5,104 @@ * @author cph * */ - public final class Compatibility { - /** Doom v1.2 */ - public static final int doom_12_compatibility=0; - - public static final int doom_1666_compatibility=1; /* Doom v1.666 */ - public static final int doom2_19_compatibility=2; /* Doom & Doom 2 v1.9 */ - public static final int ultdoom_compatibility=3; /* Ultimate Doom and Doom95 */ - public static final int finaldoom_compatibility=4; /* Final Doom */ - public static final int dosdoom_compatibility=5; /* DosDoom 0.47 */ - public static final int tasdoom_compatibility=6; /* TASDoom */ - public static final int boom_compatibility_compatibility=7; /* Boom's compatibility mode */ - public static final int boom_201_compatibility=8; /* Boom v2.01 */ - public static final int boom_202_compatibility=9; /* Boom v2.02 */ - public static final int lxdoom_1_compatibility=10; /* LxDoom v1.3.2+ */ - public static final int mbf_compatibility=11; /* MBF */ - public static final int prboom_1_compatibility=12; /* PrBoom 2.03beta? */ - public static final int prboom_2_compatibility=13; /* PrBoom 2.1.0-2.1.1 */ - public static final int prboom_3_compatibility=14; /* PrBoom 2.2.x */ - public static final int prboom_4_compatibility=15; /* PrBoom 2.3.x */ - public static final int prboom_5_compatibility=16; /* PrBoom 2.4.0 */ - public static final int prboom_6_compatibility=17; /* Latest PrBoom */ - public static final int MAX_COMPATIBILITY_LEVEL=18; /* Must be last entry */ - /* Aliases follow */ - public static final int boom_compatibility = boom_201_compatibility; /* Alias used by G_Compatibility */ - public static final int best_compatibility = prboom_6_compatibility; - - public static final prboom_comp_t[] prboom_comp = { - new prboom_comp_t(0xffffffff, 0x02020615, false, "-force_monster_avoid_hazards"), - new prboom_comp_t(0x00000000, 0x02040601, false, "-force_remove_slime_trails"), - new prboom_comp_t(0x02020200, 0x02040801, false, "-force_no_dropoff"), - new prboom_comp_t(0x00000000, 0x02040801, false, "-force_truncated_sector_specials"), - new prboom_comp_t(0x00000000, 0x02040802, false, "-force_boom_brainawake"), - new prboom_comp_t(0x00000000, 0x02040802, false, "-force_prboom_friction"), - new prboom_comp_t(0x02020500, 0x02040000, false, "-reject_pad_with_ff"), - new prboom_comp_t(0xffffffff, 0x02040802, false, "-force_lxdoom_demo_compatibility"), - new prboom_comp_t(0x00000000, 0x0202061b, false, "-allow_ssg_direct"), - new prboom_comp_t(0x00000000, 0x02040601, false, "-treat_no_clipping_things_as_not_blocking"), - new prboom_comp_t(0x00000000, 0x02040803, false, "-force_incorrect_processing_of_respawn_frame_entry"), - new prboom_comp_t(0x00000000, 0x02040601, false, "-force_correct_code_for_3_keys_doors_in_mbf"), - new prboom_comp_t(0x00000000, 0x02040601, false, "-uninitialize_crush_field_for_stairs"), - new prboom_comp_t(0x00000000, 0x02040802, false, "-force_boom_findnexthighestfloor"), - new prboom_comp_t(0x00000000, 0x02040802, false, "-allow_sky_transfer_in_boom"), - new prboom_comp_t(0x00000000, 0x02040803, false, "-apply_green_armor_class_to_armor_bonuses"), - new prboom_comp_t(0x00000000, 0x02040803, false, "-apply_blue_armor_class_to_megasphere"), - new prboom_comp_t(0x02050001, 0x02050003, false, "-wrong_fixeddiv"), - new prboom_comp_t(0x02020200, 0x02050003, false, "-force_incorrect_bobbing_in_boom"), - new prboom_comp_t(0xffffffff, 0x00000000, false, "-boom_deh_parser"), - new prboom_comp_t(0x00000000, 0x02050007, false, "-mbf_remove_thinker_in_killmobj"), - new prboom_comp_t(0x00000000, 0x02050007, false, "-do_not_inherit_friendlyness_flag_on_spawn"), - new prboom_comp_t(0x00000000, 0x02050007, false, "-do_not_use_misc12_frame_parameters_in_a_mushroom") - }; - - public static final int PC_MONSTER_AVOID_HAZARDS=0; - public static final int PC_REMOVE_SLIME_TRAILS=1; - public static final int PC_NO_DROPOFF=2; - public static final int PC_TRUNCATED_SECTOR_SPECIALS=3; - public static final int PC_BOOM_BRAINAWAKE=4; - public static final int PC_PRBOOM_FRICTION=5; - public static final int PC_REJECT_PAD_WITH_FF=6; - public static final int PC_FORCE_LXDOOM_DEMO_COMPATIBILITY=7; - public static final int PC_ALLOW_SSG_DIRECT=8; - public static final int PC_TREAT_NO_CLIPPING_THINGS_AS_NOT_BLOCKING=9; - public static final int PC_FORCE_INCORRECT_PROCESSING_OF_RESPAWN_FRAME_ENTRY=10; - public static final int PC_FORCE_CORRECT_CODE_FOR_3_KEYS_DOORS_IN_MBF=11; - public static final int PC_UNINITIALIZE_CRUSH_FIELD_FOR_STAIRS=12; - public static final int PC_FORCE_BOOM_FINDNEXTHIGHESTFLOOR=13; - public static final int PC_ALLOW_SKY_TRANSFER_IN_BOOM=14; - public static final int PC_APPLY_GREEN_ARMOR_CLASS_TO_ARMOR_BONUSES=15; - public static final int PC_APPLY_BLUE_ARMOR_CLASS_TO_MEGASPHERE=16; - public static final int PC_WRONG_FIXEDDIV=17; - public static final int PC_FORCE_INCORRECT_BOBBING_IN_BOOM=18; - public static final int PC_BOOM_DEH_PARSER=19; - public static final int PC_MBF_REMOVE_THINKER_IN_KILLMOBJ=20; - public static final int PC_DO_NOT_INHERIT_FRIENDLYNESS_FLAG_ON_SPAWN=21; - public static final int PC_DO_NOT_USE_MISC12_FRAME_PARAMETERS_IN_A_MUSHROOM=21; - public static final int PC_MAX=23; - - public enum PC - { + /** Doom v1.2 */ + public static final int doom_12_compatibility = 0; + + public static final int doom_1666_compatibility = 1; + /* Doom v1.666 */ + public static final int doom2_19_compatibility = 2; + /* Doom & Doom 2 v1.9 */ + public static final int ultdoom_compatibility = 3; + /* Ultimate Doom and Doom95 */ + public static final int finaldoom_compatibility = 4; + /* Final Doom */ + public static final int dosdoom_compatibility = 5; + /* DosDoom 0.47 */ + public static final int tasdoom_compatibility = 6; + /* TASDoom */ + public static final int boom_compatibility_compatibility = 7; + /* Boom's compatibility mode */ + public static final int boom_201_compatibility = 8; + /* Boom v2.01 */ + public static final int boom_202_compatibility = 9; + /* Boom v2.02 */ + public static final int lxdoom_1_compatibility = 10; + /* LxDoom v1.3.2+ */ + public static final int mbf_compatibility = 11; + /* MBF */ + public static final int prboom_1_compatibility = 12; + /* PrBoom 2.03beta? */ + public static final int prboom_2_compatibility = 13; + /* PrBoom 2.1.0-2.1.1 */ + public static final int prboom_3_compatibility = 14; + /* PrBoom 2.2.x */ + public static final int prboom_4_compatibility = 15; + /* PrBoom 2.3.x */ + public static final int prboom_5_compatibility = 16; + /* PrBoom 2.4.0 */ + public static final int prboom_6_compatibility = 17; + /* Latest PrBoom */ + public static final int MAX_COMPATIBILITY_LEVEL = 18; + /* Must be last entry */ + /* Aliases follow */ + public static final int boom_compatibility = boom_201_compatibility; + /* Alias used by G_Compatibility */ + public static final int best_compatibility = prboom_6_compatibility; + + public static final prboom_comp_t[] prboom_comp = { + new prboom_comp_t(0xffffffff, 0x02020615, false, "-force_monster_avoid_hazards"), + new prboom_comp_t(0x00000000, 0x02040601, false, "-force_remove_slime_trails"), + new prboom_comp_t(0x02020200, 0x02040801, false, "-force_no_dropoff"), + new prboom_comp_t(0x00000000, 0x02040801, false, "-force_truncated_sector_specials"), + new prboom_comp_t(0x00000000, 0x02040802, false, "-force_boom_brainawake"), + new prboom_comp_t(0x00000000, 0x02040802, false, "-force_prboom_friction"), + new prboom_comp_t(0x02020500, 0x02040000, false, "-reject_pad_with_ff"), + new prboom_comp_t(0xffffffff, 0x02040802, false, "-force_lxdoom_demo_compatibility"), + new prboom_comp_t(0x00000000, 0x0202061b, false, "-allow_ssg_direct"), + new prboom_comp_t(0x00000000, 0x02040601, false, "-treat_no_clipping_things_as_not_blocking"), + new prboom_comp_t(0x00000000, 0x02040803, false, "-force_incorrect_processing_of_respawn_frame_entry"), + new prboom_comp_t(0x00000000, 0x02040601, false, "-force_correct_code_for_3_keys_doors_in_mbf"), + new prboom_comp_t(0x00000000, 0x02040601, false, "-uninitialize_crush_field_for_stairs"), + new prboom_comp_t(0x00000000, 0x02040802, false, "-force_boom_findnexthighestfloor"), + new prboom_comp_t(0x00000000, 0x02040802, false, "-allow_sky_transfer_in_boom"), + new prboom_comp_t(0x00000000, 0x02040803, false, "-apply_green_armor_class_to_armor_bonuses"), + new prboom_comp_t(0x00000000, 0x02040803, false, "-apply_blue_armor_class_to_megasphere"), + new prboom_comp_t(0x02050001, 0x02050003, false, "-wrong_fixeddiv"), + new prboom_comp_t(0x02020200, 0x02050003, false, "-force_incorrect_bobbing_in_boom"), + new prboom_comp_t(0xffffffff, 0x00000000, false, "-boom_deh_parser"), + new prboom_comp_t(0x00000000, 0x02050007, false, "-mbf_remove_thinker_in_killmobj"), + new prboom_comp_t(0x00000000, 0x02050007, false, "-do_not_inherit_friendlyness_flag_on_spawn"), + new prboom_comp_t(0x00000000, 0x02050007, false, "-do_not_use_misc12_frame_parameters_in_a_mushroom") + }; + + public static final int PC_MONSTER_AVOID_HAZARDS = 0; + public static final int PC_REMOVE_SLIME_TRAILS = 1; + public static final int PC_NO_DROPOFF = 2; + public static final int PC_TRUNCATED_SECTOR_SPECIALS = 3; + public static final int PC_BOOM_BRAINAWAKE = 4; + public static final int PC_PRBOOM_FRICTION = 5; + public static final int PC_REJECT_PAD_WITH_FF = 6; + public static final int PC_FORCE_LXDOOM_DEMO_COMPATIBILITY = 7; + public static final int PC_ALLOW_SSG_DIRECT = 8; + public static final int PC_TREAT_NO_CLIPPING_THINGS_AS_NOT_BLOCKING = 9; + public static final int PC_FORCE_INCORRECT_PROCESSING_OF_RESPAWN_FRAME_ENTRY = 10; + public static final int PC_FORCE_CORRECT_CODE_FOR_3_KEYS_DOORS_IN_MBF = 11; + public static final int PC_UNINITIALIZE_CRUSH_FIELD_FOR_STAIRS = 12; + public static final int PC_FORCE_BOOM_FINDNEXTHIGHESTFLOOR = 13; + public static final int PC_ALLOW_SKY_TRANSFER_IN_BOOM = 14; + public static final int PC_APPLY_GREEN_ARMOR_CLASS_TO_ARMOR_BONUSES = 15; + public static final int PC_APPLY_BLUE_ARMOR_CLASS_TO_MEGASPHERE = 16; + public static final int PC_WRONG_FIXEDDIV = 17; + public static final int PC_FORCE_INCORRECT_BOBBING_IN_BOOM = 18; + public static final int PC_BOOM_DEH_PARSER = 19; + public static final int PC_MBF_REMOVE_THINKER_IN_KILLMOBJ = 20; + public static final int PC_DO_NOT_INHERIT_FRIENDLYNESS_FLAG_ON_SPAWN = 21; + public static final int PC_DO_NOT_USE_MISC12_FRAME_PARAMETERS_IN_A_MUSHROOM = 21; + public static final int PC_MAX = 23; + + public enum PC { PC_MONSTER_AVOID_HAZARDS, PC_REMOVE_SLIME_TRAILS, PC_NO_DROPOFF, @@ -110,6 +127,6 @@ public enum PC PC_DO_NOT_INHERIT_FRIENDLYNESS_FLAG_ON_SPAWN, PC_DO_NOT_USE_MISC12_FRAME_PARAMETERS_IN_A_MUSHROOM, PC_MAX - }; - - } + }; + +} diff --git a/src/boom/E6Y.java b/src/boom/E6Y.java index 779296e5..57e1e519 100644 --- a/src/boom/E6Y.java +++ b/src/boom/E6Y.java @@ -32,10 +32,9 @@ * *----------------------------------------------------------------------------- */ +public interface E6Y { -public interface E6Y{ - -/* + /* #define HU_HUDADDX (HU_HUDX) #define HU_HUDADDY (HU_HUDY+(-1)*HU_GAPY) #define HU_CENTERMSGX (320/2) @@ -45,47 +44,45 @@ public interface E6Y{ #define HU_HUDADDY_D (HU_HUDY_LL+(-1)*HU_GAPY) #define HU_MSGCENTERTIMEOUT (2*TICRATE) -*/ - -public static final String STSTR_SECRETFOUND = "A secret is revealed!"; + */ + public static final String STSTR_SECRETFOUND = "A secret is revealed!"; -public static final int S_CANT_GL_ARB_MULTITEXTURE= 0x10000000; -public static final int S_CANT_GL_ARB_MULTISAMPLEFACTOR= 0x20000000; + public static final int S_CANT_GL_ARB_MULTITEXTURE = 0x10000000; + public static final int S_CANT_GL_ARB_MULTISAMPLEFACTOR = 0x20000000; -public static final int GL_COMBINE_ARB = 0x8570; -public static final int GL_RGB_SCALE_ARB = 0x8573; + public static final int GL_COMBINE_ARB = 0x8570; + public static final int GL_RGB_SCALE_ARB = 0x8573; -public static final char NO_INDEX =0xFFFF; + public static final char NO_INDEX = 0xFFFF; -public static final float FOV_CORRECTION_FACTOR= 1.13776f; -public static final int FOV90 =90; + public static final float FOV_CORRECTION_FACTOR = 1.13776f; + public static final int FOV90 = 90; //public static final double DEG2RAD( a ) ( a * Pi ) / 180.0f; //#define RAD2DEG( a ) ( a / Pi ) * 180.0f; - -public class buf_overrun_item_t -{ - String wadname; - int map; - int address; -} - -public class camera_t -{ - long x; - long y; - long z; - long PrevX; - long PrevY; - long PrevZ; - long angle; - long pitch; - long PrevAngle; - long PrevPitch; - int type; -} - -/* + public class buf_overrun_item_t { + + String wadname; + int map; + int address; + } + + public class camera_t { + + long x; + long y; + long z; + long PrevX; + long PrevY; + long PrevZ; + long angle; + long pitch; + long PrevAngle; + long PrevPitch; + int type; + } + + /* extern int REAL_SCREENWIDTH; extern int REAL_SCREENHEIGHT; @@ -411,6 +408,5 @@ public class camera_t #endif #endif -*/ - -} \ No newline at end of file + */ +} diff --git a/src/boom/mapglvertex_t.java b/src/boom/mapglvertex_t.java index aeb27d4b..6fda1ba5 100644 --- a/src/boom/mapglvertex_t.java +++ b/src/boom/mapglvertex_t.java @@ -6,8 +6,8 @@ import w.CacheableDoomObject; /** fixed 32 bit gl_vert format v2.0+ (glBsp 1.91) */ +public class mapglvertex_t implements CacheableDoomObject { -public class mapglvertex_t implements CacheableDoomObject{ public int x, y; // fixed_t public static int sizeOf() { @@ -18,7 +18,7 @@ public static int sizeOf() { public void unpack(ByteBuffer buf) throws IOException { buf.order(ByteOrder.LITTLE_ENDIAN); - x=buf.getInt(); - y=buf.getInt(); + x = buf.getInt(); + y = buf.getInt(); } -} \ No newline at end of file +} diff --git a/src/boom/mapnode_v4_t.java b/src/boom/mapnode_v4_t.java index a94b6c2c..2dd15cd6 100644 --- a/src/boom/mapnode_v4_t.java +++ b/src/boom/mapnode_v4_t.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; - import w.CacheableDoomObject; import w.DoomBuffer; diff --git a/src/boom/mapnode_znod_t.java b/src/boom/mapnode_znod_t.java index d4e14a4c..590d95c6 100644 --- a/src/boom/mapnode_znod_t.java +++ b/src/boom/mapnode_znod_t.java @@ -3,43 +3,41 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; - import w.CacheableDoomObject; import w.DoomBuffer; public class mapnode_znod_t implements CacheableDoomObject { - - public short x; // Partition line from (x,y) to x+dx,y+dy) - public short y; - public short dx; - public short dy; - // Bounding box for each child, clip against view frustum. - public short[][] bbox; - // If NF_SUBSECTOR its a subsector, else it's a node of another subtree. - public int[] children; - - public mapnode_znod_t(){ - this.bbox = new short[2][4]; - this.children = new int[2]; - } - - public static final int sizeOf() { - return (8 + 16 + 8); - } - - @Override - public void unpack(ByteBuffer buf) - throws IOException { - buf.order(ByteOrder.LITTLE_ENDIAN); - this.x = buf.getShort(); - this.y = buf.getShort(); - this.dx = buf.getShort(); - this.dy = buf.getShort(); - DoomBuffer.readShortArray(buf, this.bbox[0], 4); - DoomBuffer.readShortArray(buf, this.bbox[1], 4); - DoomBuffer.readIntArray(buf, this.children, 2); - - } + public short x; // Partition line from (x,y) to x+dx,y+dy) + public short y; + public short dx; + public short dy; + // Bounding box for each child, clip against view frustum. + public short[][] bbox; + // If NF_SUBSECTOR its a subsector, else it's a node of another subtree. + public int[] children; + + public mapnode_znod_t() { + this.bbox = new short[2][4]; + this.children = new int[2]; + } + + public static final int sizeOf() { + return (8 + 16 + 8); + } + + @Override + public void unpack(ByteBuffer buf) + throws IOException { + buf.order(ByteOrder.LITTLE_ENDIAN); + this.x = buf.getShort(); + this.y = buf.getShort(); + this.dx = buf.getShort(); + this.dy = buf.getShort(); + DoomBuffer.readShortArray(buf, this.bbox[0], 4); + DoomBuffer.readShortArray(buf, this.bbox[1], 4); + DoomBuffer.readIntArray(buf, this.children, 2); + + } } diff --git a/src/boom/mapseg_v4_t.java b/src/boom/mapseg_v4_t.java index 6ed83718..9ff89ace 100644 --- a/src/boom/mapseg_v4_t.java +++ b/src/boom/mapseg_v4_t.java @@ -11,35 +11,34 @@ * MAES: this is the ON-DISK structure. The corresponding memory structure, * segs_t, has fixed_t members. */ +public class mapseg_v4_t implements CacheableDoomObject { + + public mapseg_v4_t() { + + } + + public int v1; + public int v2; + public char angle; + public char linedef; + public char side; + public char offset; + + public static int sizeOf() { + return 16; + } + + @Override + public void unpack(ByteBuffer buf) + throws IOException { + buf.order(ByteOrder.LITTLE_ENDIAN); + this.v1 = buf.getInt(); + this.v2 = buf.getInt(); + this.angle = buf.getChar(); + this.linedef = buf.getChar(); + this.side = buf.getChar(); + this.offset = buf.getChar(); -public class mapseg_v4_t implements CacheableDoomObject{ - - public mapseg_v4_t(){ - } - public int v1; - public int v2; - public char angle; - public char linedef; - public char side; - public char offset; - - public static int sizeOf(){ - return 16; - } - - @Override - public void unpack(ByteBuffer buf) - throws IOException { - buf.order(ByteOrder.LITTLE_ENDIAN); - this.v1 = buf.getInt(); - this.v2 = buf.getInt(); - this.angle=buf.getChar(); - this.linedef=buf.getChar(); - this.side=buf.getChar(); - this.offset=buf.getChar(); - - } - - }; +}; diff --git a/src/boom/mapseg_znod_t.java b/src/boom/mapseg_znod_t.java index a5f7b368..a62580d0 100644 --- a/src/boom/mapseg_znod_t.java +++ b/src/boom/mapseg_znod_t.java @@ -8,29 +8,28 @@ /** ZDoom node? * */ +public class mapseg_znod_t implements CacheableDoomObject { -public class mapseg_znod_t implements CacheableDoomObject{ - - public mapseg_znod_t(){ - + public mapseg_znod_t() { + + } + + public int v1, v2; // Those are unsigned :-/ + public char linedef; + public byte side; + + public static int sizeOf() { + return 11; + } + + @Override + public void unpack(ByteBuffer buf) + throws IOException { + buf.order(ByteOrder.LITTLE_ENDIAN); + this.v1 = buf.getInt(); + this.v2 = buf.getInt(); + this.linedef = buf.getChar(); + this.side = buf.get(); } - public int v1,v2; // Those are unsigned :-/ - public char linedef; - public byte side; - - public static int sizeOf(){ - return 11; - } - - @Override - public void unpack(ByteBuffer buf) - throws IOException { - buf.order(ByteOrder.LITTLE_ENDIAN); - this.v1 = buf.getInt(); - this.v2 = buf.getInt(); - this.linedef=buf.getChar(); - this.side=buf.get(); - } - - }; +}; diff --git a/src/boom/mapsubsector_v4_t.java b/src/boom/mapsubsector_v4_t.java index b5413407..d04058d9 100644 --- a/src/boom/mapsubsector_v4_t.java +++ b/src/boom/mapsubsector_v4_t.java @@ -3,25 +3,24 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; - import w.CacheableDoomObject; -public class mapsubsector_v4_t implements CacheableDoomObject{ - - public char numsegs; - /** Index of first one, segs are stored sequentially. */ - public int firstseg; - - @Override - public void unpack(ByteBuffer buf) - throws IOException { - buf.order(ByteOrder.LITTLE_ENDIAN); - this.numsegs = buf.getChar(); - this.firstseg = buf.getInt(); - } +public class mapsubsector_v4_t implements CacheableDoomObject { + + public char numsegs; + /** Index of first one, segs are stored sequentially. */ + public int firstseg; + + @Override + public void unpack(ByteBuffer buf) + throws IOException { + buf.order(ByteOrder.LITTLE_ENDIAN); + this.numsegs = buf.getChar(); + this.firstseg = buf.getInt(); + } + + public static int sizeOf() { + return 6; + } - public static int sizeOf(){ - return 6; - } - } diff --git a/src/boom/mapsubsector_znod_t.java b/src/boom/mapsubsector_znod_t.java index af8c2cab..19bd91d8 100644 --- a/src/boom/mapsubsector_znod_t.java +++ b/src/boom/mapsubsector_znod_t.java @@ -3,23 +3,22 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; - import utils.C2JUtils; import w.CacheableDoomObject; -public class mapsubsector_znod_t implements CacheableDoomObject{ - +public class mapsubsector_znod_t implements CacheableDoomObject { + public long numsegs; - - @Override - public void unpack(ByteBuffer buf) - throws IOException { - buf.order(ByteOrder.LITTLE_ENDIAN); - this.numsegs = C2JUtils.unsigned(buf.getInt()); - } - public static final int sizeOf(){ - return 4; - } - + @Override + public void unpack(ByteBuffer buf) + throws IOException { + buf.order(ByteOrder.LITTLE_ENDIAN); + this.numsegs = C2JUtils.unsigned(buf.getInt()); + } + + public static final int sizeOf() { + return 4; + } + } diff --git a/src/boom/prboom_comp_t.java b/src/boom/prboom_comp_t.java index 4b1b5451..bc0da37f 100644 --- a/src/boom/prboom_comp_t.java +++ b/src/boom/prboom_comp_t.java @@ -16,4 +16,4 @@ public prboom_comp_t(int minver, int maxver, boolean state, String cmd) { public boolean state; public String cmd; -} \ No newline at end of file +} diff --git a/src/data/Defines.java b/src/data/Defines.java index 75a1e6a6..2c6c262e 100644 --- a/src/data/Defines.java +++ b/src/data/Defines.java @@ -33,31 +33,26 @@ // key definitions, lots of other stuff. // //----------------------------------------------------------------------------- - //#ifndef __DOOMDEF__ //#define __DOOMDEF__ - //#include //#include - // // Global parameters/defines. // // DOOM version -public final class Defines{ - - /** Seems to be 109 for shareware 1.9, wtf is this*/ -public static final int VERSION = 109 ; +public final class Defines { -public static final int JAVARANDOM_MASK = 0x80; - -/** Some parts of the code may actually be better used as if in a UNIX environment */ + /** Seems to be 109 for shareware 1.9, wtf is this*/ + public static final int VERSION = 109; -public static final boolean NORMALUNIX =false; + public static final int JAVARANDOM_MASK = 0x80; + /** Some parts of the code may actually be better used as if in a UNIX environment */ + public static final boolean NORMALUNIX = false; -/** If rangecheck is undefined, ost parameter validation debugging code will not be compiled */ -public static final boolean RANGECHECK=false; + /** If rangecheck is undefined, ost parameter validation debugging code will not be compiled */ + public static final boolean RANGECHECK = false; // Do or do not use external soundserver. // The sndserver binary to be run separately @@ -68,84 +63,73 @@ public final class Defines{ // handled by SNDINTR. //#define SNDSERV 1 //#define SNDINTR 1 - // Defines suck. C sucks. // C++ might sucks for OOP, but it sure is a better C. // So there. - // MAES: moved static defines out of here and into VideoScaleInfo. - // State updates, number of tics / second. -public static final int BASETICRATE = 35; -public static final int TIC_MUL = 1; -public static final int TICRATE = BASETICRATE*TIC_MUL; + public static final int BASETICRATE = 35; + public static final int TIC_MUL = 1; + public static final int TICRATE = BASETICRATE * TIC_MUL; // // Difficulty/skill settings/filters. // - // Skill flags. -public static int MTF_EASY = 1; -public static int MTF_NORMAL = 2; -public static int MTF_HARD = 4; + public static int MTF_EASY = 1; + public static int MTF_NORMAL = 2; + public static int MTF_HARD = 4; // Deaf monsters/do not react to sound. -public static int MTF_AMBUSH =8; + public static int MTF_AMBUSH = 8; //Maes: this makes it a bit less retarded. -public static final int NUMCARDS=card_t.NUMCARDS.ordinal(); - + public static final int NUMCARDS = card_t.NUMCARDS.ordinal(); //Maes: this makes it a bit less retarded. -public static final int NUMWEAPONS=weapontype_t.NUMWEAPONS.ordinal(); + public static final int NUMWEAPONS = weapontype_t.NUMWEAPONS.ordinal(); //Maes: this makes it a bit less retarded. -public static final int NUMAMMO=ammotype_t.NUMAMMO.ordinal(); + public static final int NUMAMMO = ammotype_t.NUMAMMO.ordinal(); // Power up artifacts. -public static final int pw_invulnerability=0; -public static final int pw_strength=1; -public static final int pw_invisibility=2; -public static final int pw_ironfeet=3; -public static final int pw_allmap=4; -public static final int pw_infrared=5; -public static final int NUMPOWERS=6; - - -/** Power up durations, - * how many seconds till expiration, - * assuming TICRATE is 35 ticks/second. - */ - public static final int INVULNTICS=(30*TICRATE), - INVISTICS=(60*TICRATE), - INFRATICS=(120*TICRATE), - IRONTICS =(60*TICRATE); + public static final int pw_invulnerability = 0; + public static final int pw_strength = 1; + public static final int pw_invisibility = 2; + public static final int pw_ironfeet = 3; + public static final int pw_allmap = 4; + public static final int pw_infrared = 5; + public static final int NUMPOWERS = 6; + + /** Power up durations, + * how many seconds till expiration, + * assuming TICRATE is 35 ticks/second. + */ + public static final int INVULNTICS = (30 * TICRATE), + INVISTICS = (60 * TICRATE), + INFRATICS = (120 * TICRATE), + IRONTICS = (60 * TICRATE); // Center command from Heretic -public final static int TOCENTER=-8; + public final static int TOCENTER = -8; // from r_defs.h: - - - //Silhouette, needed for clipping Segs (mainly) //and sprites representing things. -public static final int SIL_NONE =0; -public static final int SIL_BOTTOM =1; -public static final int SIL_TOP = 2; -public static final int SIL_BOTH = 3; + public static final int SIL_NONE = 0; + public static final int SIL_BOTTOM = 1; + public static final int SIL_TOP = 2; + public static final int SIL_BOTH = 3; //SKY, store the number for name. -static public final String SKYFLATNAME ="F_SKY1"; + static public final String SKYFLATNAME = "F_SKY1"; // The sky map is 256*128*4 maps. -public static final int ANGLETOSKYSHIFT = 22; + public static final int ANGLETOSKYSHIFT = 22; // From r_draw.c - // status bar height at bottom of screen -public static final int SBARHEIGHT = 32; - + public static final int SBARHEIGHT = 32; // //Different vetween registered DOOM (1994) and @@ -153,9 +137,8 @@ public final class Defines{ //This is supposedly ignored for commercial //release (aka DOOM II), which had 34 maps //in one episode. So there. -public static final int NUMEPISODES=4; -public static final int NUMMAPS =9; - + public static final int NUMEPISODES = 4; + public static final int NUMMAPS = 9; //in tics //U #define PAUSELEN (TICRATE*2) @@ -164,137 +147,118 @@ public final class Defines{ //pixel distance from "(YOU)" to "PLAYER N" //U #define STARDIST 10 //U #define WK 1 - - // MAES 23/5/2011: moved SP_... stuff to EndLevel - -public static final int BACKUPTICS = 12; - - - + public static final int BACKUPTICS = 12; // From Zone: - // //ZONE MEMORY //PU - purge tags. //Tags < 100 are not overwritten until freed. -public static final int PU_STATIC = 1; // static entire execution time -public static final int PU_SOUND = 2; // static while playing -public static final int PU_MUSIC = 3; // static while playing -public static final int PU_DAVE = 4; // anything else Dave wants static -public static final int PU_LEVEL = 50; // static until level exited -public static final int PU_LEVSPEC = 51; // a special thinker in a level + public static final int PU_STATIC = 1; // static entire execution time + public static final int PU_SOUND = 2; // static while playing + public static final int PU_MUSIC = 3; // static while playing + public static final int PU_DAVE = 4; // anything else Dave wants static + public static final int PU_LEVEL = 50; // static until level exited + public static final int PU_LEVSPEC = 51; // a special thinker in a level //Tags >= 100 are purgable whenever needed. -public static final int PU_PURGELEVEL = 100; -public static final int PU_CACHE = 101; - + public static final int PU_PURGELEVEL = 100; + public static final int PU_CACHE = 101; // From hu_lib.h: - //font stuff -static public final Signals.ScanCode HU_CHARERASE = Signals.ScanCode.SC_BACKSPACE; + static public final Signals.ScanCode HU_CHARERASE = Signals.ScanCode.SC_BACKSPACE; -public static final int HU_MAXLINES = 4; -public static final int HU_MAXLINELENGTH = 80; + public static final int HU_MAXLINES = 4; + public static final int HU_MAXLINELENGTH = 80; // From hu_stuff.h - // //Globally visible constants. // -static public final byte HU_FONTSTART = '!'; // the first font characters -static public final byte HU_FONTEND ='_'; // the last font characters + static public final byte HU_FONTSTART = '!'; // the first font characters + static public final byte HU_FONTEND = '_'; // the last font characters //Calculate # of glyphs in font. -public static final int HU_FONTSIZE = (HU_FONTEND - HU_FONTSTART + 1); + public static final int HU_FONTSIZE = (HU_FONTEND - HU_FONTSTART + 1); -static public final char HU_BROADCAST = 5; + static public final char HU_BROADCAST = 5; -static public final Signals.ScanCode HU_MSGREFRESH = Signals.ScanCode.SC_ENTER; -static public final char HU_MSGX =0; -static public final char HU_MSGY =0; -static public final char HU_MSGWIDTH =64; // in characters -static public final char HU_MSGHEIGHT = 1; // in lines + static public final Signals.ScanCode HU_MSGREFRESH = Signals.ScanCode.SC_ENTER; + static public final char HU_MSGX = 0; + static public final char HU_MSGY = 0; + static public final char HU_MSGWIDTH = 64; // in characters + static public final char HU_MSGHEIGHT = 1; // in lines -public static final int HU_MSGTIMEOUT = (4*TICRATE); + public static final int HU_MSGTIMEOUT = (4 * TICRATE); -public static final int SAVESTRINGSIZE = 24; + public static final int SAVESTRINGSIZE = 24; // // Button/action code definitions. // From d_event.h + // Press "Fire". + public static final int BT_ATTACK = 1; + // Use button, to open doors, activate switches. + public static final int BT_USE = 2; + + // Flag: game events, not really buttons. + public static final int BT_SPECIAL = 128; + public static final int BT_SPECIALMASK = 3; + + // Flag, weapon change pending. + // If true, the next 3 bits hold weapon num. + public static final int BT_CHANGE = 4; + // The 3bit weapon mask and shift, convenience. + public static final int BT_WEAPONMASK = (8 + 16 + 32); + public static final int BT_WEAPONSHIFT = 3; + + // Pause the game. + public static final int BTS_PAUSE = 1; + // Save the game at each console. + public static final int BTS_SAVEGAME = 2; + + // Savegame slot numbers + // occupy the second byte of buttons. + public static final int BTS_SAVEMASK = (4 + 8 + 16); + public static final int BTS_SAVESHIFT = 2; - // Press "Fire". - public static final int BT_ATTACK = 1; - // Use button, to open doors, activate switches. - public static final int BT_USE = 2; - - // Flag: game events, not really buttons. - public static final int BT_SPECIAL = 128; - public static final int BT_SPECIALMASK = 3; - - // Flag, weapon change pending. - // If true, the next 3 bits hold weapon num. - public static final int BT_CHANGE = 4; - // The 3bit weapon mask and shift, convenience. - public static final int BT_WEAPONMASK = (8+16+32); - public static final int BT_WEAPONSHIFT = 3; - - // Pause the game. - public static final int BTS_PAUSE = 1; - // Save the game at each console. - public static final int BTS_SAVEGAME = 2; - - // Savegame slot numbers - // occupy the second byte of buttons. - public static final int BTS_SAVEMASK = (4+8+16); - public static final int BTS_SAVESHIFT = 2; - - - - //==================== Stuff from r_local.c ========================================= + public static final int FLOATSPEED = (FRACUNIT * 4); - - public static final int FLOATSPEED =(FRACUNIT*4); - - public static final int VIEWHEIGHT = (41*FRACUNIT); + public static final int VIEWHEIGHT = (41 * FRACUNIT); // mapblocks are used to check movement // against lines and things - public static final int MAPBLOCKUNITS= 128; - public static final int MAPBLOCKSIZE =(MAPBLOCKUNITS*FRACUNIT); - public static final int MAPBLOCKSHIFT =(FRACBITS+7); - public static final int MAPBMASK =(MAPBLOCKSIZE-1); - public static final int MAPBTOFRAC= (MAPBLOCKSHIFT-FRACBITS); - public static final int BLOCKMAPPADDING= 8*FRACUNIT; + public static final int MAPBLOCKUNITS = 128; + public static final int MAPBLOCKSIZE = (MAPBLOCKUNITS * FRACUNIT); + public static final int MAPBLOCKSHIFT = (FRACBITS + 7); + public static final int MAPBMASK = (MAPBLOCKSIZE - 1); + public static final int MAPBTOFRAC = (MAPBLOCKSHIFT - FRACBITS); + public static final int BLOCKMAPPADDING = 8 * FRACUNIT; // player radius for movement checking - public static final int PLAYERRADIUS =16*FRACUNIT; - public static final int GRAVITY = MAPFRACUNIT; - public static int USERANGE =(64*FRACUNIT); - public static int MELEERANGE = (64*FRACUNIT); - public static int MISSILERANGE=(32*64*FRACUNIT); + public static final int PLAYERRADIUS = 16 * FRACUNIT; + public static final int GRAVITY = MAPFRACUNIT; + public static int USERANGE = (64 * FRACUNIT); + public static int MELEERANGE = (64 * FRACUNIT); + public static int MISSILERANGE = (32 * 64 * FRACUNIT); // follow a player exlusively for 3 seconds - public static int BASETHRESHOLD= 100; + public static int BASETHRESHOLD = 100; + public static int PT_ADDLINES = 1; + public static int PT_ADDTHINGS = 2; + public static int PT_EARLYOUT = 4; - - public static int PT_ADDLINES =1; - public static int PT_ADDTHINGS =2; - public static int PT_EARLYOUT =4; - - // - // P_MOBJ - // - public static int ONFLOORZ = MININT; - public static int ONCEILINGZ = MAXINT; + // + // P_MOBJ + // + public static int ONFLOORZ = MININT; + public static int ONCEILINGZ = MAXINT; - // Time interval for item respawning. - public static int ITEMQUESIZE =128; - + // Time interval for item respawning. + public static int ITEMQUESIZE = 128; /** Indicate a leaf. e6y: support for extended nodes */ public static final int NF_SUBSECTOR = 0x80000000; @@ -302,21 +266,14 @@ public final class Defines{ /** This is the regular leaf indicator. Use for reference/conversions */ public static final int NF_SUBSECTOR_CLASSIC = 0x8000; - - /** Player states. */ - - public static final int PST_LIVE=0, // Playing or camping. - PST_DEAD=1, // Dead on the ground, view follows killer. + public static final int PST_LIVE = 0, // Playing or camping. + PST_DEAD = 1, // Dead on the ground, view follows killer. - PST_REBORN=2; // Ready to restart/respawn??? - - public static final int FF_FULLBRIGHT = 0x8000; // flag in thing->frame - public static final int FF_FRAMEMASK = 0x7fff; + PST_REBORN = 2; // Ready to restart/respawn??? + public static final int FF_FULLBRIGHT = 0x8000; // flag in thing->frame + public static final int FF_FRAMEMASK = 0x7fff; - -static final String -rcsid = "$Id: Defines.java,v 1.48 2012/09/24 17:16:22 velktron Exp $"; + static final String rcsid = "$Id: Defines.java,v 1.48 2012/09/24 17:16:22 velktron Exp $"; } - diff --git a/src/data/Limits.java b/src/data/Limits.java index 7b13c704..45c3ff5e 100644 --- a/src/data/Limits.java +++ b/src/data/Limits.java @@ -4,99 +4,98 @@ import static m.fixed_t.MAPFRACUNIT; /** Everything that constitutes a removable limit should go here */ - public final class Limits { - // Obvious rendering limits - public static final int MAXVISPLANES = 128; - public static final int MAXSEGS = 32; - public static final int MAXVISSPRITES = 128; - public static final int MAXDRAWSEGS = 256; - // MAES: Moved MAXOPENINGS to renderer state, it's scale dependant. - public static final int CEILSPEED = MAPFRACUNIT; - public static final int CEILWAIT = 150; - public static final int MAXCEILINGS = 30; - - public static final int MAXANIMS = 32; - - /** Animating line specials */ - public static final int MAXLINEANIMS = 64; - - // These are only used in the renderer, effectively putting - // a limit to the size of lookup tables for screen buffers. - public static final int MAXWIDTH = 1600; - public static final int MAXHEIGHT = 1200; - - // Command line/file limits - public static final int MAXWADFILES = 20; - public static final int MAXARGVS = 100; - - // The maximum number of players, multiplayer/networking. - // Max computers/players in a game. AFFECTS SAVEGAMES. - public static final int MAXPLAYERS = 4; - public final static int MAXNETNODES = 8; - - /** Some quirky engine limits */ - public static final int MAXEVENTS = 64; - - /** max # of wall switch TYPES in a level */ - public static final int MAXSWITCHES = 50; - - /** 20 adjoining sectors max! */ - public static final int MAX_ADJOINING_SECTORS = 20; - - // 4 players, 4 buttons each at once, max. - public static final int MAXBUTTONS = 16; - - // 1 second, in ticks. - public static final int BUTTONTIME = 35; - - /** - * keep track of special lines as they are hit, but don't process them until - * the move is proven valid - */ - public static final int MAXSPECIALCROSS = 8; - public static final int MAXHEALTH = 100; - - /** - * MAXRADIUS is for precalculated sector block boxes the spider demon is - * larger, but we do not have any moving sectors nearby - */ - public static final int MAXRADIUS = 32 * FRACUNIT; - - public static final int MAXINTERCEPTS = 128; - public static final int MAXMOVE = (30 * MAPFRACUNIT); - - /** Player spawn spots for deathmatch. */ - public static final int MAX_DM_STARTS = 10; - - // C's "chars" are actually Java signed bytes. - public static final byte MAXCHAR = ((byte) 0x7f); - public static final byte MINCHAR = ((byte) 0x80); - - // 16-bit integers... - public static final short MAXSHORT = ((short) 0x7fff); - public static final short MINSHORT = ((short) 0x8000); - - // Max pos 32-bit int. - public static final int MAXINT = ((int) 0x7fffffff); - public static final long MAXLONG = ((long) 0x7fffffff); - - // Max negative 32-bit integer. These are considered to be the same. - public static final int MININT = ((int) 0x80000000); - public static final long MINLONG = ((long) 0x80000000); - - // Buffering/memory limits. - public static final int SAVEGAMESIZE = 0x2c000; - - public static final int SAVESTRINGSIZE = 24; - public static final int VERSIONSIZE = 16; - - public static final int PLATWAIT = 3; - public static final int PLATSPEED = MAPFRACUNIT; - public static final int MAXPLATS = 30; - public static final int MAXSKULLS = 20; - public static final int NUMBRAINTARGETS=32; - public static final int NUMMOBJTYPES=mobjtype_t.NUMMOBJTYPES.ordinal(); - + // Obvious rendering limits + public static final int MAXVISPLANES = 128; + public static final int MAXSEGS = 32; + public static final int MAXVISSPRITES = 128; + public static final int MAXDRAWSEGS = 256; + // MAES: Moved MAXOPENINGS to renderer state, it's scale dependant. + public static final int CEILSPEED = MAPFRACUNIT; + public static final int CEILWAIT = 150; + public static final int MAXCEILINGS = 30; + + public static final int MAXANIMS = 32; + + /** Animating line specials */ + public static final int MAXLINEANIMS = 64; + + // These are only used in the renderer, effectively putting + // a limit to the size of lookup tables for screen buffers. + public static final int MAXWIDTH = 1600; + public static final int MAXHEIGHT = 1200; + + // Command line/file limits + public static final int MAXWADFILES = 20; + public static final int MAXARGVS = 100; + + // The maximum number of players, multiplayer/networking. + // Max computers/players in a game. AFFECTS SAVEGAMES. + public static final int MAXPLAYERS = 4; + public final static int MAXNETNODES = 8; + + /** Some quirky engine limits */ + public static final int MAXEVENTS = 64; + + /** max # of wall switch TYPES in a level */ + public static final int MAXSWITCHES = 50; + + /** 20 adjoining sectors max! */ + public static final int MAX_ADJOINING_SECTORS = 20; + + // 4 players, 4 buttons each at once, max. + public static final int MAXBUTTONS = 16; + + // 1 second, in ticks. + public static final int BUTTONTIME = 35; + + /** + * keep track of special lines as they are hit, but don't process them until + * the move is proven valid + */ + public static final int MAXSPECIALCROSS = 8; + public static final int MAXHEALTH = 100; + + /** + * MAXRADIUS is for precalculated sector block boxes the spider demon is + * larger, but we do not have any moving sectors nearby + */ + public static final int MAXRADIUS = 32 * FRACUNIT; + + public static final int MAXINTERCEPTS = 128; + public static final int MAXMOVE = (30 * MAPFRACUNIT); + + /** Player spawn spots for deathmatch. */ + public static final int MAX_DM_STARTS = 10; + + // C's "chars" are actually Java signed bytes. + public static final byte MAXCHAR = ((byte) 0x7f); + public static final byte MINCHAR = ((byte) 0x80); + + // 16-bit integers... + public static final short MAXSHORT = ((short) 0x7fff); + public static final short MINSHORT = ((short) 0x8000); + + // Max pos 32-bit int. + public static final int MAXINT = ((int) 0x7fffffff); + public static final long MAXLONG = ((long) 0x7fffffff); + + // Max negative 32-bit integer. These are considered to be the same. + public static final int MININT = ((int) 0x80000000); + public static final long MINLONG = ((long) 0x80000000); + + // Buffering/memory limits. + public static final int SAVEGAMESIZE = 0x2c000; + + public static final int SAVESTRINGSIZE = 24; + public static final int VERSIONSIZE = 16; + + public static final int PLATWAIT = 3; + public static final int PLATSPEED = MAPFRACUNIT; + public static final int MAXPLATS = 30; + public static final int MAXSKULLS = 20; + public static final int NUMBRAINTARGETS = 32; + public static final int NUMMOBJTYPES = mobjtype_t.NUMMOBJTYPES.ordinal(); + } diff --git a/src/data/SineCosine.java b/src/data/SineCosine.java index 53a90f29..5e2929a6 100644 --- a/src/data/SineCosine.java +++ b/src/data/SineCosine.java @@ -8,1069 +8,1064 @@ * @author Maes * */ - public class SineCosine { - // MAES: original size was 10240, but includes 5PI/4 periods. - // We can get away with ints on this one because of the small range. - // MAES: WTF? -64 ~ 64K range... so 17-bit accuracy? heh. - + // MAES: original size was 10240, but includes 5PI/4 periods. + // We can get away with ints on this one because of the small range. + // MAES: WTF? -64 ~ 64K range... so 17-bit accuracy? heh. /** * Original size was 10240, but includes 5PI/4 periods. * We can get away with ints on this one because of the small range. * MAES: WTF? -64 ~ 64K range... so 17-bit accuracy? heh. */ - - public static int[] finesine= - { - 25,75,125,175,226,276,326,376, - 427,477,527,578,628,678,728,779, - 829,879,929,980,1030,1080,1130,1181, - 1231,1281,1331,1382,1432,1482,1532,1583, - 1633,1683,1733,1784,1834,1884,1934,1985, - 2035,2085,2135,2186,2236,2286,2336,2387, - 2437,2487,2537,2587,2638,2688,2738,2788, - 2839,2889,2939,2989,3039,3090,3140,3190, - 3240,3291,3341,3391,3441,3491,3541,3592, - 3642,3692,3742,3792,3843,3893,3943,3993, - 4043,4093,4144,4194,4244,4294,4344,4394, - 4445,4495,4545,4595,4645,4695,4745,4796, - 4846,4896,4946,4996,5046,5096,5146,5197, - 5247,5297,5347,5397,5447,5497,5547,5597, - 5647,5697,5748,5798,5848,5898,5948,5998, - 6048,6098,6148,6198,6248,6298,6348,6398, - 6448,6498,6548,6598,6648,6698,6748,6798, - 6848,6898,6948,6998,7048,7098,7148,7198, - 7248,7298,7348,7398,7448,7498,7548,7598, - 7648,7697,7747,7797,7847,7897,7947,7997, - 8047,8097,8147,8196,8246,8296,8346,8396, - 8446,8496,8545,8595,8645,8695,8745,8794, - 8844,8894,8944,8994,9043,9093,9143,9193, - 9243,9292,9342,9392,9442,9491,9541,9591, - 9640,9690,9740,9790,9839,9889,9939,9988, - 10038,10088,10137,10187,10237,10286,10336,10386, - 10435,10485,10534,10584,10634,10683,10733,10782, - 10832,10882,10931,10981,11030,11080,11129,11179, - 11228,11278,11327,11377,11426,11476,11525,11575, - 11624,11674,11723,11773,11822,11872,11921,11970, - 12020,12069,12119,12168,12218,12267,12316,12366, - 12415,12464,12514,12563,12612,12662,12711,12760, - 12810,12859,12908,12957,13007,13056,13105,13154, - 13204,13253,13302,13351,13401,13450,13499,13548, - 13597,13647,13696,13745,13794,13843,13892,13941, - 13990,14040,14089,14138,14187,14236,14285,14334, - 14383,14432,14481,14530,14579,14628,14677,14726, - 14775,14824,14873,14922,14971,15020,15069,15118, - 15167,15215,15264,15313,15362,15411,15460,15509, - 15557,15606,15655,15704,15753,15802,15850,15899, - 15948,15997,16045,16094,16143,16191,16240,16289, - 16338,16386,16435,16484,16532,16581,16629,16678, - 16727,16775,16824,16872,16921,16970,17018,17067, - 17115,17164,17212,17261,17309,17358,17406,17455, - 17503,17551,17600,17648,17697,17745,17793,17842, - 17890,17939,17987,18035,18084,18132,18180,18228, - 18277,18325,18373,18421,18470,18518,18566,18614, - 18663,18711,18759,18807,18855,18903,18951,19000, - 19048,19096,19144,19192,19240,19288,19336,19384, - 19432,19480,19528,19576,19624,19672,19720,19768, - 19816,19864,19912,19959,20007,20055,20103,20151, - 20199,20246,20294,20342,20390,20438,20485,20533, - 20581,20629,20676,20724,20772,20819,20867,20915, - 20962,21010,21057,21105,21153,21200,21248,21295, - 21343,21390,21438,21485,21533,21580,21628,21675, - 21723,21770,21817,21865,21912,21960,22007,22054, - 22102,22149,22196,22243,22291,22338,22385,22433, - 22480,22527,22574,22621,22668,22716,22763,22810, - 22857,22904,22951,22998,23045,23092,23139,23186, - 23233,23280,23327,23374,23421,23468,23515,23562, - 23609,23656,23703,23750,23796,23843,23890,23937, - 23984,24030,24077,24124,24171,24217,24264,24311, - 24357,24404,24451,24497,24544,24591,24637,24684, - 24730,24777,24823,24870,24916,24963,25009,25056, - 25102,25149,25195,25241,25288,25334,25381,25427, - 25473,25520,25566,25612,25658,25705,25751,25797, - 25843,25889,25936,25982,26028,26074,26120,26166, - 26212,26258,26304,26350,26396,26442,26488,26534, - 26580,26626,26672,26718,26764,26810,26856,26902, - 26947,26993,27039,27085,27131,27176,27222,27268, - 27313,27359,27405,27450,27496,27542,27587,27633, - 27678,27724,27770,27815,27861,27906,27952,27997, - 28042,28088,28133,28179,28224,28269,28315,28360, - 28405,28451,28496,28541,28586,28632,28677,28722, - 28767,28812,28858,28903,28948,28993,29038,29083, - 29128,29173,29218,29263,29308,29353,29398,29443, - 29488,29533,29577,29622,29667,29712,29757,29801, - 29846,29891,29936,29980,30025,30070,30114,30159, - 30204,30248,30293,30337,30382,30426,30471,30515, - 30560,30604,30649,30693,30738,30782,30826,30871, - 30915,30959,31004,31048,31092,31136,31181,31225, - 31269,31313,31357,31402,31446,31490,31534,31578, - 31622,31666,31710,31754,31798,31842,31886,31930, - 31974,32017,32061,32105,32149,32193,32236,32280, - 32324,32368,32411,32455,32499,32542,32586,32630, - 32673,32717,32760,32804,32847,32891,32934,32978, - 33021,33065,33108,33151,33195,33238,33281,33325, - 33368,33411,33454,33498,33541,33584,33627,33670, - 33713,33756,33799,33843,33886,33929,33972,34015, - 34057,34100,34143,34186,34229,34272,34315,34358, - 34400,34443,34486,34529,34571,34614,34657,34699, - 34742,34785,34827,34870,34912,34955,34997,35040, - 35082,35125,35167,35210,35252,35294,35337,35379, - 35421,35464,35506,35548,35590,35633,35675,35717, - 35759,35801,35843,35885,35927,35969,36011,36053, - 36095,36137,36179,36221,36263,36305,36347,36388, - 36430,36472,36514,36555,36597,36639,36681,36722, - 36764,36805,36847,36889,36930,36972,37013,37055, - 37096,37137,37179,37220,37262,37303,37344,37386, - 37427,37468,37509,37551,37592,37633,37674,37715, - 37756,37797,37838,37879,37920,37961,38002,38043, - 38084,38125,38166,38207,38248,38288,38329,38370, - 38411,38451,38492,38533,38573,38614,38655,38695, - 38736,38776,38817,38857,38898,38938,38979,39019, - 39059,39100,39140,39180,39221,39261,39301,39341, - 39382,39422,39462,39502,39542,39582,39622,39662, - 39702,39742,39782,39822,39862,39902,39942,39982, - 40021,40061,40101,40141,40180,40220,40260,40300, - 40339,40379,40418,40458,40497,40537,40576,40616, - 40655,40695,40734,40773,40813,40852,40891,40931, - 40970,41009,41048,41087,41127,41166,41205,41244, - 41283,41322,41361,41400,41439,41478,41517,41556, - 41595,41633,41672,41711,41750,41788,41827,41866, - 41904,41943,41982,42020,42059,42097,42136,42174, - 42213,42251,42290,42328,42366,42405,42443,42481, - 42520,42558,42596,42634,42672,42711,42749,42787, - 42825,42863,42901,42939,42977,43015,43053,43091, - 43128,43166,43204,43242,43280,43317,43355,43393, - 43430,43468,43506,43543,43581,43618,43656,43693, - 43731,43768,43806,43843,43880,43918,43955,43992, - 44029,44067,44104,44141,44178,44215,44252,44289, - 44326,44363,44400,44437,44474,44511,44548,44585, - 44622,44659,44695,44732,44769,44806,44842,44879, - 44915,44952,44989,45025,45062,45098,45135,45171, - 45207,45244,45280,45316,45353,45389,45425,45462, - 45498,45534,45570,45606,45642,45678,45714,45750, - 45786,45822,45858,45894,45930,45966,46002,46037, - 46073,46109,46145,46180,46216,46252,46287,46323, - 46358,46394,46429,46465,46500,46536,46571,46606, - 46642,46677,46712,46747,46783,46818,46853,46888, - 46923,46958,46993,47028,47063,47098,47133,47168, - 47203,47238,47273,47308,47342,47377,47412,47446, - 47481,47516,47550,47585,47619,47654,47688,47723, - 47757,47792,47826,47860,47895,47929,47963,47998, - 48032,48066,48100,48134,48168,48202,48237,48271, - 48305,48338,48372,48406,48440,48474,48508,48542, - 48575,48609,48643,48676,48710,48744,48777,48811, - 48844,48878,48911,48945,48978,49012,49045,49078, - 49112,49145,49178,49211,49244,49278,49311,49344, - 49377,49410,49443,49476,49509,49542,49575,49608, - 49640,49673,49706,49739,49771,49804,49837,49869, - 49902,49935,49967,50000,50032,50065,50097,50129, - 50162,50194,50226,50259,50291,50323,50355,50387, - 50420,50452,50484,50516,50548,50580,50612,50644, - 50675,50707,50739,50771,50803,50834,50866,50898, - 50929,50961,50993,51024,51056,51087,51119,51150, - 51182,51213,51244,51276,51307,51338,51369,51401, - 51432,51463,51494,51525,51556,51587,51618,51649, - 51680,51711,51742,51773,51803,51834,51865,51896, - 51926,51957,51988,52018,52049,52079,52110,52140, - 52171,52201,52231,52262,52292,52322,52353,52383, - 52413,52443,52473,52503,52534,52564,52594,52624, - 52653,52683,52713,52743,52773,52803,52832,52862, - 52892,52922,52951,52981,53010,53040,53069,53099, - 53128,53158,53187,53216,53246,53275,53304,53334, - 53363,53392,53421,53450,53479,53508,53537,53566, - 53595,53624,53653,53682,53711,53739,53768,53797, - 53826,53854,53883,53911,53940,53969,53997,54026, - 54054,54082,54111,54139,54167,54196,54224,54252, - 54280,54308,54337,54365,54393,54421,54449,54477, - 54505,54533,54560,54588,54616,54644,54672,54699, - 54727,54755,54782,54810,54837,54865,54892,54920, - 54947,54974,55002,55029,55056,55084,55111,55138, - 55165,55192,55219,55246,55274,55300,55327,55354, - 55381,55408,55435,55462,55489,55515,55542,55569, - 55595,55622,55648,55675,55701,55728,55754,55781, - 55807,55833,55860,55886,55912,55938,55965,55991, - 56017,56043,56069,56095,56121,56147,56173,56199, - 56225,56250,56276,56302,56328,56353,56379,56404, - 56430,56456,56481,56507,56532,56557,56583,56608, - 56633,56659,56684,56709,56734,56760,56785,56810, - 56835,56860,56885,56910,56935,56959,56984,57009, - 57034,57059,57083,57108,57133,57157,57182,57206, - 57231,57255,57280,57304,57329,57353,57377,57402, - 57426,57450,57474,57498,57522,57546,57570,57594, - 57618,57642,57666,57690,57714,57738,57762,57785, - 57809,57833,57856,57880,57903,57927,57950,57974, - 57997,58021,58044,58067,58091,58114,58137,58160, - 58183,58207,58230,58253,58276,58299,58322,58345, - 58367,58390,58413,58436,58459,58481,58504,58527, - 58549,58572,58594,58617,58639,58662,58684,58706, - 58729,58751,58773,58795,58818,58840,58862,58884, - 58906,58928,58950,58972,58994,59016,59038,59059, - 59081,59103,59125,59146,59168,59190,59211,59233, - 59254,59276,59297,59318,59340,59361,59382,59404, - 59425,59446,59467,59488,59509,59530,59551,59572, - 59593,59614,59635,59656,59677,59697,59718,59739, - 59759,59780,59801,59821,59842,59862,59883,59903, - 59923,59944,59964,59984,60004,60025,60045,60065, - 60085,60105,60125,60145,60165,60185,60205,60225, - 60244,60264,60284,60304,60323,60343,60363,60382, - 60402,60421,60441,60460,60479,60499,60518,60537, - 60556,60576,60595,60614,60633,60652,60671,60690, - 60709,60728,60747,60766,60785,60803,60822,60841, - 60859,60878,60897,60915,60934,60952,60971,60989, - 61007,61026,61044,61062,61081,61099,61117,61135, - 61153,61171,61189,61207,61225,61243,61261,61279, - 61297,61314,61332,61350,61367,61385,61403,61420, - 61438,61455,61473,61490,61507,61525,61542,61559, - 61577,61594,61611,61628,61645,61662,61679,61696, - 61713,61730,61747,61764,61780,61797,61814,61831, - 61847,61864,61880,61897,61913,61930,61946,61963, - 61979,61995,62012,62028,62044,62060,62076,62092, - 62108,62125,62141,62156,62172,62188,62204,62220, - 62236,62251,62267,62283,62298,62314,62329,62345, - 62360,62376,62391,62407,62422,62437,62453,62468, - 62483,62498,62513,62528,62543,62558,62573,62588, - 62603,62618,62633,62648,62662,62677,62692,62706, - 62721,62735,62750,62764,62779,62793,62808,62822, - 62836,62850,62865,62879,62893,62907,62921,62935, - 62949,62963,62977,62991,63005,63019,63032,63046, - 63060,63074,63087,63101,63114,63128,63141,63155, - 63168,63182,63195,63208,63221,63235,63248,63261, - 63274,63287,63300,63313,63326,63339,63352,63365, - 63378,63390,63403,63416,63429,63441,63454,63466, - 63479,63491,63504,63516,63528,63541,63553,63565, - 63578,63590,63602,63614,63626,63638,63650,63662, - 63674,63686,63698,63709,63721,63733,63745,63756, - 63768,63779,63791,63803,63814,63825,63837,63848, - 63859,63871,63882,63893,63904,63915,63927,63938, - 63949,63960,63971,63981,63992,64003,64014,64025, - 64035,64046,64057,64067,64078,64088,64099,64109, - 64120,64130,64140,64151,64161,64171,64181,64192, - 64202,64212,64222,64232,64242,64252,64261,64271, - 64281,64291,64301,64310,64320,64330,64339,64349, - 64358,64368,64377,64387,64396,64405,64414,64424, - 64433,64442,64451,64460,64469,64478,64487,64496, - 64505,64514,64523,64532,64540,64549,64558,64566, - 64575,64584,64592,64601,64609,64617,64626,64634, - 64642,64651,64659,64667,64675,64683,64691,64699, - 64707,64715,64723,64731,64739,64747,64754,64762, - 64770,64777,64785,64793,64800,64808,64815,64822, - 64830,64837,64844,64852,64859,64866,64873,64880, - 64887,64895,64902,64908,64915,64922,64929,64936, - 64943,64949,64956,64963,64969,64976,64982,64989, - 64995,65002,65008,65015,65021,65027,65033,65040, - 65046,65052,65058,65064,65070,65076,65082,65088, - 65094,65099,65105,65111,65117,65122,65128,65133, - 65139,65144,65150,65155,65161,65166,65171,65177, - 65182,65187,65192,65197,65202,65207,65212,65217, - 65222,65227,65232,65237,65242,65246,65251,65256, - 65260,65265,65270,65274,65279,65283,65287,65292, - 65296,65300,65305,65309,65313,65317,65321,65325, - 65329,65333,65337,65341,65345,65349,65352,65356, - 65360,65363,65367,65371,65374,65378,65381,65385, - 65388,65391,65395,65398,65401,65404,65408,65411, - 65414,65417,65420,65423,65426,65429,65431,65434, - 65437,65440,65442,65445,65448,65450,65453,65455, - 65458,65460,65463,65465,65467,65470,65472,65474, - 65476,65478,65480,65482,65484,65486,65488,65490, - 65492,65494,65496,65497,65499,65501,65502,65504, - 65505,65507,65508,65510,65511,65513,65514,65515, - 65516,65518,65519,65520,65521,65522,65523,65524, - 65525,65526,65527,65527,65528,65529,65530,65530, - 65531,65531,65532,65532,65533,65533,65534,65534, - 65534,65535,65535,65535,65535,65535,65535,65535, - 65535,65535,65535,65535,65535,65535,65535,65534, - 65534,65534,65533,65533,65532,65532,65531,65531, - 65530,65530,65529,65528,65527,65527,65526,65525, - 65524,65523,65522,65521,65520,65519,65518,65516, - 65515,65514,65513,65511,65510,65508,65507,65505, - 65504,65502,65501,65499,65497,65496,65494,65492, - 65490,65488,65486,65484,65482,65480,65478,65476, - 65474,65472,65470,65467,65465,65463,65460,65458, - 65455,65453,65450,65448,65445,65442,65440,65437, - 65434,65431,65429,65426,65423,65420,65417,65414, - 65411,65408,65404,65401,65398,65395,65391,65388, - 65385,65381,65378,65374,65371,65367,65363,65360, - 65356,65352,65349,65345,65341,65337,65333,65329, - 65325,65321,65317,65313,65309,65305,65300,65296, - 65292,65287,65283,65279,65274,65270,65265,65260, - 65256,65251,65246,65242,65237,65232,65227,65222, - 65217,65212,65207,65202,65197,65192,65187,65182, - 65177,65171,65166,65161,65155,65150,65144,65139, - 65133,65128,65122,65117,65111,65105,65099,65094, - 65088,65082,65076,65070,65064,65058,65052,65046, - 65040,65033,65027,65021,65015,65008,65002,64995, - 64989,64982,64976,64969,64963,64956,64949,64943, - 64936,64929,64922,64915,64908,64902,64895,64887, - 64880,64873,64866,64859,64852,64844,64837,64830, - 64822,64815,64808,64800,64793,64785,64777,64770, - 64762,64754,64747,64739,64731,64723,64715,64707, - 64699,64691,64683,64675,64667,64659,64651,64642, - 64634,64626,64617,64609,64600,64592,64584,64575, - 64566,64558,64549,64540,64532,64523,64514,64505, - 64496,64487,64478,64469,64460,64451,64442,64433, - 64424,64414,64405,64396,64387,64377,64368,64358, - 64349,64339,64330,64320,64310,64301,64291,64281, - 64271,64261,64252,64242,64232,64222,64212,64202, - 64192,64181,64171,64161,64151,64140,64130,64120, - 64109,64099,64088,64078,64067,64057,64046,64035, - 64025,64014,64003,63992,63981,63971,63960,63949, - 63938,63927,63915,63904,63893,63882,63871,63859, - 63848,63837,63825,63814,63803,63791,63779,63768, - 63756,63745,63733,63721,63709,63698,63686,63674, - 63662,63650,63638,63626,63614,63602,63590,63578, - 63565,63553,63541,63528,63516,63504,63491,63479, - 63466,63454,63441,63429,63416,63403,63390,63378, - 63365,63352,63339,63326,63313,63300,63287,63274, - 63261,63248,63235,63221,63208,63195,63182,63168, - 63155,63141,63128,63114,63101,63087,63074,63060, - 63046,63032,63019,63005,62991,62977,62963,62949, - 62935,62921,62907,62893,62879,62865,62850,62836, - 62822,62808,62793,62779,62764,62750,62735,62721, - 62706,62692,62677,62662,62648,62633,62618,62603, - 62588,62573,62558,62543,62528,62513,62498,62483, - 62468,62453,62437,62422,62407,62391,62376,62360, - 62345,62329,62314,62298,62283,62267,62251,62236, - 62220,62204,62188,62172,62156,62141,62125,62108, - 62092,62076,62060,62044,62028,62012,61995,61979, - 61963,61946,61930,61913,61897,61880,61864,61847, - 61831,61814,61797,61780,61764,61747,61730,61713, - 61696,61679,61662,61645,61628,61611,61594,61577, - 61559,61542,61525,61507,61490,61473,61455,61438, - 61420,61403,61385,61367,61350,61332,61314,61297, - 61279,61261,61243,61225,61207,61189,61171,61153, - 61135,61117,61099,61081,61062,61044,61026,61007, - 60989,60971,60952,60934,60915,60897,60878,60859, - 60841,60822,60803,60785,60766,60747,60728,60709, - 60690,60671,60652,60633,60614,60595,60576,60556, - 60537,60518,60499,60479,60460,60441,60421,60402, - 60382,60363,60343,60323,60304,60284,60264,60244, - 60225,60205,60185,60165,60145,60125,60105,60085, - 60065,60045,60025,60004,59984,59964,59944,59923, - 59903,59883,59862,59842,59821,59801,59780,59759, - 59739,59718,59697,59677,59656,59635,59614,59593, - 59572,59551,59530,59509,59488,59467,59446,59425, - 59404,59382,59361,59340,59318,59297,59276,59254, - 59233,59211,59190,59168,59146,59125,59103,59081, - 59059,59038,59016,58994,58972,58950,58928,58906, - 58884,58862,58840,58818,58795,58773,58751,58729, - 58706,58684,58662,58639,58617,58594,58572,58549, - 58527,58504,58481,58459,58436,58413,58390,58367, - 58345,58322,58299,58276,58253,58230,58207,58183, - 58160,58137,58114,58091,58067,58044,58021,57997, - 57974,57950,57927,57903,57880,57856,57833,57809, - 57785,57762,57738,57714,57690,57666,57642,57618, - 57594,57570,57546,57522,57498,57474,57450,57426, - 57402,57377,57353,57329,57304,57280,57255,57231, - 57206,57182,57157,57133,57108,57083,57059,57034, - 57009,56984,56959,56935,56910,56885,56860,56835, - 56810,56785,56760,56734,56709,56684,56659,56633, - 56608,56583,56557,56532,56507,56481,56456,56430, - 56404,56379,56353,56328,56302,56276,56250,56225, - 56199,56173,56147,56121,56095,56069,56043,56017, - 55991,55965,55938,55912,55886,55860,55833,55807, - 55781,55754,55728,55701,55675,55648,55622,55595, - 55569,55542,55515,55489,55462,55435,55408,55381, - 55354,55327,55300,55274,55246,55219,55192,55165, - 55138,55111,55084,55056,55029,55002,54974,54947, - 54920,54892,54865,54837,54810,54782,54755,54727, - 54699,54672,54644,54616,54588,54560,54533,54505, - 54477,54449,54421,54393,54365,54337,54308,54280, - 54252,54224,54196,54167,54139,54111,54082,54054, - 54026,53997,53969,53940,53911,53883,53854,53826, - 53797,53768,53739,53711,53682,53653,53624,53595, - 53566,53537,53508,53479,53450,53421,53392,53363, - 53334,53304,53275,53246,53216,53187,53158,53128, - 53099,53069,53040,53010,52981,52951,52922,52892, - 52862,52832,52803,52773,52743,52713,52683,52653, - 52624,52594,52564,52534,52503,52473,52443,52413, - 52383,52353,52322,52292,52262,52231,52201,52171, - 52140,52110,52079,52049,52018,51988,51957,51926, - 51896,51865,51834,51803,51773,51742,51711,51680, - 51649,51618,51587,51556,51525,51494,51463,51432, - 51401,51369,51338,51307,51276,51244,51213,51182, - 51150,51119,51087,51056,51024,50993,50961,50929, - 50898,50866,50834,50803,50771,50739,50707,50675, - 50644,50612,50580,50548,50516,50484,50452,50420, - 50387,50355,50323,50291,50259,50226,50194,50162, - 50129,50097,50065,50032,50000,49967,49935,49902, - 49869,49837,49804,49771,49739,49706,49673,49640, - 49608,49575,49542,49509,49476,49443,49410,49377, - 49344,49311,49278,49244,49211,49178,49145,49112, - 49078,49045,49012,48978,48945,48911,48878,48844, - 48811,48777,48744,48710,48676,48643,48609,48575, - 48542,48508,48474,48440,48406,48372,48338,48304, - 48271,48237,48202,48168,48134,48100,48066,48032, - 47998,47963,47929,47895,47860,47826,47792,47757, - 47723,47688,47654,47619,47585,47550,47516,47481, - 47446,47412,47377,47342,47308,47273,47238,47203, - 47168,47133,47098,47063,47028,46993,46958,46923, - 46888,46853,46818,46783,46747,46712,46677,46642, - 46606,46571,46536,46500,46465,46429,46394,46358, - 46323,46287,46252,46216,46180,46145,46109,46073, - 46037,46002,45966,45930,45894,45858,45822,45786, - 45750,45714,45678,45642,45606,45570,45534,45498, - 45462,45425,45389,45353,45316,45280,45244,45207, - 45171,45135,45098,45062,45025,44989,44952,44915, - 44879,44842,44806,44769,44732,44695,44659,44622, - 44585,44548,44511,44474,44437,44400,44363,44326, - 44289,44252,44215,44178,44141,44104,44067,44029, - 43992,43955,43918,43880,43843,43806,43768,43731, - 43693,43656,43618,43581,43543,43506,43468,43430, - 43393,43355,43317,43280,43242,43204,43166,43128, - 43091,43053,43015,42977,42939,42901,42863,42825, - 42787,42749,42711,42672,42634,42596,42558,42520, - 42481,42443,42405,42366,42328,42290,42251,42213, - 42174,42136,42097,42059,42020,41982,41943,41904, - 41866,41827,41788,41750,41711,41672,41633,41595, - 41556,41517,41478,41439,41400,41361,41322,41283, - 41244,41205,41166,41127,41088,41048,41009,40970, - 40931,40891,40852,40813,40773,40734,40695,40655, - 40616,40576,40537,40497,40458,40418,40379,40339, - 40300,40260,40220,40180,40141,40101,40061,40021, - 39982,39942,39902,39862,39822,39782,39742,39702, - 39662,39622,39582,39542,39502,39462,39422,39382, - 39341,39301,39261,39221,39180,39140,39100,39059, - 39019,38979,38938,38898,38857,38817,38776,38736, - 38695,38655,38614,38573,38533,38492,38451,38411, - 38370,38329,38288,38248,38207,38166,38125,38084, - 38043,38002,37961,37920,37879,37838,37797,37756, - 37715,37674,37633,37592,37551,37509,37468,37427, - 37386,37344,37303,37262,37220,37179,37137,37096, - 37055,37013,36972,36930,36889,36847,36805,36764, - 36722,36681,36639,36597,36556,36514,36472,36430, - 36388,36347,36305,36263,36221,36179,36137,36095, - 36053,36011,35969,35927,35885,35843,35801,35759, - 35717,35675,35633,35590,35548,35506,35464,35421, - 35379,35337,35294,35252,35210,35167,35125,35082, - 35040,34997,34955,34912,34870,34827,34785,34742, - 34699,34657,34614,34571,34529,34486,34443,34400, - 34358,34315,34272,34229,34186,34143,34100,34057, - 34015,33972,33929,33886,33843,33799,33756,33713, - 33670,33627,33584,33541,33498,33454,33411,33368, - 33325,33281,33238,33195,33151,33108,33065,33021, - 32978,32934,32891,32847,32804,32760,32717,32673, - 32630,32586,32542,32499,32455,32411,32368,32324, - 32280,32236,32193,32149,32105,32061,32017,31974, - 31930,31886,31842,31798,31754,31710,31666,31622, - 31578,31534,31490,31446,31402,31357,31313,31269, - 31225,31181,31136,31092,31048,31004,30959,30915, - 30871,30826,30782,30738,30693,30649,30604,30560, - 30515,30471,30426,30382,30337,30293,30248,30204, - 30159,30114,30070,30025,29980,29936,29891,29846, - 29801,29757,29712,29667,29622,29577,29533,29488, - 29443,29398,29353,29308,29263,29218,29173,29128, - 29083,29038,28993,28948,28903,28858,28812,28767, - 28722,28677,28632,28586,28541,28496,28451,28405, - 28360,28315,28269,28224,28179,28133,28088,28042, - 27997,27952,27906,27861,27815,27770,27724,27678, - 27633,27587,27542,27496,27450,27405,27359,27313, - 27268,27222,27176,27131,27085,27039,26993,26947, - 26902,26856,26810,26764,26718,26672,26626,26580, - 26534,26488,26442,26396,26350,26304,26258,26212, - 26166,26120,26074,26028,25982,25936,25889,25843, - 25797,25751,25705,25658,25612,25566,25520,25473, - 25427,25381,25334,25288,25241,25195,25149,25102, - 25056,25009,24963,24916,24870,24823,24777,24730, - 24684,24637,24591,24544,24497,24451,24404,24357, - 24311,24264,24217,24171,24124,24077,24030,23984, - 23937,23890,23843,23796,23750,23703,23656,23609, - 23562,23515,23468,23421,23374,23327,23280,23233, - 23186,23139,23092,23045,22998,22951,22904,22857, - 22810,22763,22716,22668,22621,22574,22527,22480, - 22433,22385,22338,22291,22243,22196,22149,22102, - 22054,22007,21960,21912,21865,21817,21770,21723, - 21675,21628,21580,21533,21485,21438,21390,21343, - 21295,21248,21200,21153,21105,21057,21010,20962, - 20915,20867,20819,20772,20724,20676,20629,20581, - 20533,20485,20438,20390,20342,20294,20246,20199, - 20151,20103,20055,20007,19959,19912,19864,19816, - 19768,19720,19672,19624,19576,19528,19480,19432, - 19384,19336,19288,19240,19192,19144,19096,19048, - 19000,18951,18903,18855,18807,18759,18711,18663, - 18614,18566,18518,18470,18421,18373,18325,18277, - 18228,18180,18132,18084,18035,17987,17939,17890, - 17842,17793,17745,17697,17648,17600,17551,17503, - 17455,17406,17358,17309,17261,17212,17164,17115, - 17067,17018,16970,16921,16872,16824,16775,16727, - 16678,16629,16581,16532,16484,16435,16386,16338, - 16289,16240,16191,16143,16094,16045,15997,15948, - 15899,15850,15802,15753,15704,15655,15606,15557, - 15509,15460,15411,15362,15313,15264,15215,15167, - 15118,15069,15020,14971,14922,14873,14824,14775, - 14726,14677,14628,14579,14530,14481,14432,14383, - 14334,14285,14236,14187,14138,14089,14040,13990, - 13941,13892,13843,13794,13745,13696,13646,13597, - 13548,13499,13450,13401,13351,13302,13253,13204, - 13154,13105,13056,13007,12957,12908,12859,12810, - 12760,12711,12662,12612,12563,12514,12464,12415, - 12366,12316,12267,12218,12168,12119,12069,12020, - 11970,11921,11872,11822,11773,11723,11674,11624, - 11575,11525,11476,11426,11377,11327,11278,11228, - 11179,11129,11080,11030,10981,10931,10882,10832, - 10782,10733,10683,10634,10584,10534,10485,10435, - 10386,10336,10286,10237,10187,10137,10088,10038, - 9988,9939,9889,9839,9790,9740,9690,9640, - 9591,9541,9491,9442,9392,9342,9292,9243, - 9193,9143,9093,9043,8994,8944,8894,8844, - 8794,8745,8695,8645,8595,8545,8496,8446, - 8396,8346,8296,8246,8196,8147,8097,8047, - 7997,7947,7897,7847,7797,7747,7697,7648, - 7598,7548,7498,7448,7398,7348,7298,7248, - 7198,7148,7098,7048,6998,6948,6898,6848, - 6798,6748,6698,6648,6598,6548,6498,6448, - 6398,6348,6298,6248,6198,6148,6098,6048, - 5998,5948,5898,5848,5798,5748,5697,5647, - 5597,5547,5497,5447,5397,5347,5297,5247, - 5197,5146,5096,5046,4996,4946,4896,4846, - 4796,4745,4695,4645,4595,4545,4495,4445, - 4394,4344,4294,4244,4194,4144,4093,4043, - 3993,3943,3893,3843,3792,3742,3692,3642, - 3592,3541,3491,3441,3391,3341,3291,3240, - 3190,3140,3090,3039,2989,2939,2889,2839, - 2788,2738,2688,2638,2587,2537,2487,2437, - 2387,2336,2286,2236,2186,2135,2085,2035, - 1985,1934,1884,1834,1784,1733,1683,1633, - 1583,1532,1482,1432,1382,1331,1281,1231, - 1181,1130,1080,1030,980,929,879,829, - 779,728,678,628,578,527,477,427, - 376,326,276,226,175,125,75,25, - -25,-75,-125,-175,-226,-276,-326,-376, - -427,-477,-527,-578,-628,-678,-728,-779, - -829,-879,-929,-980,-1030,-1080,-1130,-1181, - -1231,-1281,-1331,-1382,-1432,-1482,-1532,-1583, - -1633,-1683,-1733,-1784,-1834,-1884,-1934,-1985, - -2035,-2085,-2135,-2186,-2236,-2286,-2336,-2387, - -2437,-2487,-2537,-2588,-2638,-2688,-2738,-2788, - -2839,-2889,-2939,-2989,-3039,-3090,-3140,-3190, - -3240,-3291,-3341,-3391,-3441,-3491,-3541,-3592, - -3642,-3692,-3742,-3792,-3843,-3893,-3943,-3993, - -4043,-4093,-4144,-4194,-4244,-4294,-4344,-4394, - -4445,-4495,-4545,-4595,-4645,-4695,-4745,-4796, - -4846,-4896,-4946,-4996,-5046,-5096,-5146,-5197, - -5247,-5297,-5347,-5397,-5447,-5497,-5547,-5597, - -5647,-5697,-5748,-5798,-5848,-5898,-5948,-5998, - -6048,-6098,-6148,-6198,-6248,-6298,-6348,-6398, - -6448,-6498,-6548,-6598,-6648,-6698,-6748,-6798, - -6848,-6898,-6948,-6998,-7048,-7098,-7148,-7198, - -7248,-7298,-7348,-7398,-7448,-7498,-7548,-7598, - -7648,-7697,-7747,-7797,-7847,-7897,-7947,-7997, - -8047,-8097,-8147,-8196,-8246,-8296,-8346,-8396, - -8446,-8496,-8545,-8595,-8645,-8695,-8745,-8794, - -8844,-8894,-8944,-8994,-9043,-9093,-9143,-9193, - -9243,-9292,-9342,-9392,-9442,-9491,-9541,-9591, - -9640,-9690,-9740,-9790,-9839,-9889,-9939,-9988, - -10038,-10088,-10137,-10187,-10237,-10286,-10336,-10386, - -10435,-10485,-10534,-10584,-10634,-10683,-10733,-10782, - -10832,-10882,-10931,-10981,-11030,-11080,-11129,-11179, - -11228,-11278,-11327,-11377,-11426,-11476,-11525,-11575, - -11624,-11674,-11723,-11773,-11822,-11872,-11921,-11970, - -12020,-12069,-12119,-12168,-12218,-12267,-12316,-12366, - -12415,-12464,-12514,-12563,-12612,-12662,-12711,-12760, - -12810,-12859,-12908,-12957,-13007,-13056,-13105,-13154, - -13204,-13253,-13302,-13351,-13401,-13450,-13499,-13548, - -13597,-13647,-13696,-13745,-13794,-13843,-13892,-13941, - -13990,-14040,-14089,-14138,-14187,-14236,-14285,-14334, - -14383,-14432,-14481,-14530,-14579,-14628,-14677,-14726, - -14775,-14824,-14873,-14922,-14971,-15020,-15069,-15118, - -15167,-15215,-15264,-15313,-15362,-15411,-15460,-15509, - -15557,-15606,-15655,-15704,-15753,-15802,-15850,-15899, - -15948,-15997,-16045,-16094,-16143,-16191,-16240,-16289, - -16338,-16386,-16435,-16484,-16532,-16581,-16629,-16678, - -16727,-16775,-16824,-16872,-16921,-16970,-17018,-17067, - -17115,-17164,-17212,-17261,-17309,-17358,-17406,-17455, - -17503,-17551,-17600,-17648,-17697,-17745,-17793,-17842, - -17890,-17939,-17987,-18035,-18084,-18132,-18180,-18228, - -18277,-18325,-18373,-18421,-18470,-18518,-18566,-18614, - -18663,-18711,-18759,-18807,-18855,-18903,-18951,-19000, - -19048,-19096,-19144,-19192,-19240,-19288,-19336,-19384, - -19432,-19480,-19528,-19576,-19624,-19672,-19720,-19768, - -19816,-19864,-19912,-19959,-20007,-20055,-20103,-20151, - -20199,-20246,-20294,-20342,-20390,-20438,-20485,-20533, - -20581,-20629,-20676,-20724,-20772,-20819,-20867,-20915, - -20962,-21010,-21057,-21105,-21153,-21200,-21248,-21295, - -21343,-21390,-21438,-21485,-21533,-21580,-21628,-21675, - -21723,-21770,-21817,-21865,-21912,-21960,-22007,-22054, - -22102,-22149,-22196,-22243,-22291,-22338,-22385,-22433, - -22480,-22527,-22574,-22621,-22668,-22716,-22763,-22810, - -22857,-22904,-22951,-22998,-23045,-23092,-23139,-23186, - -23233,-23280,-23327,-23374,-23421,-23468,-23515,-23562, - -23609,-23656,-23703,-23750,-23796,-23843,-23890,-23937, - -23984,-24030,-24077,-24124,-24171,-24217,-24264,-24311, - -24357,-24404,-24451,-24497,-24544,-24591,-24637,-24684, - -24730,-24777,-24823,-24870,-24916,-24963,-25009,-25056, - -25102,-25149,-25195,-25241,-25288,-25334,-25381,-25427, - -25473,-25520,-25566,-25612,-25658,-25705,-25751,-25797, - -25843,-25889,-25936,-25982,-26028,-26074,-26120,-26166, - -26212,-26258,-26304,-26350,-26396,-26442,-26488,-26534, - -26580,-26626,-26672,-26718,-26764,-26810,-26856,-26902, - -26947,-26993,-27039,-27085,-27131,-27176,-27222,-27268, - -27313,-27359,-27405,-27450,-27496,-27542,-27587,-27633, - -27678,-27724,-27770,-27815,-27861,-27906,-27952,-27997, - -28042,-28088,-28133,-28179,-28224,-28269,-28315,-28360, - -28405,-28451,-28496,-28541,-28586,-28632,-28677,-28722, - -28767,-28812,-28858,-28903,-28948,-28993,-29038,-29083, - -29128,-29173,-29218,-29263,-29308,-29353,-29398,-29443, - -29488,-29533,-29577,-29622,-29667,-29712,-29757,-29801, - -29846,-29891,-29936,-29980,-30025,-30070,-30114,-30159, - -30204,-30248,-30293,-30337,-30382,-30426,-30471,-30515, - -30560,-30604,-30649,-30693,-30738,-30782,-30826,-30871, - -30915,-30959,-31004,-31048,-31092,-31136,-31181,-31225, - -31269,-31313,-31357,-31402,-31446,-31490,-31534,-31578, - -31622,-31666,-31710,-31754,-31798,-31842,-31886,-31930, - -31974,-32017,-32061,-32105,-32149,-32193,-32236,-32280, - -32324,-32368,-32411,-32455,-32499,-32542,-32586,-32630, - -32673,-32717,-32760,-32804,-32847,-32891,-32934,-32978, - -33021,-33065,-33108,-33151,-33195,-33238,-33281,-33325, - -33368,-33411,-33454,-33498,-33541,-33584,-33627,-33670, - -33713,-33756,-33799,-33843,-33886,-33929,-33972,-34015, - -34057,-34100,-34143,-34186,-34229,-34272,-34315,-34358, - -34400,-34443,-34486,-34529,-34571,-34614,-34657,-34699, - -34742,-34785,-34827,-34870,-34912,-34955,-34997,-35040, - -35082,-35125,-35167,-35210,-35252,-35294,-35337,-35379, - -35421,-35464,-35506,-35548,-35590,-35633,-35675,-35717, - -35759,-35801,-35843,-35885,-35927,-35969,-36011,-36053, - -36095,-36137,-36179,-36221,-36263,-36305,-36347,-36388, - -36430,-36472,-36514,-36555,-36597,-36639,-36681,-36722, - -36764,-36805,-36847,-36889,-36930,-36972,-37013,-37055, - -37096,-37137,-37179,-37220,-37262,-37303,-37344,-37386, - -37427,-37468,-37509,-37551,-37592,-37633,-37674,-37715, - -37756,-37797,-37838,-37879,-37920,-37961,-38002,-38043, - -38084,-38125,-38166,-38207,-38248,-38288,-38329,-38370, - -38411,-38451,-38492,-38533,-38573,-38614,-38655,-38695, - -38736,-38776,-38817,-38857,-38898,-38938,-38979,-39019, - -39059,-39100,-39140,-39180,-39221,-39261,-39301,-39341, - -39382,-39422,-39462,-39502,-39542,-39582,-39622,-39662, - -39702,-39742,-39782,-39822,-39862,-39902,-39942,-39982, - -40021,-40061,-40101,-40141,-40180,-40220,-40260,-40299, - -40339,-40379,-40418,-40458,-40497,-40537,-40576,-40616, - -40655,-40695,-40734,-40773,-40813,-40852,-40891,-40931, - -40970,-41009,-41048,-41087,-41127,-41166,-41205,-41244, - -41283,-41322,-41361,-41400,-41439,-41478,-41517,-41556, - -41595,-41633,-41672,-41711,-41750,-41788,-41827,-41866, - -41904,-41943,-41982,-42020,-42059,-42097,-42136,-42174, - -42213,-42251,-42290,-42328,-42366,-42405,-42443,-42481, - -42520,-42558,-42596,-42634,-42672,-42711,-42749,-42787, - -42825,-42863,-42901,-42939,-42977,-43015,-43053,-43091, - -43128,-43166,-43204,-43242,-43280,-43317,-43355,-43393, - -43430,-43468,-43506,-43543,-43581,-43618,-43656,-43693, - -43731,-43768,-43806,-43843,-43880,-43918,-43955,-43992, - -44029,-44067,-44104,-44141,-44178,-44215,-44252,-44289, - -44326,-44363,-44400,-44437,-44474,-44511,-44548,-44585, - -44622,-44659,-44695,-44732,-44769,-44806,-44842,-44879, - -44915,-44952,-44989,-45025,-45062,-45098,-45135,-45171, - -45207,-45244,-45280,-45316,-45353,-45389,-45425,-45462, - -45498,-45534,-45570,-45606,-45642,-45678,-45714,-45750, - -45786,-45822,-45858,-45894,-45930,-45966,-46002,-46037, - -46073,-46109,-46145,-46180,-46216,-46252,-46287,-46323, - -46358,-46394,-46429,-46465,-46500,-46536,-46571,-46606, - -46642,-46677,-46712,-46747,-46783,-46818,-46853,-46888, - -46923,-46958,-46993,-47028,-47063,-47098,-47133,-47168, - -47203,-47238,-47273,-47308,-47342,-47377,-47412,-47446, - -47481,-47516,-47550,-47585,-47619,-47654,-47688,-47723, - -47757,-47792,-47826,-47860,-47895,-47929,-47963,-47998, - -48032,-48066,-48100,-48134,-48168,-48202,-48236,-48271, - -48304,-48338,-48372,-48406,-48440,-48474,-48508,-48542, - -48575,-48609,-48643,-48676,-48710,-48744,-48777,-48811, - -48844,-48878,-48911,-48945,-48978,-49012,-49045,-49078, - -49112,-49145,-49178,-49211,-49244,-49278,-49311,-49344, - -49377,-49410,-49443,-49476,-49509,-49542,-49575,-49608, - -49640,-49673,-49706,-49739,-49771,-49804,-49837,-49869, - -49902,-49935,-49967,-50000,-50032,-50065,-50097,-50129, - -50162,-50194,-50226,-50259,-50291,-50323,-50355,-50387, - -50420,-50452,-50484,-50516,-50548,-50580,-50612,-50644, - -50675,-50707,-50739,-50771,-50803,-50834,-50866,-50898, - -50929,-50961,-50993,-51024,-51056,-51087,-51119,-51150, - -51182,-51213,-51244,-51276,-51307,-51338,-51369,-51401, - -51432,-51463,-51494,-51525,-51556,-51587,-51618,-51649, - -51680,-51711,-51742,-51773,-51803,-51834,-51865,-51896, - -51926,-51957,-51988,-52018,-52049,-52079,-52110,-52140, - -52171,-52201,-52231,-52262,-52292,-52322,-52353,-52383, - -52413,-52443,-52473,-52503,-52534,-52564,-52594,-52624, - -52653,-52683,-52713,-52743,-52773,-52803,-52832,-52862, - -52892,-52922,-52951,-52981,-53010,-53040,-53069,-53099, - -53128,-53158,-53187,-53216,-53246,-53275,-53304,-53334, - -53363,-53392,-53421,-53450,-53479,-53508,-53537,-53566, - -53595,-53624,-53653,-53682,-53711,-53739,-53768,-53797, - -53826,-53854,-53883,-53911,-53940,-53969,-53997,-54026, - -54054,-54082,-54111,-54139,-54167,-54196,-54224,-54252, - -54280,-54308,-54337,-54365,-54393,-54421,-54449,-54477, - -54505,-54533,-54560,-54588,-54616,-54644,-54672,-54699, - -54727,-54755,-54782,-54810,-54837,-54865,-54892,-54920, - -54947,-54974,-55002,-55029,-55056,-55084,-55111,-55138, - -55165,-55192,-55219,-55246,-55274,-55300,-55327,-55354, - -55381,-55408,-55435,-55462,-55489,-55515,-55542,-55569, - -55595,-55622,-55648,-55675,-55701,-55728,-55754,-55781, - -55807,-55833,-55860,-55886,-55912,-55938,-55965,-55991, - -56017,-56043,-56069,-56095,-56121,-56147,-56173,-56199, - -56225,-56250,-56276,-56302,-56328,-56353,-56379,-56404, - -56430,-56456,-56481,-56507,-56532,-56557,-56583,-56608, - -56633,-56659,-56684,-56709,-56734,-56760,-56785,-56810, - -56835,-56860,-56885,-56910,-56935,-56959,-56984,-57009, - -57034,-57059,-57083,-57108,-57133,-57157,-57182,-57206, - -57231,-57255,-57280,-57304,-57329,-57353,-57377,-57402, - -57426,-57450,-57474,-57498,-57522,-57546,-57570,-57594, - -57618,-57642,-57666,-57690,-57714,-57738,-57762,-57785, - -57809,-57833,-57856,-57880,-57903,-57927,-57950,-57974, - -57997,-58021,-58044,-58067,-58091,-58114,-58137,-58160, - -58183,-58207,-58230,-58253,-58276,-58299,-58322,-58345, - -58367,-58390,-58413,-58436,-58459,-58481,-58504,-58527, - -58549,-58572,-58594,-58617,-58639,-58662,-58684,-58706, - -58729,-58751,-58773,-58795,-58818,-58840,-58862,-58884, - -58906,-58928,-58950,-58972,-58994,-59016,-59038,-59059, - -59081,-59103,-59125,-59146,-59168,-59190,-59211,-59233, - -59254,-59276,-59297,-59318,-59340,-59361,-59382,-59404, - -59425,-59446,-59467,-59488,-59509,-59530,-59551,-59572, - -59593,-59614,-59635,-59656,-59677,-59697,-59718,-59739, - -59759,-59780,-59801,-59821,-59842,-59862,-59883,-59903, - -59923,-59944,-59964,-59984,-60004,-60025,-60045,-60065, - -60085,-60105,-60125,-60145,-60165,-60185,-60205,-60225, - -60244,-60264,-60284,-60304,-60323,-60343,-60363,-60382, - -60402,-60421,-60441,-60460,-60479,-60499,-60518,-60537, - -60556,-60576,-60595,-60614,-60633,-60652,-60671,-60690, - -60709,-60728,-60747,-60766,-60785,-60803,-60822,-60841, - -60859,-60878,-60897,-60915,-60934,-60952,-60971,-60989, - -61007,-61026,-61044,-61062,-61081,-61099,-61117,-61135, - -61153,-61171,-61189,-61207,-61225,-61243,-61261,-61279, - -61297,-61314,-61332,-61350,-61367,-61385,-61403,-61420, - -61438,-61455,-61473,-61490,-61507,-61525,-61542,-61559, - -61577,-61594,-61611,-61628,-61645,-61662,-61679,-61696, - -61713,-61730,-61747,-61764,-61780,-61797,-61814,-61831, - -61847,-61864,-61880,-61897,-61913,-61930,-61946,-61963, - -61979,-61995,-62012,-62028,-62044,-62060,-62076,-62092, - -62108,-62125,-62141,-62156,-62172,-62188,-62204,-62220, - -62236,-62251,-62267,-62283,-62298,-62314,-62329,-62345, - -62360,-62376,-62391,-62407,-62422,-62437,-62453,-62468, - -62483,-62498,-62513,-62528,-62543,-62558,-62573,-62588, - -62603,-62618,-62633,-62648,-62662,-62677,-62692,-62706, - -62721,-62735,-62750,-62764,-62779,-62793,-62808,-62822, - -62836,-62850,-62865,-62879,-62893,-62907,-62921,-62935, - -62949,-62963,-62977,-62991,-63005,-63019,-63032,-63046, - -63060,-63074,-63087,-63101,-63114,-63128,-63141,-63155, - -63168,-63182,-63195,-63208,-63221,-63235,-63248,-63261, - -63274,-63287,-63300,-63313,-63326,-63339,-63352,-63365, - -63378,-63390,-63403,-63416,-63429,-63441,-63454,-63466, - -63479,-63491,-63504,-63516,-63528,-63541,-63553,-63565, - -63578,-63590,-63602,-63614,-63626,-63638,-63650,-63662, - -63674,-63686,-63698,-63709,-63721,-63733,-63745,-63756, - -63768,-63779,-63791,-63803,-63814,-63825,-63837,-63848, - -63859,-63871,-63882,-63893,-63904,-63915,-63927,-63938, - -63949,-63960,-63971,-63981,-63992,-64003,-64014,-64025, - -64035,-64046,-64057,-64067,-64078,-64088,-64099,-64109, - -64120,-64130,-64140,-64151,-64161,-64171,-64181,-64192, - -64202,-64212,-64222,-64232,-64242,-64252,-64261,-64271, - -64281,-64291,-64301,-64310,-64320,-64330,-64339,-64349, - -64358,-64368,-64377,-64387,-64396,-64405,-64414,-64424, - -64433,-64442,-64451,-64460,-64469,-64478,-64487,-64496, - -64505,-64514,-64523,-64532,-64540,-64549,-64558,-64566, - -64575,-64584,-64592,-64601,-64609,-64617,-64626,-64634, - -64642,-64651,-64659,-64667,-64675,-64683,-64691,-64699, - -64707,-64715,-64723,-64731,-64739,-64747,-64754,-64762, - -64770,-64777,-64785,-64793,-64800,-64808,-64815,-64822, - -64830,-64837,-64844,-64852,-64859,-64866,-64873,-64880, - -64887,-64895,-64902,-64908,-64915,-64922,-64929,-64936, - -64943,-64949,-64956,-64963,-64969,-64976,-64982,-64989, - -64995,-65002,-65008,-65015,-65021,-65027,-65033,-65040, - -65046,-65052,-65058,-65064,-65070,-65076,-65082,-65088, - -65094,-65099,-65105,-65111,-65117,-65122,-65128,-65133, - -65139,-65144,-65150,-65155,-65161,-65166,-65171,-65177, - -65182,-65187,-65192,-65197,-65202,-65207,-65212,-65217, - -65222,-65227,-65232,-65237,-65242,-65246,-65251,-65256, - -65260,-65265,-65270,-65274,-65279,-65283,-65287,-65292, - -65296,-65300,-65305,-65309,-65313,-65317,-65321,-65325, - -65329,-65333,-65337,-65341,-65345,-65349,-65352,-65356, - -65360,-65363,-65367,-65371,-65374,-65378,-65381,-65385, - -65388,-65391,-65395,-65398,-65401,-65404,-65408,-65411, - -65414,-65417,-65420,-65423,-65426,-65429,-65431,-65434, - -65437,-65440,-65442,-65445,-65448,-65450,-65453,-65455, - -65458,-65460,-65463,-65465,-65467,-65470,-65472,-65474, - -65476,-65478,-65480,-65482,-65484,-65486,-65488,-65490, - -65492,-65494,-65496,-65497,-65499,-65501,-65502,-65504, - -65505,-65507,-65508,-65510,-65511,-65513,-65514,-65515, - -65516,-65518,-65519,-65520,-65521,-65522,-65523,-65524, - -65525,-65526,-65527,-65527,-65528,-65529,-65530,-65530, - -65531,-65531,-65532,-65532,-65533,-65533,-65534,-65534, - -65534,-65535,-65535,-65535,-65535,-65535,-65535,-65535, - -65535,-65535,-65535,-65535,-65535,-65535,-65535,-65534, - -65534,-65534,-65533,-65533,-65532,-65532,-65531,-65531, - -65530,-65530,-65529,-65528,-65527,-65527,-65526,-65525, - -65524,-65523,-65522,-65521,-65520,-65519,-65518,-65516, - -65515,-65514,-65513,-65511,-65510,-65508,-65507,-65505, - -65504,-65502,-65501,-65499,-65497,-65496,-65494,-65492, - -65490,-65488,-65486,-65484,-65482,-65480,-65478,-65476, - -65474,-65472,-65470,-65467,-65465,-65463,-65460,-65458, - -65455,-65453,-65450,-65448,-65445,-65442,-65440,-65437, - -65434,-65431,-65429,-65426,-65423,-65420,-65417,-65414, - -65411,-65408,-65404,-65401,-65398,-65395,-65391,-65388, - -65385,-65381,-65378,-65374,-65371,-65367,-65363,-65360, - -65356,-65352,-65349,-65345,-65341,-65337,-65333,-65329, - -65325,-65321,-65317,-65313,-65309,-65305,-65300,-65296, - -65292,-65287,-65283,-65279,-65274,-65270,-65265,-65260, - -65256,-65251,-65246,-65242,-65237,-65232,-65227,-65222, - -65217,-65212,-65207,-65202,-65197,-65192,-65187,-65182, - -65177,-65171,-65166,-65161,-65155,-65150,-65144,-65139, - -65133,-65128,-65122,-65117,-65111,-65105,-65099,-65094, - -65088,-65082,-65076,-65070,-65064,-65058,-65052,-65046, - -65040,-65033,-65027,-65021,-65015,-65008,-65002,-64995, - -64989,-64982,-64976,-64969,-64963,-64956,-64949,-64943, - -64936,-64929,-64922,-64915,-64908,-64902,-64895,-64887, - -64880,-64873,-64866,-64859,-64852,-64844,-64837,-64830, - -64822,-64815,-64808,-64800,-64793,-64785,-64777,-64770, - -64762,-64754,-64747,-64739,-64731,-64723,-64715,-64707, - -64699,-64691,-64683,-64675,-64667,-64659,-64651,-64642, - -64634,-64626,-64617,-64609,-64601,-64592,-64584,-64575, - -64566,-64558,-64549,-64540,-64532,-64523,-64514,-64505, - -64496,-64487,-64478,-64469,-64460,-64451,-64442,-64433, - -64424,-64414,-64405,-64396,-64387,-64377,-64368,-64358, - -64349,-64339,-64330,-64320,-64310,-64301,-64291,-64281, - -64271,-64261,-64252,-64242,-64232,-64222,-64212,-64202, - -64192,-64181,-64171,-64161,-64151,-64140,-64130,-64120, - -64109,-64099,-64088,-64078,-64067,-64057,-64046,-64035, - -64025,-64014,-64003,-63992,-63981,-63971,-63960,-63949, - -63938,-63927,-63915,-63904,-63893,-63882,-63871,-63859, - -63848,-63837,-63825,-63814,-63803,-63791,-63779,-63768, - -63756,-63745,-63733,-63721,-63709,-63698,-63686,-63674, - -63662,-63650,-63638,-63626,-63614,-63602,-63590,-63578, - -63565,-63553,-63541,-63528,-63516,-63504,-63491,-63479, - -63466,-63454,-63441,-63429,-63416,-63403,-63390,-63378, - -63365,-63352,-63339,-63326,-63313,-63300,-63287,-63274, - -63261,-63248,-63235,-63221,-63208,-63195,-63182,-63168, - -63155,-63141,-63128,-63114,-63101,-63087,-63074,-63060, - -63046,-63032,-63019,-63005,-62991,-62977,-62963,-62949, - -62935,-62921,-62907,-62893,-62879,-62865,-62850,-62836, - -62822,-62808,-62793,-62779,-62764,-62750,-62735,-62721, - -62706,-62692,-62677,-62662,-62648,-62633,-62618,-62603, - -62588,-62573,-62558,-62543,-62528,-62513,-62498,-62483, - -62468,-62453,-62437,-62422,-62407,-62391,-62376,-62360, - -62345,-62329,-62314,-62298,-62283,-62267,-62251,-62236, - -62220,-62204,-62188,-62172,-62156,-62141,-62125,-62108, - -62092,-62076,-62060,-62044,-62028,-62012,-61995,-61979, - -61963,-61946,-61930,-61913,-61897,-61880,-61864,-61847, - -61831,-61814,-61797,-61780,-61764,-61747,-61730,-61713, - -61696,-61679,-61662,-61645,-61628,-61611,-61594,-61577, - -61559,-61542,-61525,-61507,-61490,-61473,-61455,-61438, - -61420,-61403,-61385,-61367,-61350,-61332,-61314,-61297, - -61279,-61261,-61243,-61225,-61207,-61189,-61171,-61153, - -61135,-61117,-61099,-61081,-61062,-61044,-61026,-61007, - -60989,-60971,-60952,-60934,-60915,-60897,-60878,-60859, - -60841,-60822,-60803,-60785,-60766,-60747,-60728,-60709, - -60690,-60671,-60652,-60633,-60614,-60595,-60576,-60556, - -60537,-60518,-60499,-60479,-60460,-60441,-60421,-60402, - -60382,-60363,-60343,-60323,-60304,-60284,-60264,-60244, - -60225,-60205,-60185,-60165,-60145,-60125,-60105,-60085, - -60065,-60045,-60025,-60004,-59984,-59964,-59944,-59923, - -59903,-59883,-59862,-59842,-59821,-59801,-59780,-59759, - -59739,-59718,-59697,-59677,-59656,-59635,-59614,-59593, - -59572,-59551,-59530,-59509,-59488,-59467,-59446,-59425, - -59404,-59382,-59361,-59340,-59318,-59297,-59276,-59254, - -59233,-59211,-59189,-59168,-59146,-59125,-59103,-59081, - -59059,-59038,-59016,-58994,-58972,-58950,-58928,-58906, - -58884,-58862,-58840,-58818,-58795,-58773,-58751,-58729, - -58706,-58684,-58662,-58639,-58617,-58594,-58572,-58549, - -58527,-58504,-58481,-58459,-58436,-58413,-58390,-58367, - -58345,-58322,-58299,-58276,-58253,-58230,-58207,-58183, - -58160,-58137,-58114,-58091,-58067,-58044,-58021,-57997, - -57974,-57950,-57927,-57903,-57880,-57856,-57833,-57809, - -57785,-57762,-57738,-57714,-57690,-57666,-57642,-57618, - -57594,-57570,-57546,-57522,-57498,-57474,-57450,-57426, - -57402,-57377,-57353,-57329,-57304,-57280,-57255,-57231, - -57206,-57182,-57157,-57133,-57108,-57083,-57059,-57034, - -57009,-56984,-56959,-56935,-56910,-56885,-56860,-56835, - -56810,-56785,-56760,-56734,-56709,-56684,-56659,-56633, - -56608,-56583,-56557,-56532,-56507,-56481,-56456,-56430, - -56404,-56379,-56353,-56328,-56302,-56276,-56250,-56225, - -56199,-56173,-56147,-56121,-56095,-56069,-56043,-56017, - -55991,-55965,-55938,-55912,-55886,-55860,-55833,-55807, - -55781,-55754,-55728,-55701,-55675,-55648,-55622,-55595, - -55569,-55542,-55515,-55489,-55462,-55435,-55408,-55381, - -55354,-55327,-55300,-55274,-55246,-55219,-55192,-55165, - -55138,-55111,-55084,-55056,-55029,-55002,-54974,-54947, - -54920,-54892,-54865,-54837,-54810,-54782,-54755,-54727, - -54699,-54672,-54644,-54616,-54588,-54560,-54533,-54505, - -54477,-54449,-54421,-54393,-54365,-54337,-54308,-54280, - -54252,-54224,-54196,-54167,-54139,-54111,-54082,-54054, - -54026,-53997,-53969,-53940,-53911,-53883,-53854,-53826, - -53797,-53768,-53739,-53711,-53682,-53653,-53624,-53595, - -53566,-53537,-53508,-53479,-53450,-53421,-53392,-53363, - -53334,-53304,-53275,-53246,-53216,-53187,-53158,-53128, - -53099,-53069,-53040,-53010,-52981,-52951,-52922,-52892, - -52862,-52832,-52803,-52773,-52743,-52713,-52683,-52653, - -52624,-52594,-52564,-52534,-52503,-52473,-52443,-52413, - -52383,-52353,-52322,-52292,-52262,-52231,-52201,-52171, - -52140,-52110,-52079,-52049,-52018,-51988,-51957,-51926, - -51896,-51865,-51834,-51803,-51773,-51742,-51711,-51680, - -51649,-51618,-51587,-51556,-51525,-51494,-51463,-51432, - -51401,-51369,-51338,-51307,-51276,-51244,-51213,-51182, - -51150,-51119,-51087,-51056,-51024,-50993,-50961,-50929, - -50898,-50866,-50834,-50803,-50771,-50739,-50707,-50675, - -50644,-50612,-50580,-50548,-50516,-50484,-50452,-50420, - -50387,-50355,-50323,-50291,-50259,-50226,-50194,-50162, - -50129,-50097,-50065,-50032,-50000,-49967,-49935,-49902, - -49869,-49837,-49804,-49771,-49739,-49706,-49673,-49640, - -49608,-49575,-49542,-49509,-49476,-49443,-49410,-49377, - -49344,-49311,-49278,-49244,-49211,-49178,-49145,-49112, - -49078,-49045,-49012,-48978,-48945,-48911,-48878,-48844, - -48811,-48777,-48744,-48710,-48676,-48643,-48609,-48575, - -48542,-48508,-48474,-48440,-48406,-48372,-48338,-48305, - -48271,-48237,-48202,-48168,-48134,-48100,-48066,-48032, - -47998,-47963,-47929,-47895,-47860,-47826,-47792,-47757, - -47723,-47688,-47654,-47619,-47585,-47550,-47516,-47481, - -47446,-47412,-47377,-47342,-47307,-47273,-47238,-47203, - -47168,-47133,-47098,-47063,-47028,-46993,-46958,-46923, - -46888,-46853,-46818,-46783,-46747,-46712,-46677,-46642, - -46606,-46571,-46536,-46500,-46465,-46429,-46394,-46358, - -46323,-46287,-46251,-46216,-46180,-46145,-46109,-46073, - -46037,-46002,-45966,-45930,-45894,-45858,-45822,-45786, - -45750,-45714,-45678,-45642,-45606,-45570,-45534,-45498, - -45462,-45425,-45389,-45353,-45316,-45280,-45244,-45207, - -45171,-45135,-45098,-45062,-45025,-44989,-44952,-44915, - -44879,-44842,-44806,-44769,-44732,-44695,-44659,-44622, - -44585,-44548,-44511,-44474,-44437,-44400,-44363,-44326, - -44289,-44252,-44215,-44178,-44141,-44104,-44067,-44029, - -43992,-43955,-43918,-43880,-43843,-43806,-43768,-43731, - -43693,-43656,-43618,-43581,-43543,-43506,-43468,-43430, - -43393,-43355,-43317,-43280,-43242,-43204,-43166,-43128, - -43091,-43053,-43015,-42977,-42939,-42901,-42863,-42825, - -42787,-42749,-42711,-42672,-42634,-42596,-42558,-42520, - -42481,-42443,-42405,-42366,-42328,-42290,-42251,-42213, - -42174,-42136,-42097,-42059,-42020,-41982,-41943,-41904, - -41866,-41827,-41788,-41750,-41711,-41672,-41633,-41595, - -41556,-41517,-41478,-41439,-41400,-41361,-41322,-41283, - -41244,-41205,-41166,-41127,-41087,-41048,-41009,-40970, - -40931,-40891,-40852,-40813,-40773,-40734,-40695,-40655, - -40616,-40576,-40537,-40497,-40458,-40418,-40379,-40339, - -40299,-40260,-40220,-40180,-40141,-40101,-40061,-40021, - -39982,-39942,-39902,-39862,-39822,-39782,-39742,-39702, - -39662,-39622,-39582,-39542,-39502,-39462,-39422,-39382, - -39341,-39301,-39261,-39221,-39180,-39140,-39100,-39059, - -39019,-38979,-38938,-38898,-38857,-38817,-38776,-38736, - -38695,-38655,-38614,-38573,-38533,-38492,-38451,-38411, - -38370,-38329,-38288,-38248,-38207,-38166,-38125,-38084, - -38043,-38002,-37961,-37920,-37879,-37838,-37797,-37756, - -37715,-37674,-37633,-37592,-37550,-37509,-37468,-37427, - -37386,-37344,-37303,-37262,-37220,-37179,-37137,-37096, - -37055,-37013,-36972,-36930,-36889,-36847,-36805,-36764, - -36722,-36681,-36639,-36597,-36556,-36514,-36472,-36430, - -36388,-36347,-36305,-36263,-36221,-36179,-36137,-36095, - -36053,-36011,-35969,-35927,-35885,-35843,-35801,-35759, - -35717,-35675,-35633,-35590,-35548,-35506,-35464,-35421, - -35379,-35337,-35294,-35252,-35210,-35167,-35125,-35082, - -35040,-34997,-34955,-34912,-34870,-34827,-34785,-34742, - -34699,-34657,-34614,-34571,-34529,-34486,-34443,-34400, - -34358,-34315,-34272,-34229,-34186,-34143,-34100,-34057, - -34015,-33972,-33929,-33886,-33843,-33799,-33756,-33713, - -33670,-33627,-33584,-33541,-33498,-33454,-33411,-33368, - -33325,-33281,-33238,-33195,-33151,-33108,-33065,-33021, - -32978,-32934,-32891,-32847,-32804,-32760,-32717,-32673, - -32630,-32586,-32542,-32499,-32455,-32411,-32368,-32324, - -32280,-32236,-32193,-32149,-32105,-32061,-32017,-31974, - -31930,-31886,-31842,-31798,-31754,-31710,-31666,-31622, - -31578,-31534,-31490,-31446,-31402,-31357,-31313,-31269, - -31225,-31181,-31136,-31092,-31048,-31004,-30959,-30915, - -30871,-30826,-30782,-30738,-30693,-30649,-30604,-30560, - -30515,-30471,-30426,-30382,-30337,-30293,-30248,-30204, - -30159,-30114,-30070,-30025,-29980,-29936,-29891,-29846, - -29801,-29757,-29712,-29667,-29622,-29577,-29533,-29488, - -29443,-29398,-29353,-29308,-29263,-29218,-29173,-29128, - -29083,-29038,-28993,-28948,-28903,-28858,-28812,-28767, - -28722,-28677,-28632,-28586,-28541,-28496,-28451,-28405, - -28360,-28315,-28269,-28224,-28179,-28133,-28088,-28042, - -27997,-27952,-27906,-27861,-27815,-27770,-27724,-27678, - -27633,-27587,-27542,-27496,-27450,-27405,-27359,-27313, - -27268,-27222,-27176,-27131,-27085,-27039,-26993,-26947, - -26902,-26856,-26810,-26764,-26718,-26672,-26626,-26580, - -26534,-26488,-26442,-26396,-26350,-26304,-26258,-26212, - -26166,-26120,-26074,-26028,-25982,-25936,-25889,-25843, - -25797,-25751,-25705,-25658,-25612,-25566,-25520,-25473, - -25427,-25381,-25334,-25288,-25241,-25195,-25149,-25102, - -25056,-25009,-24963,-24916,-24870,-24823,-24777,-24730, - -24684,-24637,-24591,-24544,-24497,-24451,-24404,-24357, - -24311,-24264,-24217,-24171,-24124,-24077,-24030,-23984, - -23937,-23890,-23843,-23796,-23750,-23703,-23656,-23609, - -23562,-23515,-23468,-23421,-23374,-23327,-23280,-23233, - -23186,-23139,-23092,-23045,-22998,-22951,-22904,-22857, - -22810,-22763,-22716,-22668,-22621,-22574,-22527,-22480, - -22432,-22385,-22338,-22291,-22243,-22196,-22149,-22102, - -22054,-22007,-21960,-21912,-21865,-21817,-21770,-21723, - -21675,-21628,-21580,-21533,-21485,-21438,-21390,-21343, - -21295,-21248,-21200,-21153,-21105,-21057,-21010,-20962, - -20915,-20867,-20819,-20772,-20724,-20676,-20629,-20581, - -20533,-20485,-20438,-20390,-20342,-20294,-20246,-20199, - -20151,-20103,-20055,-20007,-19959,-19912,-19864,-19816, - -19768,-19720,-19672,-19624,-19576,-19528,-19480,-19432, - -19384,-19336,-19288,-19240,-19192,-19144,-19096,-19048, - -19000,-18951,-18903,-18855,-18807,-18759,-18711,-18663, - -18614,-18566,-18518,-18470,-18421,-18373,-18325,-18277, - -18228,-18180,-18132,-18084,-18035,-17987,-17939,-17890, - -17842,-17793,-17745,-17697,-17648,-17600,-17551,-17503, - -17455,-17406,-17358,-17309,-17261,-17212,-17164,-17115, - -17067,-17018,-16970,-16921,-16872,-16824,-16775,-16727, - -16678,-16629,-16581,-16532,-16484,-16435,-16386,-16338, - -16289,-16240,-16191,-16143,-16094,-16045,-15997,-15948, - -15899,-15850,-15802,-15753,-15704,-15655,-15606,-15557, - -15509,-15460,-15411,-15362,-15313,-15264,-15215,-15167, - -15118,-15069,-15020,-14971,-14922,-14873,-14824,-14775, - -14726,-14677,-14628,-14579,-14530,-14481,-14432,-14383, - -14334,-14285,-14236,-14187,-14138,-14089,-14040,-13990, - -13941,-13892,-13843,-13794,-13745,-13696,-13647,-13597, - -13548,-13499,-13450,-13401,-13351,-13302,-13253,-13204, - -13154,-13105,-13056,-13007,-12957,-12908,-12859,-12810, - -12760,-12711,-12662,-12612,-12563,-12514,-12464,-12415, - -12366,-12316,-12267,-12217,-12168,-12119,-12069,-12020, - -11970,-11921,-11872,-11822,-11773,-11723,-11674,-11624, - -11575,-11525,-11476,-11426,-11377,-11327,-11278,-11228, - -11179,-11129,-11080,-11030,-10981,-10931,-10882,-10832, - -10782,-10733,-10683,-10634,-10584,-10534,-10485,-10435, - -10386,-10336,-10286,-10237,-10187,-10137,-10088,-10038, - -9988,-9939,-9889,-9839,-9790,-9740,-9690,-9640, - -9591,-9541,-9491,-9442,-9392,-9342,-9292,-9243, - -9193,-9143,-9093,-9043,-8994,-8944,-8894,-8844, - -8794,-8745,-8695,-8645,-8595,-8545,-8496,-8446, - -8396,-8346,-8296,-8246,-8196,-8147,-8097,-8047, - -7997,-7947,-7897,-7847,-7797,-7747,-7697,-7648, - -7598,-7548,-7498,-7448,-7398,-7348,-7298,-7248, - -7198,-7148,-7098,-7048,-6998,-6948,-6898,-6848, - -6798,-6748,-6698,-6648,-6598,-6548,-6498,-6448, - -6398,-6348,-6298,-6248,-6198,-6148,-6098,-6048, - -5998,-5948,-5898,-5848,-5798,-5747,-5697,-5647, - -5597,-5547,-5497,-5447,-5397,-5347,-5297,-5247, - -5197,-5146,-5096,-5046,-4996,-4946,-4896,-4846, - -4796,-4745,-4695,-4645,-4595,-4545,-4495,-4445, - -4394,-4344,-4294,-4244,-4194,-4144,-4093,-4043, - -3993,-3943,-3893,-3843,-3792,-3742,-3692,-3642, - -3592,-3541,-3491,-3441,-3391,-3341,-3291,-3240, - -3190,-3140,-3090,-3039,-2989,-2939,-2889,-2839, - -2788,-2738,-2688,-2638,-2588,-2537,-2487,-2437, - -2387,-2336,-2286,-2236,-2186,-2135,-2085,-2035, - -1985,-1934,-1884,-1834,-1784,-1733,-1683,-1633, - -1583,-1532,-1482,-1432,-1382,-1331,-1281,-1231, - -1181,-1130,-1080,-1030,-980,-929,-879,-829, - -779,-728,-678,-628,-578,-527,-477,-427, - -376,-326,-276,-226,-175,-125,-75,-25 - }; - + public static int[] finesine + = { + 25, 75, 125, 175, 226, 276, 326, 376, + 427, 477, 527, 578, 628, 678, 728, 779, + 829, 879, 929, 980, 1030, 1080, 1130, 1181, + 1231, 1281, 1331, 1382, 1432, 1482, 1532, 1583, + 1633, 1683, 1733, 1784, 1834, 1884, 1934, 1985, + 2035, 2085, 2135, 2186, 2236, 2286, 2336, 2387, + 2437, 2487, 2537, 2587, 2638, 2688, 2738, 2788, + 2839, 2889, 2939, 2989, 3039, 3090, 3140, 3190, + 3240, 3291, 3341, 3391, 3441, 3491, 3541, 3592, + 3642, 3692, 3742, 3792, 3843, 3893, 3943, 3993, + 4043, 4093, 4144, 4194, 4244, 4294, 4344, 4394, + 4445, 4495, 4545, 4595, 4645, 4695, 4745, 4796, + 4846, 4896, 4946, 4996, 5046, 5096, 5146, 5197, + 5247, 5297, 5347, 5397, 5447, 5497, 5547, 5597, + 5647, 5697, 5748, 5798, 5848, 5898, 5948, 5998, + 6048, 6098, 6148, 6198, 6248, 6298, 6348, 6398, + 6448, 6498, 6548, 6598, 6648, 6698, 6748, 6798, + 6848, 6898, 6948, 6998, 7048, 7098, 7148, 7198, + 7248, 7298, 7348, 7398, 7448, 7498, 7548, 7598, + 7648, 7697, 7747, 7797, 7847, 7897, 7947, 7997, + 8047, 8097, 8147, 8196, 8246, 8296, 8346, 8396, + 8446, 8496, 8545, 8595, 8645, 8695, 8745, 8794, + 8844, 8894, 8944, 8994, 9043, 9093, 9143, 9193, + 9243, 9292, 9342, 9392, 9442, 9491, 9541, 9591, + 9640, 9690, 9740, 9790, 9839, 9889, 9939, 9988, + 10038, 10088, 10137, 10187, 10237, 10286, 10336, 10386, + 10435, 10485, 10534, 10584, 10634, 10683, 10733, 10782, + 10832, 10882, 10931, 10981, 11030, 11080, 11129, 11179, + 11228, 11278, 11327, 11377, 11426, 11476, 11525, 11575, + 11624, 11674, 11723, 11773, 11822, 11872, 11921, 11970, + 12020, 12069, 12119, 12168, 12218, 12267, 12316, 12366, + 12415, 12464, 12514, 12563, 12612, 12662, 12711, 12760, + 12810, 12859, 12908, 12957, 13007, 13056, 13105, 13154, + 13204, 13253, 13302, 13351, 13401, 13450, 13499, 13548, + 13597, 13647, 13696, 13745, 13794, 13843, 13892, 13941, + 13990, 14040, 14089, 14138, 14187, 14236, 14285, 14334, + 14383, 14432, 14481, 14530, 14579, 14628, 14677, 14726, + 14775, 14824, 14873, 14922, 14971, 15020, 15069, 15118, + 15167, 15215, 15264, 15313, 15362, 15411, 15460, 15509, + 15557, 15606, 15655, 15704, 15753, 15802, 15850, 15899, + 15948, 15997, 16045, 16094, 16143, 16191, 16240, 16289, + 16338, 16386, 16435, 16484, 16532, 16581, 16629, 16678, + 16727, 16775, 16824, 16872, 16921, 16970, 17018, 17067, + 17115, 17164, 17212, 17261, 17309, 17358, 17406, 17455, + 17503, 17551, 17600, 17648, 17697, 17745, 17793, 17842, + 17890, 17939, 17987, 18035, 18084, 18132, 18180, 18228, + 18277, 18325, 18373, 18421, 18470, 18518, 18566, 18614, + 18663, 18711, 18759, 18807, 18855, 18903, 18951, 19000, + 19048, 19096, 19144, 19192, 19240, 19288, 19336, 19384, + 19432, 19480, 19528, 19576, 19624, 19672, 19720, 19768, + 19816, 19864, 19912, 19959, 20007, 20055, 20103, 20151, + 20199, 20246, 20294, 20342, 20390, 20438, 20485, 20533, + 20581, 20629, 20676, 20724, 20772, 20819, 20867, 20915, + 20962, 21010, 21057, 21105, 21153, 21200, 21248, 21295, + 21343, 21390, 21438, 21485, 21533, 21580, 21628, 21675, + 21723, 21770, 21817, 21865, 21912, 21960, 22007, 22054, + 22102, 22149, 22196, 22243, 22291, 22338, 22385, 22433, + 22480, 22527, 22574, 22621, 22668, 22716, 22763, 22810, + 22857, 22904, 22951, 22998, 23045, 23092, 23139, 23186, + 23233, 23280, 23327, 23374, 23421, 23468, 23515, 23562, + 23609, 23656, 23703, 23750, 23796, 23843, 23890, 23937, + 23984, 24030, 24077, 24124, 24171, 24217, 24264, 24311, + 24357, 24404, 24451, 24497, 24544, 24591, 24637, 24684, + 24730, 24777, 24823, 24870, 24916, 24963, 25009, 25056, + 25102, 25149, 25195, 25241, 25288, 25334, 25381, 25427, + 25473, 25520, 25566, 25612, 25658, 25705, 25751, 25797, + 25843, 25889, 25936, 25982, 26028, 26074, 26120, 26166, + 26212, 26258, 26304, 26350, 26396, 26442, 26488, 26534, + 26580, 26626, 26672, 26718, 26764, 26810, 26856, 26902, + 26947, 26993, 27039, 27085, 27131, 27176, 27222, 27268, + 27313, 27359, 27405, 27450, 27496, 27542, 27587, 27633, + 27678, 27724, 27770, 27815, 27861, 27906, 27952, 27997, + 28042, 28088, 28133, 28179, 28224, 28269, 28315, 28360, + 28405, 28451, 28496, 28541, 28586, 28632, 28677, 28722, + 28767, 28812, 28858, 28903, 28948, 28993, 29038, 29083, + 29128, 29173, 29218, 29263, 29308, 29353, 29398, 29443, + 29488, 29533, 29577, 29622, 29667, 29712, 29757, 29801, + 29846, 29891, 29936, 29980, 30025, 30070, 30114, 30159, + 30204, 30248, 30293, 30337, 30382, 30426, 30471, 30515, + 30560, 30604, 30649, 30693, 30738, 30782, 30826, 30871, + 30915, 30959, 31004, 31048, 31092, 31136, 31181, 31225, + 31269, 31313, 31357, 31402, 31446, 31490, 31534, 31578, + 31622, 31666, 31710, 31754, 31798, 31842, 31886, 31930, + 31974, 32017, 32061, 32105, 32149, 32193, 32236, 32280, + 32324, 32368, 32411, 32455, 32499, 32542, 32586, 32630, + 32673, 32717, 32760, 32804, 32847, 32891, 32934, 32978, + 33021, 33065, 33108, 33151, 33195, 33238, 33281, 33325, + 33368, 33411, 33454, 33498, 33541, 33584, 33627, 33670, + 33713, 33756, 33799, 33843, 33886, 33929, 33972, 34015, + 34057, 34100, 34143, 34186, 34229, 34272, 34315, 34358, + 34400, 34443, 34486, 34529, 34571, 34614, 34657, 34699, + 34742, 34785, 34827, 34870, 34912, 34955, 34997, 35040, + 35082, 35125, 35167, 35210, 35252, 35294, 35337, 35379, + 35421, 35464, 35506, 35548, 35590, 35633, 35675, 35717, + 35759, 35801, 35843, 35885, 35927, 35969, 36011, 36053, + 36095, 36137, 36179, 36221, 36263, 36305, 36347, 36388, + 36430, 36472, 36514, 36555, 36597, 36639, 36681, 36722, + 36764, 36805, 36847, 36889, 36930, 36972, 37013, 37055, + 37096, 37137, 37179, 37220, 37262, 37303, 37344, 37386, + 37427, 37468, 37509, 37551, 37592, 37633, 37674, 37715, + 37756, 37797, 37838, 37879, 37920, 37961, 38002, 38043, + 38084, 38125, 38166, 38207, 38248, 38288, 38329, 38370, + 38411, 38451, 38492, 38533, 38573, 38614, 38655, 38695, + 38736, 38776, 38817, 38857, 38898, 38938, 38979, 39019, + 39059, 39100, 39140, 39180, 39221, 39261, 39301, 39341, + 39382, 39422, 39462, 39502, 39542, 39582, 39622, 39662, + 39702, 39742, 39782, 39822, 39862, 39902, 39942, 39982, + 40021, 40061, 40101, 40141, 40180, 40220, 40260, 40300, + 40339, 40379, 40418, 40458, 40497, 40537, 40576, 40616, + 40655, 40695, 40734, 40773, 40813, 40852, 40891, 40931, + 40970, 41009, 41048, 41087, 41127, 41166, 41205, 41244, + 41283, 41322, 41361, 41400, 41439, 41478, 41517, 41556, + 41595, 41633, 41672, 41711, 41750, 41788, 41827, 41866, + 41904, 41943, 41982, 42020, 42059, 42097, 42136, 42174, + 42213, 42251, 42290, 42328, 42366, 42405, 42443, 42481, + 42520, 42558, 42596, 42634, 42672, 42711, 42749, 42787, + 42825, 42863, 42901, 42939, 42977, 43015, 43053, 43091, + 43128, 43166, 43204, 43242, 43280, 43317, 43355, 43393, + 43430, 43468, 43506, 43543, 43581, 43618, 43656, 43693, + 43731, 43768, 43806, 43843, 43880, 43918, 43955, 43992, + 44029, 44067, 44104, 44141, 44178, 44215, 44252, 44289, + 44326, 44363, 44400, 44437, 44474, 44511, 44548, 44585, + 44622, 44659, 44695, 44732, 44769, 44806, 44842, 44879, + 44915, 44952, 44989, 45025, 45062, 45098, 45135, 45171, + 45207, 45244, 45280, 45316, 45353, 45389, 45425, 45462, + 45498, 45534, 45570, 45606, 45642, 45678, 45714, 45750, + 45786, 45822, 45858, 45894, 45930, 45966, 46002, 46037, + 46073, 46109, 46145, 46180, 46216, 46252, 46287, 46323, + 46358, 46394, 46429, 46465, 46500, 46536, 46571, 46606, + 46642, 46677, 46712, 46747, 46783, 46818, 46853, 46888, + 46923, 46958, 46993, 47028, 47063, 47098, 47133, 47168, + 47203, 47238, 47273, 47308, 47342, 47377, 47412, 47446, + 47481, 47516, 47550, 47585, 47619, 47654, 47688, 47723, + 47757, 47792, 47826, 47860, 47895, 47929, 47963, 47998, + 48032, 48066, 48100, 48134, 48168, 48202, 48237, 48271, + 48305, 48338, 48372, 48406, 48440, 48474, 48508, 48542, + 48575, 48609, 48643, 48676, 48710, 48744, 48777, 48811, + 48844, 48878, 48911, 48945, 48978, 49012, 49045, 49078, + 49112, 49145, 49178, 49211, 49244, 49278, 49311, 49344, + 49377, 49410, 49443, 49476, 49509, 49542, 49575, 49608, + 49640, 49673, 49706, 49739, 49771, 49804, 49837, 49869, + 49902, 49935, 49967, 50000, 50032, 50065, 50097, 50129, + 50162, 50194, 50226, 50259, 50291, 50323, 50355, 50387, + 50420, 50452, 50484, 50516, 50548, 50580, 50612, 50644, + 50675, 50707, 50739, 50771, 50803, 50834, 50866, 50898, + 50929, 50961, 50993, 51024, 51056, 51087, 51119, 51150, + 51182, 51213, 51244, 51276, 51307, 51338, 51369, 51401, + 51432, 51463, 51494, 51525, 51556, 51587, 51618, 51649, + 51680, 51711, 51742, 51773, 51803, 51834, 51865, 51896, + 51926, 51957, 51988, 52018, 52049, 52079, 52110, 52140, + 52171, 52201, 52231, 52262, 52292, 52322, 52353, 52383, + 52413, 52443, 52473, 52503, 52534, 52564, 52594, 52624, + 52653, 52683, 52713, 52743, 52773, 52803, 52832, 52862, + 52892, 52922, 52951, 52981, 53010, 53040, 53069, 53099, + 53128, 53158, 53187, 53216, 53246, 53275, 53304, 53334, + 53363, 53392, 53421, 53450, 53479, 53508, 53537, 53566, + 53595, 53624, 53653, 53682, 53711, 53739, 53768, 53797, + 53826, 53854, 53883, 53911, 53940, 53969, 53997, 54026, + 54054, 54082, 54111, 54139, 54167, 54196, 54224, 54252, + 54280, 54308, 54337, 54365, 54393, 54421, 54449, 54477, + 54505, 54533, 54560, 54588, 54616, 54644, 54672, 54699, + 54727, 54755, 54782, 54810, 54837, 54865, 54892, 54920, + 54947, 54974, 55002, 55029, 55056, 55084, 55111, 55138, + 55165, 55192, 55219, 55246, 55274, 55300, 55327, 55354, + 55381, 55408, 55435, 55462, 55489, 55515, 55542, 55569, + 55595, 55622, 55648, 55675, 55701, 55728, 55754, 55781, + 55807, 55833, 55860, 55886, 55912, 55938, 55965, 55991, + 56017, 56043, 56069, 56095, 56121, 56147, 56173, 56199, + 56225, 56250, 56276, 56302, 56328, 56353, 56379, 56404, + 56430, 56456, 56481, 56507, 56532, 56557, 56583, 56608, + 56633, 56659, 56684, 56709, 56734, 56760, 56785, 56810, + 56835, 56860, 56885, 56910, 56935, 56959, 56984, 57009, + 57034, 57059, 57083, 57108, 57133, 57157, 57182, 57206, + 57231, 57255, 57280, 57304, 57329, 57353, 57377, 57402, + 57426, 57450, 57474, 57498, 57522, 57546, 57570, 57594, + 57618, 57642, 57666, 57690, 57714, 57738, 57762, 57785, + 57809, 57833, 57856, 57880, 57903, 57927, 57950, 57974, + 57997, 58021, 58044, 58067, 58091, 58114, 58137, 58160, + 58183, 58207, 58230, 58253, 58276, 58299, 58322, 58345, + 58367, 58390, 58413, 58436, 58459, 58481, 58504, 58527, + 58549, 58572, 58594, 58617, 58639, 58662, 58684, 58706, + 58729, 58751, 58773, 58795, 58818, 58840, 58862, 58884, + 58906, 58928, 58950, 58972, 58994, 59016, 59038, 59059, + 59081, 59103, 59125, 59146, 59168, 59190, 59211, 59233, + 59254, 59276, 59297, 59318, 59340, 59361, 59382, 59404, + 59425, 59446, 59467, 59488, 59509, 59530, 59551, 59572, + 59593, 59614, 59635, 59656, 59677, 59697, 59718, 59739, + 59759, 59780, 59801, 59821, 59842, 59862, 59883, 59903, + 59923, 59944, 59964, 59984, 60004, 60025, 60045, 60065, + 60085, 60105, 60125, 60145, 60165, 60185, 60205, 60225, + 60244, 60264, 60284, 60304, 60323, 60343, 60363, 60382, + 60402, 60421, 60441, 60460, 60479, 60499, 60518, 60537, + 60556, 60576, 60595, 60614, 60633, 60652, 60671, 60690, + 60709, 60728, 60747, 60766, 60785, 60803, 60822, 60841, + 60859, 60878, 60897, 60915, 60934, 60952, 60971, 60989, + 61007, 61026, 61044, 61062, 61081, 61099, 61117, 61135, + 61153, 61171, 61189, 61207, 61225, 61243, 61261, 61279, + 61297, 61314, 61332, 61350, 61367, 61385, 61403, 61420, + 61438, 61455, 61473, 61490, 61507, 61525, 61542, 61559, + 61577, 61594, 61611, 61628, 61645, 61662, 61679, 61696, + 61713, 61730, 61747, 61764, 61780, 61797, 61814, 61831, + 61847, 61864, 61880, 61897, 61913, 61930, 61946, 61963, + 61979, 61995, 62012, 62028, 62044, 62060, 62076, 62092, + 62108, 62125, 62141, 62156, 62172, 62188, 62204, 62220, + 62236, 62251, 62267, 62283, 62298, 62314, 62329, 62345, + 62360, 62376, 62391, 62407, 62422, 62437, 62453, 62468, + 62483, 62498, 62513, 62528, 62543, 62558, 62573, 62588, + 62603, 62618, 62633, 62648, 62662, 62677, 62692, 62706, + 62721, 62735, 62750, 62764, 62779, 62793, 62808, 62822, + 62836, 62850, 62865, 62879, 62893, 62907, 62921, 62935, + 62949, 62963, 62977, 62991, 63005, 63019, 63032, 63046, + 63060, 63074, 63087, 63101, 63114, 63128, 63141, 63155, + 63168, 63182, 63195, 63208, 63221, 63235, 63248, 63261, + 63274, 63287, 63300, 63313, 63326, 63339, 63352, 63365, + 63378, 63390, 63403, 63416, 63429, 63441, 63454, 63466, + 63479, 63491, 63504, 63516, 63528, 63541, 63553, 63565, + 63578, 63590, 63602, 63614, 63626, 63638, 63650, 63662, + 63674, 63686, 63698, 63709, 63721, 63733, 63745, 63756, + 63768, 63779, 63791, 63803, 63814, 63825, 63837, 63848, + 63859, 63871, 63882, 63893, 63904, 63915, 63927, 63938, + 63949, 63960, 63971, 63981, 63992, 64003, 64014, 64025, + 64035, 64046, 64057, 64067, 64078, 64088, 64099, 64109, + 64120, 64130, 64140, 64151, 64161, 64171, 64181, 64192, + 64202, 64212, 64222, 64232, 64242, 64252, 64261, 64271, + 64281, 64291, 64301, 64310, 64320, 64330, 64339, 64349, + 64358, 64368, 64377, 64387, 64396, 64405, 64414, 64424, + 64433, 64442, 64451, 64460, 64469, 64478, 64487, 64496, + 64505, 64514, 64523, 64532, 64540, 64549, 64558, 64566, + 64575, 64584, 64592, 64601, 64609, 64617, 64626, 64634, + 64642, 64651, 64659, 64667, 64675, 64683, 64691, 64699, + 64707, 64715, 64723, 64731, 64739, 64747, 64754, 64762, + 64770, 64777, 64785, 64793, 64800, 64808, 64815, 64822, + 64830, 64837, 64844, 64852, 64859, 64866, 64873, 64880, + 64887, 64895, 64902, 64908, 64915, 64922, 64929, 64936, + 64943, 64949, 64956, 64963, 64969, 64976, 64982, 64989, + 64995, 65002, 65008, 65015, 65021, 65027, 65033, 65040, + 65046, 65052, 65058, 65064, 65070, 65076, 65082, 65088, + 65094, 65099, 65105, 65111, 65117, 65122, 65128, 65133, + 65139, 65144, 65150, 65155, 65161, 65166, 65171, 65177, + 65182, 65187, 65192, 65197, 65202, 65207, 65212, 65217, + 65222, 65227, 65232, 65237, 65242, 65246, 65251, 65256, + 65260, 65265, 65270, 65274, 65279, 65283, 65287, 65292, + 65296, 65300, 65305, 65309, 65313, 65317, 65321, 65325, + 65329, 65333, 65337, 65341, 65345, 65349, 65352, 65356, + 65360, 65363, 65367, 65371, 65374, 65378, 65381, 65385, + 65388, 65391, 65395, 65398, 65401, 65404, 65408, 65411, + 65414, 65417, 65420, 65423, 65426, 65429, 65431, 65434, + 65437, 65440, 65442, 65445, 65448, 65450, 65453, 65455, + 65458, 65460, 65463, 65465, 65467, 65470, 65472, 65474, + 65476, 65478, 65480, 65482, 65484, 65486, 65488, 65490, + 65492, 65494, 65496, 65497, 65499, 65501, 65502, 65504, + 65505, 65507, 65508, 65510, 65511, 65513, 65514, 65515, + 65516, 65518, 65519, 65520, 65521, 65522, 65523, 65524, + 65525, 65526, 65527, 65527, 65528, 65529, 65530, 65530, + 65531, 65531, 65532, 65532, 65533, 65533, 65534, 65534, + 65534, 65535, 65535, 65535, 65535, 65535, 65535, 65535, + 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65534, + 65534, 65534, 65533, 65533, 65532, 65532, 65531, 65531, + 65530, 65530, 65529, 65528, 65527, 65527, 65526, 65525, + 65524, 65523, 65522, 65521, 65520, 65519, 65518, 65516, + 65515, 65514, 65513, 65511, 65510, 65508, 65507, 65505, + 65504, 65502, 65501, 65499, 65497, 65496, 65494, 65492, + 65490, 65488, 65486, 65484, 65482, 65480, 65478, 65476, + 65474, 65472, 65470, 65467, 65465, 65463, 65460, 65458, + 65455, 65453, 65450, 65448, 65445, 65442, 65440, 65437, + 65434, 65431, 65429, 65426, 65423, 65420, 65417, 65414, + 65411, 65408, 65404, 65401, 65398, 65395, 65391, 65388, + 65385, 65381, 65378, 65374, 65371, 65367, 65363, 65360, + 65356, 65352, 65349, 65345, 65341, 65337, 65333, 65329, + 65325, 65321, 65317, 65313, 65309, 65305, 65300, 65296, + 65292, 65287, 65283, 65279, 65274, 65270, 65265, 65260, + 65256, 65251, 65246, 65242, 65237, 65232, 65227, 65222, + 65217, 65212, 65207, 65202, 65197, 65192, 65187, 65182, + 65177, 65171, 65166, 65161, 65155, 65150, 65144, 65139, + 65133, 65128, 65122, 65117, 65111, 65105, 65099, 65094, + 65088, 65082, 65076, 65070, 65064, 65058, 65052, 65046, + 65040, 65033, 65027, 65021, 65015, 65008, 65002, 64995, + 64989, 64982, 64976, 64969, 64963, 64956, 64949, 64943, + 64936, 64929, 64922, 64915, 64908, 64902, 64895, 64887, + 64880, 64873, 64866, 64859, 64852, 64844, 64837, 64830, + 64822, 64815, 64808, 64800, 64793, 64785, 64777, 64770, + 64762, 64754, 64747, 64739, 64731, 64723, 64715, 64707, + 64699, 64691, 64683, 64675, 64667, 64659, 64651, 64642, + 64634, 64626, 64617, 64609, 64600, 64592, 64584, 64575, + 64566, 64558, 64549, 64540, 64532, 64523, 64514, 64505, + 64496, 64487, 64478, 64469, 64460, 64451, 64442, 64433, + 64424, 64414, 64405, 64396, 64387, 64377, 64368, 64358, + 64349, 64339, 64330, 64320, 64310, 64301, 64291, 64281, + 64271, 64261, 64252, 64242, 64232, 64222, 64212, 64202, + 64192, 64181, 64171, 64161, 64151, 64140, 64130, 64120, + 64109, 64099, 64088, 64078, 64067, 64057, 64046, 64035, + 64025, 64014, 64003, 63992, 63981, 63971, 63960, 63949, + 63938, 63927, 63915, 63904, 63893, 63882, 63871, 63859, + 63848, 63837, 63825, 63814, 63803, 63791, 63779, 63768, + 63756, 63745, 63733, 63721, 63709, 63698, 63686, 63674, + 63662, 63650, 63638, 63626, 63614, 63602, 63590, 63578, + 63565, 63553, 63541, 63528, 63516, 63504, 63491, 63479, + 63466, 63454, 63441, 63429, 63416, 63403, 63390, 63378, + 63365, 63352, 63339, 63326, 63313, 63300, 63287, 63274, + 63261, 63248, 63235, 63221, 63208, 63195, 63182, 63168, + 63155, 63141, 63128, 63114, 63101, 63087, 63074, 63060, + 63046, 63032, 63019, 63005, 62991, 62977, 62963, 62949, + 62935, 62921, 62907, 62893, 62879, 62865, 62850, 62836, + 62822, 62808, 62793, 62779, 62764, 62750, 62735, 62721, + 62706, 62692, 62677, 62662, 62648, 62633, 62618, 62603, + 62588, 62573, 62558, 62543, 62528, 62513, 62498, 62483, + 62468, 62453, 62437, 62422, 62407, 62391, 62376, 62360, + 62345, 62329, 62314, 62298, 62283, 62267, 62251, 62236, + 62220, 62204, 62188, 62172, 62156, 62141, 62125, 62108, + 62092, 62076, 62060, 62044, 62028, 62012, 61995, 61979, + 61963, 61946, 61930, 61913, 61897, 61880, 61864, 61847, + 61831, 61814, 61797, 61780, 61764, 61747, 61730, 61713, + 61696, 61679, 61662, 61645, 61628, 61611, 61594, 61577, + 61559, 61542, 61525, 61507, 61490, 61473, 61455, 61438, + 61420, 61403, 61385, 61367, 61350, 61332, 61314, 61297, + 61279, 61261, 61243, 61225, 61207, 61189, 61171, 61153, + 61135, 61117, 61099, 61081, 61062, 61044, 61026, 61007, + 60989, 60971, 60952, 60934, 60915, 60897, 60878, 60859, + 60841, 60822, 60803, 60785, 60766, 60747, 60728, 60709, + 60690, 60671, 60652, 60633, 60614, 60595, 60576, 60556, + 60537, 60518, 60499, 60479, 60460, 60441, 60421, 60402, + 60382, 60363, 60343, 60323, 60304, 60284, 60264, 60244, + 60225, 60205, 60185, 60165, 60145, 60125, 60105, 60085, + 60065, 60045, 60025, 60004, 59984, 59964, 59944, 59923, + 59903, 59883, 59862, 59842, 59821, 59801, 59780, 59759, + 59739, 59718, 59697, 59677, 59656, 59635, 59614, 59593, + 59572, 59551, 59530, 59509, 59488, 59467, 59446, 59425, + 59404, 59382, 59361, 59340, 59318, 59297, 59276, 59254, + 59233, 59211, 59190, 59168, 59146, 59125, 59103, 59081, + 59059, 59038, 59016, 58994, 58972, 58950, 58928, 58906, + 58884, 58862, 58840, 58818, 58795, 58773, 58751, 58729, + 58706, 58684, 58662, 58639, 58617, 58594, 58572, 58549, + 58527, 58504, 58481, 58459, 58436, 58413, 58390, 58367, + 58345, 58322, 58299, 58276, 58253, 58230, 58207, 58183, + 58160, 58137, 58114, 58091, 58067, 58044, 58021, 57997, + 57974, 57950, 57927, 57903, 57880, 57856, 57833, 57809, + 57785, 57762, 57738, 57714, 57690, 57666, 57642, 57618, + 57594, 57570, 57546, 57522, 57498, 57474, 57450, 57426, + 57402, 57377, 57353, 57329, 57304, 57280, 57255, 57231, + 57206, 57182, 57157, 57133, 57108, 57083, 57059, 57034, + 57009, 56984, 56959, 56935, 56910, 56885, 56860, 56835, + 56810, 56785, 56760, 56734, 56709, 56684, 56659, 56633, + 56608, 56583, 56557, 56532, 56507, 56481, 56456, 56430, + 56404, 56379, 56353, 56328, 56302, 56276, 56250, 56225, + 56199, 56173, 56147, 56121, 56095, 56069, 56043, 56017, + 55991, 55965, 55938, 55912, 55886, 55860, 55833, 55807, + 55781, 55754, 55728, 55701, 55675, 55648, 55622, 55595, + 55569, 55542, 55515, 55489, 55462, 55435, 55408, 55381, + 55354, 55327, 55300, 55274, 55246, 55219, 55192, 55165, + 55138, 55111, 55084, 55056, 55029, 55002, 54974, 54947, + 54920, 54892, 54865, 54837, 54810, 54782, 54755, 54727, + 54699, 54672, 54644, 54616, 54588, 54560, 54533, 54505, + 54477, 54449, 54421, 54393, 54365, 54337, 54308, 54280, + 54252, 54224, 54196, 54167, 54139, 54111, 54082, 54054, + 54026, 53997, 53969, 53940, 53911, 53883, 53854, 53826, + 53797, 53768, 53739, 53711, 53682, 53653, 53624, 53595, + 53566, 53537, 53508, 53479, 53450, 53421, 53392, 53363, + 53334, 53304, 53275, 53246, 53216, 53187, 53158, 53128, + 53099, 53069, 53040, 53010, 52981, 52951, 52922, 52892, + 52862, 52832, 52803, 52773, 52743, 52713, 52683, 52653, + 52624, 52594, 52564, 52534, 52503, 52473, 52443, 52413, + 52383, 52353, 52322, 52292, 52262, 52231, 52201, 52171, + 52140, 52110, 52079, 52049, 52018, 51988, 51957, 51926, + 51896, 51865, 51834, 51803, 51773, 51742, 51711, 51680, + 51649, 51618, 51587, 51556, 51525, 51494, 51463, 51432, + 51401, 51369, 51338, 51307, 51276, 51244, 51213, 51182, + 51150, 51119, 51087, 51056, 51024, 50993, 50961, 50929, + 50898, 50866, 50834, 50803, 50771, 50739, 50707, 50675, + 50644, 50612, 50580, 50548, 50516, 50484, 50452, 50420, + 50387, 50355, 50323, 50291, 50259, 50226, 50194, 50162, + 50129, 50097, 50065, 50032, 50000, 49967, 49935, 49902, + 49869, 49837, 49804, 49771, 49739, 49706, 49673, 49640, + 49608, 49575, 49542, 49509, 49476, 49443, 49410, 49377, + 49344, 49311, 49278, 49244, 49211, 49178, 49145, 49112, + 49078, 49045, 49012, 48978, 48945, 48911, 48878, 48844, + 48811, 48777, 48744, 48710, 48676, 48643, 48609, 48575, + 48542, 48508, 48474, 48440, 48406, 48372, 48338, 48304, + 48271, 48237, 48202, 48168, 48134, 48100, 48066, 48032, + 47998, 47963, 47929, 47895, 47860, 47826, 47792, 47757, + 47723, 47688, 47654, 47619, 47585, 47550, 47516, 47481, + 47446, 47412, 47377, 47342, 47308, 47273, 47238, 47203, + 47168, 47133, 47098, 47063, 47028, 46993, 46958, 46923, + 46888, 46853, 46818, 46783, 46747, 46712, 46677, 46642, + 46606, 46571, 46536, 46500, 46465, 46429, 46394, 46358, + 46323, 46287, 46252, 46216, 46180, 46145, 46109, 46073, + 46037, 46002, 45966, 45930, 45894, 45858, 45822, 45786, + 45750, 45714, 45678, 45642, 45606, 45570, 45534, 45498, + 45462, 45425, 45389, 45353, 45316, 45280, 45244, 45207, + 45171, 45135, 45098, 45062, 45025, 44989, 44952, 44915, + 44879, 44842, 44806, 44769, 44732, 44695, 44659, 44622, + 44585, 44548, 44511, 44474, 44437, 44400, 44363, 44326, + 44289, 44252, 44215, 44178, 44141, 44104, 44067, 44029, + 43992, 43955, 43918, 43880, 43843, 43806, 43768, 43731, + 43693, 43656, 43618, 43581, 43543, 43506, 43468, 43430, + 43393, 43355, 43317, 43280, 43242, 43204, 43166, 43128, + 43091, 43053, 43015, 42977, 42939, 42901, 42863, 42825, + 42787, 42749, 42711, 42672, 42634, 42596, 42558, 42520, + 42481, 42443, 42405, 42366, 42328, 42290, 42251, 42213, + 42174, 42136, 42097, 42059, 42020, 41982, 41943, 41904, + 41866, 41827, 41788, 41750, 41711, 41672, 41633, 41595, + 41556, 41517, 41478, 41439, 41400, 41361, 41322, 41283, + 41244, 41205, 41166, 41127, 41088, 41048, 41009, 40970, + 40931, 40891, 40852, 40813, 40773, 40734, 40695, 40655, + 40616, 40576, 40537, 40497, 40458, 40418, 40379, 40339, + 40300, 40260, 40220, 40180, 40141, 40101, 40061, 40021, + 39982, 39942, 39902, 39862, 39822, 39782, 39742, 39702, + 39662, 39622, 39582, 39542, 39502, 39462, 39422, 39382, + 39341, 39301, 39261, 39221, 39180, 39140, 39100, 39059, + 39019, 38979, 38938, 38898, 38857, 38817, 38776, 38736, + 38695, 38655, 38614, 38573, 38533, 38492, 38451, 38411, + 38370, 38329, 38288, 38248, 38207, 38166, 38125, 38084, + 38043, 38002, 37961, 37920, 37879, 37838, 37797, 37756, + 37715, 37674, 37633, 37592, 37551, 37509, 37468, 37427, + 37386, 37344, 37303, 37262, 37220, 37179, 37137, 37096, + 37055, 37013, 36972, 36930, 36889, 36847, 36805, 36764, + 36722, 36681, 36639, 36597, 36556, 36514, 36472, 36430, + 36388, 36347, 36305, 36263, 36221, 36179, 36137, 36095, + 36053, 36011, 35969, 35927, 35885, 35843, 35801, 35759, + 35717, 35675, 35633, 35590, 35548, 35506, 35464, 35421, + 35379, 35337, 35294, 35252, 35210, 35167, 35125, 35082, + 35040, 34997, 34955, 34912, 34870, 34827, 34785, 34742, + 34699, 34657, 34614, 34571, 34529, 34486, 34443, 34400, + 34358, 34315, 34272, 34229, 34186, 34143, 34100, 34057, + 34015, 33972, 33929, 33886, 33843, 33799, 33756, 33713, + 33670, 33627, 33584, 33541, 33498, 33454, 33411, 33368, + 33325, 33281, 33238, 33195, 33151, 33108, 33065, 33021, + 32978, 32934, 32891, 32847, 32804, 32760, 32717, 32673, + 32630, 32586, 32542, 32499, 32455, 32411, 32368, 32324, + 32280, 32236, 32193, 32149, 32105, 32061, 32017, 31974, + 31930, 31886, 31842, 31798, 31754, 31710, 31666, 31622, + 31578, 31534, 31490, 31446, 31402, 31357, 31313, 31269, + 31225, 31181, 31136, 31092, 31048, 31004, 30959, 30915, + 30871, 30826, 30782, 30738, 30693, 30649, 30604, 30560, + 30515, 30471, 30426, 30382, 30337, 30293, 30248, 30204, + 30159, 30114, 30070, 30025, 29980, 29936, 29891, 29846, + 29801, 29757, 29712, 29667, 29622, 29577, 29533, 29488, + 29443, 29398, 29353, 29308, 29263, 29218, 29173, 29128, + 29083, 29038, 28993, 28948, 28903, 28858, 28812, 28767, + 28722, 28677, 28632, 28586, 28541, 28496, 28451, 28405, + 28360, 28315, 28269, 28224, 28179, 28133, 28088, 28042, + 27997, 27952, 27906, 27861, 27815, 27770, 27724, 27678, + 27633, 27587, 27542, 27496, 27450, 27405, 27359, 27313, + 27268, 27222, 27176, 27131, 27085, 27039, 26993, 26947, + 26902, 26856, 26810, 26764, 26718, 26672, 26626, 26580, + 26534, 26488, 26442, 26396, 26350, 26304, 26258, 26212, + 26166, 26120, 26074, 26028, 25982, 25936, 25889, 25843, + 25797, 25751, 25705, 25658, 25612, 25566, 25520, 25473, + 25427, 25381, 25334, 25288, 25241, 25195, 25149, 25102, + 25056, 25009, 24963, 24916, 24870, 24823, 24777, 24730, + 24684, 24637, 24591, 24544, 24497, 24451, 24404, 24357, + 24311, 24264, 24217, 24171, 24124, 24077, 24030, 23984, + 23937, 23890, 23843, 23796, 23750, 23703, 23656, 23609, + 23562, 23515, 23468, 23421, 23374, 23327, 23280, 23233, + 23186, 23139, 23092, 23045, 22998, 22951, 22904, 22857, + 22810, 22763, 22716, 22668, 22621, 22574, 22527, 22480, + 22433, 22385, 22338, 22291, 22243, 22196, 22149, 22102, + 22054, 22007, 21960, 21912, 21865, 21817, 21770, 21723, + 21675, 21628, 21580, 21533, 21485, 21438, 21390, 21343, + 21295, 21248, 21200, 21153, 21105, 21057, 21010, 20962, + 20915, 20867, 20819, 20772, 20724, 20676, 20629, 20581, + 20533, 20485, 20438, 20390, 20342, 20294, 20246, 20199, + 20151, 20103, 20055, 20007, 19959, 19912, 19864, 19816, + 19768, 19720, 19672, 19624, 19576, 19528, 19480, 19432, + 19384, 19336, 19288, 19240, 19192, 19144, 19096, 19048, + 19000, 18951, 18903, 18855, 18807, 18759, 18711, 18663, + 18614, 18566, 18518, 18470, 18421, 18373, 18325, 18277, + 18228, 18180, 18132, 18084, 18035, 17987, 17939, 17890, + 17842, 17793, 17745, 17697, 17648, 17600, 17551, 17503, + 17455, 17406, 17358, 17309, 17261, 17212, 17164, 17115, + 17067, 17018, 16970, 16921, 16872, 16824, 16775, 16727, + 16678, 16629, 16581, 16532, 16484, 16435, 16386, 16338, + 16289, 16240, 16191, 16143, 16094, 16045, 15997, 15948, + 15899, 15850, 15802, 15753, 15704, 15655, 15606, 15557, + 15509, 15460, 15411, 15362, 15313, 15264, 15215, 15167, + 15118, 15069, 15020, 14971, 14922, 14873, 14824, 14775, + 14726, 14677, 14628, 14579, 14530, 14481, 14432, 14383, + 14334, 14285, 14236, 14187, 14138, 14089, 14040, 13990, + 13941, 13892, 13843, 13794, 13745, 13696, 13646, 13597, + 13548, 13499, 13450, 13401, 13351, 13302, 13253, 13204, + 13154, 13105, 13056, 13007, 12957, 12908, 12859, 12810, + 12760, 12711, 12662, 12612, 12563, 12514, 12464, 12415, + 12366, 12316, 12267, 12218, 12168, 12119, 12069, 12020, + 11970, 11921, 11872, 11822, 11773, 11723, 11674, 11624, + 11575, 11525, 11476, 11426, 11377, 11327, 11278, 11228, + 11179, 11129, 11080, 11030, 10981, 10931, 10882, 10832, + 10782, 10733, 10683, 10634, 10584, 10534, 10485, 10435, + 10386, 10336, 10286, 10237, 10187, 10137, 10088, 10038, + 9988, 9939, 9889, 9839, 9790, 9740, 9690, 9640, + 9591, 9541, 9491, 9442, 9392, 9342, 9292, 9243, + 9193, 9143, 9093, 9043, 8994, 8944, 8894, 8844, + 8794, 8745, 8695, 8645, 8595, 8545, 8496, 8446, + 8396, 8346, 8296, 8246, 8196, 8147, 8097, 8047, + 7997, 7947, 7897, 7847, 7797, 7747, 7697, 7648, + 7598, 7548, 7498, 7448, 7398, 7348, 7298, 7248, + 7198, 7148, 7098, 7048, 6998, 6948, 6898, 6848, + 6798, 6748, 6698, 6648, 6598, 6548, 6498, 6448, + 6398, 6348, 6298, 6248, 6198, 6148, 6098, 6048, + 5998, 5948, 5898, 5848, 5798, 5748, 5697, 5647, + 5597, 5547, 5497, 5447, 5397, 5347, 5297, 5247, + 5197, 5146, 5096, 5046, 4996, 4946, 4896, 4846, + 4796, 4745, 4695, 4645, 4595, 4545, 4495, 4445, + 4394, 4344, 4294, 4244, 4194, 4144, 4093, 4043, + 3993, 3943, 3893, 3843, 3792, 3742, 3692, 3642, + 3592, 3541, 3491, 3441, 3391, 3341, 3291, 3240, + 3190, 3140, 3090, 3039, 2989, 2939, 2889, 2839, + 2788, 2738, 2688, 2638, 2587, 2537, 2487, 2437, + 2387, 2336, 2286, 2236, 2186, 2135, 2085, 2035, + 1985, 1934, 1884, 1834, 1784, 1733, 1683, 1633, + 1583, 1532, 1482, 1432, 1382, 1331, 1281, 1231, + 1181, 1130, 1080, 1030, 980, 929, 879, 829, + 779, 728, 678, 628, 578, 527, 477, 427, + 376, 326, 276, 226, 175, 125, 75, 25, + -25, -75, -125, -175, -226, -276, -326, -376, + -427, -477, -527, -578, -628, -678, -728, -779, + -829, -879, -929, -980, -1030, -1080, -1130, -1181, + -1231, -1281, -1331, -1382, -1432, -1482, -1532, -1583, + -1633, -1683, -1733, -1784, -1834, -1884, -1934, -1985, + -2035, -2085, -2135, -2186, -2236, -2286, -2336, -2387, + -2437, -2487, -2537, -2588, -2638, -2688, -2738, -2788, + -2839, -2889, -2939, -2989, -3039, -3090, -3140, -3190, + -3240, -3291, -3341, -3391, -3441, -3491, -3541, -3592, + -3642, -3692, -3742, -3792, -3843, -3893, -3943, -3993, + -4043, -4093, -4144, -4194, -4244, -4294, -4344, -4394, + -4445, -4495, -4545, -4595, -4645, -4695, -4745, -4796, + -4846, -4896, -4946, -4996, -5046, -5096, -5146, -5197, + -5247, -5297, -5347, -5397, -5447, -5497, -5547, -5597, + -5647, -5697, -5748, -5798, -5848, -5898, -5948, -5998, + -6048, -6098, -6148, -6198, -6248, -6298, -6348, -6398, + -6448, -6498, -6548, -6598, -6648, -6698, -6748, -6798, + -6848, -6898, -6948, -6998, -7048, -7098, -7148, -7198, + -7248, -7298, -7348, -7398, -7448, -7498, -7548, -7598, + -7648, -7697, -7747, -7797, -7847, -7897, -7947, -7997, + -8047, -8097, -8147, -8196, -8246, -8296, -8346, -8396, + -8446, -8496, -8545, -8595, -8645, -8695, -8745, -8794, + -8844, -8894, -8944, -8994, -9043, -9093, -9143, -9193, + -9243, -9292, -9342, -9392, -9442, -9491, -9541, -9591, + -9640, -9690, -9740, -9790, -9839, -9889, -9939, -9988, + -10038, -10088, -10137, -10187, -10237, -10286, -10336, -10386, + -10435, -10485, -10534, -10584, -10634, -10683, -10733, -10782, + -10832, -10882, -10931, -10981, -11030, -11080, -11129, -11179, + -11228, -11278, -11327, -11377, -11426, -11476, -11525, -11575, + -11624, -11674, -11723, -11773, -11822, -11872, -11921, -11970, + -12020, -12069, -12119, -12168, -12218, -12267, -12316, -12366, + -12415, -12464, -12514, -12563, -12612, -12662, -12711, -12760, + -12810, -12859, -12908, -12957, -13007, -13056, -13105, -13154, + -13204, -13253, -13302, -13351, -13401, -13450, -13499, -13548, + -13597, -13647, -13696, -13745, -13794, -13843, -13892, -13941, + -13990, -14040, -14089, -14138, -14187, -14236, -14285, -14334, + -14383, -14432, -14481, -14530, -14579, -14628, -14677, -14726, + -14775, -14824, -14873, -14922, -14971, -15020, -15069, -15118, + -15167, -15215, -15264, -15313, -15362, -15411, -15460, -15509, + -15557, -15606, -15655, -15704, -15753, -15802, -15850, -15899, + -15948, -15997, -16045, -16094, -16143, -16191, -16240, -16289, + -16338, -16386, -16435, -16484, -16532, -16581, -16629, -16678, + -16727, -16775, -16824, -16872, -16921, -16970, -17018, -17067, + -17115, -17164, -17212, -17261, -17309, -17358, -17406, -17455, + -17503, -17551, -17600, -17648, -17697, -17745, -17793, -17842, + -17890, -17939, -17987, -18035, -18084, -18132, -18180, -18228, + -18277, -18325, -18373, -18421, -18470, -18518, -18566, -18614, + -18663, -18711, -18759, -18807, -18855, -18903, -18951, -19000, + -19048, -19096, -19144, -19192, -19240, -19288, -19336, -19384, + -19432, -19480, -19528, -19576, -19624, -19672, -19720, -19768, + -19816, -19864, -19912, -19959, -20007, -20055, -20103, -20151, + -20199, -20246, -20294, -20342, -20390, -20438, -20485, -20533, + -20581, -20629, -20676, -20724, -20772, -20819, -20867, -20915, + -20962, -21010, -21057, -21105, -21153, -21200, -21248, -21295, + -21343, -21390, -21438, -21485, -21533, -21580, -21628, -21675, + -21723, -21770, -21817, -21865, -21912, -21960, -22007, -22054, + -22102, -22149, -22196, -22243, -22291, -22338, -22385, -22433, + -22480, -22527, -22574, -22621, -22668, -22716, -22763, -22810, + -22857, -22904, -22951, -22998, -23045, -23092, -23139, -23186, + -23233, -23280, -23327, -23374, -23421, -23468, -23515, -23562, + -23609, -23656, -23703, -23750, -23796, -23843, -23890, -23937, + -23984, -24030, -24077, -24124, -24171, -24217, -24264, -24311, + -24357, -24404, -24451, -24497, -24544, -24591, -24637, -24684, + -24730, -24777, -24823, -24870, -24916, -24963, -25009, -25056, + -25102, -25149, -25195, -25241, -25288, -25334, -25381, -25427, + -25473, -25520, -25566, -25612, -25658, -25705, -25751, -25797, + -25843, -25889, -25936, -25982, -26028, -26074, -26120, -26166, + -26212, -26258, -26304, -26350, -26396, -26442, -26488, -26534, + -26580, -26626, -26672, -26718, -26764, -26810, -26856, -26902, + -26947, -26993, -27039, -27085, -27131, -27176, -27222, -27268, + -27313, -27359, -27405, -27450, -27496, -27542, -27587, -27633, + -27678, -27724, -27770, -27815, -27861, -27906, -27952, -27997, + -28042, -28088, -28133, -28179, -28224, -28269, -28315, -28360, + -28405, -28451, -28496, -28541, -28586, -28632, -28677, -28722, + -28767, -28812, -28858, -28903, -28948, -28993, -29038, -29083, + -29128, -29173, -29218, -29263, -29308, -29353, -29398, -29443, + -29488, -29533, -29577, -29622, -29667, -29712, -29757, -29801, + -29846, -29891, -29936, -29980, -30025, -30070, -30114, -30159, + -30204, -30248, -30293, -30337, -30382, -30426, -30471, -30515, + -30560, -30604, -30649, -30693, -30738, -30782, -30826, -30871, + -30915, -30959, -31004, -31048, -31092, -31136, -31181, -31225, + -31269, -31313, -31357, -31402, -31446, -31490, -31534, -31578, + -31622, -31666, -31710, -31754, -31798, -31842, -31886, -31930, + -31974, -32017, -32061, -32105, -32149, -32193, -32236, -32280, + -32324, -32368, -32411, -32455, -32499, -32542, -32586, -32630, + -32673, -32717, -32760, -32804, -32847, -32891, -32934, -32978, + -33021, -33065, -33108, -33151, -33195, -33238, -33281, -33325, + -33368, -33411, -33454, -33498, -33541, -33584, -33627, -33670, + -33713, -33756, -33799, -33843, -33886, -33929, -33972, -34015, + -34057, -34100, -34143, -34186, -34229, -34272, -34315, -34358, + -34400, -34443, -34486, -34529, -34571, -34614, -34657, -34699, + -34742, -34785, -34827, -34870, -34912, -34955, -34997, -35040, + -35082, -35125, -35167, -35210, -35252, -35294, -35337, -35379, + -35421, -35464, -35506, -35548, -35590, -35633, -35675, -35717, + -35759, -35801, -35843, -35885, -35927, -35969, -36011, -36053, + -36095, -36137, -36179, -36221, -36263, -36305, -36347, -36388, + -36430, -36472, -36514, -36555, -36597, -36639, -36681, -36722, + -36764, -36805, -36847, -36889, -36930, -36972, -37013, -37055, + -37096, -37137, -37179, -37220, -37262, -37303, -37344, -37386, + -37427, -37468, -37509, -37551, -37592, -37633, -37674, -37715, + -37756, -37797, -37838, -37879, -37920, -37961, -38002, -38043, + -38084, -38125, -38166, -38207, -38248, -38288, -38329, -38370, + -38411, -38451, -38492, -38533, -38573, -38614, -38655, -38695, + -38736, -38776, -38817, -38857, -38898, -38938, -38979, -39019, + -39059, -39100, -39140, -39180, -39221, -39261, -39301, -39341, + -39382, -39422, -39462, -39502, -39542, -39582, -39622, -39662, + -39702, -39742, -39782, -39822, -39862, -39902, -39942, -39982, + -40021, -40061, -40101, -40141, -40180, -40220, -40260, -40299, + -40339, -40379, -40418, -40458, -40497, -40537, -40576, -40616, + -40655, -40695, -40734, -40773, -40813, -40852, -40891, -40931, + -40970, -41009, -41048, -41087, -41127, -41166, -41205, -41244, + -41283, -41322, -41361, -41400, -41439, -41478, -41517, -41556, + -41595, -41633, -41672, -41711, -41750, -41788, -41827, -41866, + -41904, -41943, -41982, -42020, -42059, -42097, -42136, -42174, + -42213, -42251, -42290, -42328, -42366, -42405, -42443, -42481, + -42520, -42558, -42596, -42634, -42672, -42711, -42749, -42787, + -42825, -42863, -42901, -42939, -42977, -43015, -43053, -43091, + -43128, -43166, -43204, -43242, -43280, -43317, -43355, -43393, + -43430, -43468, -43506, -43543, -43581, -43618, -43656, -43693, + -43731, -43768, -43806, -43843, -43880, -43918, -43955, -43992, + -44029, -44067, -44104, -44141, -44178, -44215, -44252, -44289, + -44326, -44363, -44400, -44437, -44474, -44511, -44548, -44585, + -44622, -44659, -44695, -44732, -44769, -44806, -44842, -44879, + -44915, -44952, -44989, -45025, -45062, -45098, -45135, -45171, + -45207, -45244, -45280, -45316, -45353, -45389, -45425, -45462, + -45498, -45534, -45570, -45606, -45642, -45678, -45714, -45750, + -45786, -45822, -45858, -45894, -45930, -45966, -46002, -46037, + -46073, -46109, -46145, -46180, -46216, -46252, -46287, -46323, + -46358, -46394, -46429, -46465, -46500, -46536, -46571, -46606, + -46642, -46677, -46712, -46747, -46783, -46818, -46853, -46888, + -46923, -46958, -46993, -47028, -47063, -47098, -47133, -47168, + -47203, -47238, -47273, -47308, -47342, -47377, -47412, -47446, + -47481, -47516, -47550, -47585, -47619, -47654, -47688, -47723, + -47757, -47792, -47826, -47860, -47895, -47929, -47963, -47998, + -48032, -48066, -48100, -48134, -48168, -48202, -48236, -48271, + -48304, -48338, -48372, -48406, -48440, -48474, -48508, -48542, + -48575, -48609, -48643, -48676, -48710, -48744, -48777, -48811, + -48844, -48878, -48911, -48945, -48978, -49012, -49045, -49078, + -49112, -49145, -49178, -49211, -49244, -49278, -49311, -49344, + -49377, -49410, -49443, -49476, -49509, -49542, -49575, -49608, + -49640, -49673, -49706, -49739, -49771, -49804, -49837, -49869, + -49902, -49935, -49967, -50000, -50032, -50065, -50097, -50129, + -50162, -50194, -50226, -50259, -50291, -50323, -50355, -50387, + -50420, -50452, -50484, -50516, -50548, -50580, -50612, -50644, + -50675, -50707, -50739, -50771, -50803, -50834, -50866, -50898, + -50929, -50961, -50993, -51024, -51056, -51087, -51119, -51150, + -51182, -51213, -51244, -51276, -51307, -51338, -51369, -51401, + -51432, -51463, -51494, -51525, -51556, -51587, -51618, -51649, + -51680, -51711, -51742, -51773, -51803, -51834, -51865, -51896, + -51926, -51957, -51988, -52018, -52049, -52079, -52110, -52140, + -52171, -52201, -52231, -52262, -52292, -52322, -52353, -52383, + -52413, -52443, -52473, -52503, -52534, -52564, -52594, -52624, + -52653, -52683, -52713, -52743, -52773, -52803, -52832, -52862, + -52892, -52922, -52951, -52981, -53010, -53040, -53069, -53099, + -53128, -53158, -53187, -53216, -53246, -53275, -53304, -53334, + -53363, -53392, -53421, -53450, -53479, -53508, -53537, -53566, + -53595, -53624, -53653, -53682, -53711, -53739, -53768, -53797, + -53826, -53854, -53883, -53911, -53940, -53969, -53997, -54026, + -54054, -54082, -54111, -54139, -54167, -54196, -54224, -54252, + -54280, -54308, -54337, -54365, -54393, -54421, -54449, -54477, + -54505, -54533, -54560, -54588, -54616, -54644, -54672, -54699, + -54727, -54755, -54782, -54810, -54837, -54865, -54892, -54920, + -54947, -54974, -55002, -55029, -55056, -55084, -55111, -55138, + -55165, -55192, -55219, -55246, -55274, -55300, -55327, -55354, + -55381, -55408, -55435, -55462, -55489, -55515, -55542, -55569, + -55595, -55622, -55648, -55675, -55701, -55728, -55754, -55781, + -55807, -55833, -55860, -55886, -55912, -55938, -55965, -55991, + -56017, -56043, -56069, -56095, -56121, -56147, -56173, -56199, + -56225, -56250, -56276, -56302, -56328, -56353, -56379, -56404, + -56430, -56456, -56481, -56507, -56532, -56557, -56583, -56608, + -56633, -56659, -56684, -56709, -56734, -56760, -56785, -56810, + -56835, -56860, -56885, -56910, -56935, -56959, -56984, -57009, + -57034, -57059, -57083, -57108, -57133, -57157, -57182, -57206, + -57231, -57255, -57280, -57304, -57329, -57353, -57377, -57402, + -57426, -57450, -57474, -57498, -57522, -57546, -57570, -57594, + -57618, -57642, -57666, -57690, -57714, -57738, -57762, -57785, + -57809, -57833, -57856, -57880, -57903, -57927, -57950, -57974, + -57997, -58021, -58044, -58067, -58091, -58114, -58137, -58160, + -58183, -58207, -58230, -58253, -58276, -58299, -58322, -58345, + -58367, -58390, -58413, -58436, -58459, -58481, -58504, -58527, + -58549, -58572, -58594, -58617, -58639, -58662, -58684, -58706, + -58729, -58751, -58773, -58795, -58818, -58840, -58862, -58884, + -58906, -58928, -58950, -58972, -58994, -59016, -59038, -59059, + -59081, -59103, -59125, -59146, -59168, -59190, -59211, -59233, + -59254, -59276, -59297, -59318, -59340, -59361, -59382, -59404, + -59425, -59446, -59467, -59488, -59509, -59530, -59551, -59572, + -59593, -59614, -59635, -59656, -59677, -59697, -59718, -59739, + -59759, -59780, -59801, -59821, -59842, -59862, -59883, -59903, + -59923, -59944, -59964, -59984, -60004, -60025, -60045, -60065, + -60085, -60105, -60125, -60145, -60165, -60185, -60205, -60225, + -60244, -60264, -60284, -60304, -60323, -60343, -60363, -60382, + -60402, -60421, -60441, -60460, -60479, -60499, -60518, -60537, + -60556, -60576, -60595, -60614, -60633, -60652, -60671, -60690, + -60709, -60728, -60747, -60766, -60785, -60803, -60822, -60841, + -60859, -60878, -60897, -60915, -60934, -60952, -60971, -60989, + -61007, -61026, -61044, -61062, -61081, -61099, -61117, -61135, + -61153, -61171, -61189, -61207, -61225, -61243, -61261, -61279, + -61297, -61314, -61332, -61350, -61367, -61385, -61403, -61420, + -61438, -61455, -61473, -61490, -61507, -61525, -61542, -61559, + -61577, -61594, -61611, -61628, -61645, -61662, -61679, -61696, + -61713, -61730, -61747, -61764, -61780, -61797, -61814, -61831, + -61847, -61864, -61880, -61897, -61913, -61930, -61946, -61963, + -61979, -61995, -62012, -62028, -62044, -62060, -62076, -62092, + -62108, -62125, -62141, -62156, -62172, -62188, -62204, -62220, + -62236, -62251, -62267, -62283, -62298, -62314, -62329, -62345, + -62360, -62376, -62391, -62407, -62422, -62437, -62453, -62468, + -62483, -62498, -62513, -62528, -62543, -62558, -62573, -62588, + -62603, -62618, -62633, -62648, -62662, -62677, -62692, -62706, + -62721, -62735, -62750, -62764, -62779, -62793, -62808, -62822, + -62836, -62850, -62865, -62879, -62893, -62907, -62921, -62935, + -62949, -62963, -62977, -62991, -63005, -63019, -63032, -63046, + -63060, -63074, -63087, -63101, -63114, -63128, -63141, -63155, + -63168, -63182, -63195, -63208, -63221, -63235, -63248, -63261, + -63274, -63287, -63300, -63313, -63326, -63339, -63352, -63365, + -63378, -63390, -63403, -63416, -63429, -63441, -63454, -63466, + -63479, -63491, -63504, -63516, -63528, -63541, -63553, -63565, + -63578, -63590, -63602, -63614, -63626, -63638, -63650, -63662, + -63674, -63686, -63698, -63709, -63721, -63733, -63745, -63756, + -63768, -63779, -63791, -63803, -63814, -63825, -63837, -63848, + -63859, -63871, -63882, -63893, -63904, -63915, -63927, -63938, + -63949, -63960, -63971, -63981, -63992, -64003, -64014, -64025, + -64035, -64046, -64057, -64067, -64078, -64088, -64099, -64109, + -64120, -64130, -64140, -64151, -64161, -64171, -64181, -64192, + -64202, -64212, -64222, -64232, -64242, -64252, -64261, -64271, + -64281, -64291, -64301, -64310, -64320, -64330, -64339, -64349, + -64358, -64368, -64377, -64387, -64396, -64405, -64414, -64424, + -64433, -64442, -64451, -64460, -64469, -64478, -64487, -64496, + -64505, -64514, -64523, -64532, -64540, -64549, -64558, -64566, + -64575, -64584, -64592, -64601, -64609, -64617, -64626, -64634, + -64642, -64651, -64659, -64667, -64675, -64683, -64691, -64699, + -64707, -64715, -64723, -64731, -64739, -64747, -64754, -64762, + -64770, -64777, -64785, -64793, -64800, -64808, -64815, -64822, + -64830, -64837, -64844, -64852, -64859, -64866, -64873, -64880, + -64887, -64895, -64902, -64908, -64915, -64922, -64929, -64936, + -64943, -64949, -64956, -64963, -64969, -64976, -64982, -64989, + -64995, -65002, -65008, -65015, -65021, -65027, -65033, -65040, + -65046, -65052, -65058, -65064, -65070, -65076, -65082, -65088, + -65094, -65099, -65105, -65111, -65117, -65122, -65128, -65133, + -65139, -65144, -65150, -65155, -65161, -65166, -65171, -65177, + -65182, -65187, -65192, -65197, -65202, -65207, -65212, -65217, + -65222, -65227, -65232, -65237, -65242, -65246, -65251, -65256, + -65260, -65265, -65270, -65274, -65279, -65283, -65287, -65292, + -65296, -65300, -65305, -65309, -65313, -65317, -65321, -65325, + -65329, -65333, -65337, -65341, -65345, -65349, -65352, -65356, + -65360, -65363, -65367, -65371, -65374, -65378, -65381, -65385, + -65388, -65391, -65395, -65398, -65401, -65404, -65408, -65411, + -65414, -65417, -65420, -65423, -65426, -65429, -65431, -65434, + -65437, -65440, -65442, -65445, -65448, -65450, -65453, -65455, + -65458, -65460, -65463, -65465, -65467, -65470, -65472, -65474, + -65476, -65478, -65480, -65482, -65484, -65486, -65488, -65490, + -65492, -65494, -65496, -65497, -65499, -65501, -65502, -65504, + -65505, -65507, -65508, -65510, -65511, -65513, -65514, -65515, + -65516, -65518, -65519, -65520, -65521, -65522, -65523, -65524, + -65525, -65526, -65527, -65527, -65528, -65529, -65530, -65530, + -65531, -65531, -65532, -65532, -65533, -65533, -65534, -65534, + -65534, -65535, -65535, -65535, -65535, -65535, -65535, -65535, + -65535, -65535, -65535, -65535, -65535, -65535, -65535, -65534, + -65534, -65534, -65533, -65533, -65532, -65532, -65531, -65531, + -65530, -65530, -65529, -65528, -65527, -65527, -65526, -65525, + -65524, -65523, -65522, -65521, -65520, -65519, -65518, -65516, + -65515, -65514, -65513, -65511, -65510, -65508, -65507, -65505, + -65504, -65502, -65501, -65499, -65497, -65496, -65494, -65492, + -65490, -65488, -65486, -65484, -65482, -65480, -65478, -65476, + -65474, -65472, -65470, -65467, -65465, -65463, -65460, -65458, + -65455, -65453, -65450, -65448, -65445, -65442, -65440, -65437, + -65434, -65431, -65429, -65426, -65423, -65420, -65417, -65414, + -65411, -65408, -65404, -65401, -65398, -65395, -65391, -65388, + -65385, -65381, -65378, -65374, -65371, -65367, -65363, -65360, + -65356, -65352, -65349, -65345, -65341, -65337, -65333, -65329, + -65325, -65321, -65317, -65313, -65309, -65305, -65300, -65296, + -65292, -65287, -65283, -65279, -65274, -65270, -65265, -65260, + -65256, -65251, -65246, -65242, -65237, -65232, -65227, -65222, + -65217, -65212, -65207, -65202, -65197, -65192, -65187, -65182, + -65177, -65171, -65166, -65161, -65155, -65150, -65144, -65139, + -65133, -65128, -65122, -65117, -65111, -65105, -65099, -65094, + -65088, -65082, -65076, -65070, -65064, -65058, -65052, -65046, + -65040, -65033, -65027, -65021, -65015, -65008, -65002, -64995, + -64989, -64982, -64976, -64969, -64963, -64956, -64949, -64943, + -64936, -64929, -64922, -64915, -64908, -64902, -64895, -64887, + -64880, -64873, -64866, -64859, -64852, -64844, -64837, -64830, + -64822, -64815, -64808, -64800, -64793, -64785, -64777, -64770, + -64762, -64754, -64747, -64739, -64731, -64723, -64715, -64707, + -64699, -64691, -64683, -64675, -64667, -64659, -64651, -64642, + -64634, -64626, -64617, -64609, -64601, -64592, -64584, -64575, + -64566, -64558, -64549, -64540, -64532, -64523, -64514, -64505, + -64496, -64487, -64478, -64469, -64460, -64451, -64442, -64433, + -64424, -64414, -64405, -64396, -64387, -64377, -64368, -64358, + -64349, -64339, -64330, -64320, -64310, -64301, -64291, -64281, + -64271, -64261, -64252, -64242, -64232, -64222, -64212, -64202, + -64192, -64181, -64171, -64161, -64151, -64140, -64130, -64120, + -64109, -64099, -64088, -64078, -64067, -64057, -64046, -64035, + -64025, -64014, -64003, -63992, -63981, -63971, -63960, -63949, + -63938, -63927, -63915, -63904, -63893, -63882, -63871, -63859, + -63848, -63837, -63825, -63814, -63803, -63791, -63779, -63768, + -63756, -63745, -63733, -63721, -63709, -63698, -63686, -63674, + -63662, -63650, -63638, -63626, -63614, -63602, -63590, -63578, + -63565, -63553, -63541, -63528, -63516, -63504, -63491, -63479, + -63466, -63454, -63441, -63429, -63416, -63403, -63390, -63378, + -63365, -63352, -63339, -63326, -63313, -63300, -63287, -63274, + -63261, -63248, -63235, -63221, -63208, -63195, -63182, -63168, + -63155, -63141, -63128, -63114, -63101, -63087, -63074, -63060, + -63046, -63032, -63019, -63005, -62991, -62977, -62963, -62949, + -62935, -62921, -62907, -62893, -62879, -62865, -62850, -62836, + -62822, -62808, -62793, -62779, -62764, -62750, -62735, -62721, + -62706, -62692, -62677, -62662, -62648, -62633, -62618, -62603, + -62588, -62573, -62558, -62543, -62528, -62513, -62498, -62483, + -62468, -62453, -62437, -62422, -62407, -62391, -62376, -62360, + -62345, -62329, -62314, -62298, -62283, -62267, -62251, -62236, + -62220, -62204, -62188, -62172, -62156, -62141, -62125, -62108, + -62092, -62076, -62060, -62044, -62028, -62012, -61995, -61979, + -61963, -61946, -61930, -61913, -61897, -61880, -61864, -61847, + -61831, -61814, -61797, -61780, -61764, -61747, -61730, -61713, + -61696, -61679, -61662, -61645, -61628, -61611, -61594, -61577, + -61559, -61542, -61525, -61507, -61490, -61473, -61455, -61438, + -61420, -61403, -61385, -61367, -61350, -61332, -61314, -61297, + -61279, -61261, -61243, -61225, -61207, -61189, -61171, -61153, + -61135, -61117, -61099, -61081, -61062, -61044, -61026, -61007, + -60989, -60971, -60952, -60934, -60915, -60897, -60878, -60859, + -60841, -60822, -60803, -60785, -60766, -60747, -60728, -60709, + -60690, -60671, -60652, -60633, -60614, -60595, -60576, -60556, + -60537, -60518, -60499, -60479, -60460, -60441, -60421, -60402, + -60382, -60363, -60343, -60323, -60304, -60284, -60264, -60244, + -60225, -60205, -60185, -60165, -60145, -60125, -60105, -60085, + -60065, -60045, -60025, -60004, -59984, -59964, -59944, -59923, + -59903, -59883, -59862, -59842, -59821, -59801, -59780, -59759, + -59739, -59718, -59697, -59677, -59656, -59635, -59614, -59593, + -59572, -59551, -59530, -59509, -59488, -59467, -59446, -59425, + -59404, -59382, -59361, -59340, -59318, -59297, -59276, -59254, + -59233, -59211, -59189, -59168, -59146, -59125, -59103, -59081, + -59059, -59038, -59016, -58994, -58972, -58950, -58928, -58906, + -58884, -58862, -58840, -58818, -58795, -58773, -58751, -58729, + -58706, -58684, -58662, -58639, -58617, -58594, -58572, -58549, + -58527, -58504, -58481, -58459, -58436, -58413, -58390, -58367, + -58345, -58322, -58299, -58276, -58253, -58230, -58207, -58183, + -58160, -58137, -58114, -58091, -58067, -58044, -58021, -57997, + -57974, -57950, -57927, -57903, -57880, -57856, -57833, -57809, + -57785, -57762, -57738, -57714, -57690, -57666, -57642, -57618, + -57594, -57570, -57546, -57522, -57498, -57474, -57450, -57426, + -57402, -57377, -57353, -57329, -57304, -57280, -57255, -57231, + -57206, -57182, -57157, -57133, -57108, -57083, -57059, -57034, + -57009, -56984, -56959, -56935, -56910, -56885, -56860, -56835, + -56810, -56785, -56760, -56734, -56709, -56684, -56659, -56633, + -56608, -56583, -56557, -56532, -56507, -56481, -56456, -56430, + -56404, -56379, -56353, -56328, -56302, -56276, -56250, -56225, + -56199, -56173, -56147, -56121, -56095, -56069, -56043, -56017, + -55991, -55965, -55938, -55912, -55886, -55860, -55833, -55807, + -55781, -55754, -55728, -55701, -55675, -55648, -55622, -55595, + -55569, -55542, -55515, -55489, -55462, -55435, -55408, -55381, + -55354, -55327, -55300, -55274, -55246, -55219, -55192, -55165, + -55138, -55111, -55084, -55056, -55029, -55002, -54974, -54947, + -54920, -54892, -54865, -54837, -54810, -54782, -54755, -54727, + -54699, -54672, -54644, -54616, -54588, -54560, -54533, -54505, + -54477, -54449, -54421, -54393, -54365, -54337, -54308, -54280, + -54252, -54224, -54196, -54167, -54139, -54111, -54082, -54054, + -54026, -53997, -53969, -53940, -53911, -53883, -53854, -53826, + -53797, -53768, -53739, -53711, -53682, -53653, -53624, -53595, + -53566, -53537, -53508, -53479, -53450, -53421, -53392, -53363, + -53334, -53304, -53275, -53246, -53216, -53187, -53158, -53128, + -53099, -53069, -53040, -53010, -52981, -52951, -52922, -52892, + -52862, -52832, -52803, -52773, -52743, -52713, -52683, -52653, + -52624, -52594, -52564, -52534, -52503, -52473, -52443, -52413, + -52383, -52353, -52322, -52292, -52262, -52231, -52201, -52171, + -52140, -52110, -52079, -52049, -52018, -51988, -51957, -51926, + -51896, -51865, -51834, -51803, -51773, -51742, -51711, -51680, + -51649, -51618, -51587, -51556, -51525, -51494, -51463, -51432, + -51401, -51369, -51338, -51307, -51276, -51244, -51213, -51182, + -51150, -51119, -51087, -51056, -51024, -50993, -50961, -50929, + -50898, -50866, -50834, -50803, -50771, -50739, -50707, -50675, + -50644, -50612, -50580, -50548, -50516, -50484, -50452, -50420, + -50387, -50355, -50323, -50291, -50259, -50226, -50194, -50162, + -50129, -50097, -50065, -50032, -50000, -49967, -49935, -49902, + -49869, -49837, -49804, -49771, -49739, -49706, -49673, -49640, + -49608, -49575, -49542, -49509, -49476, -49443, -49410, -49377, + -49344, -49311, -49278, -49244, -49211, -49178, -49145, -49112, + -49078, -49045, -49012, -48978, -48945, -48911, -48878, -48844, + -48811, -48777, -48744, -48710, -48676, -48643, -48609, -48575, + -48542, -48508, -48474, -48440, -48406, -48372, -48338, -48305, + -48271, -48237, -48202, -48168, -48134, -48100, -48066, -48032, + -47998, -47963, -47929, -47895, -47860, -47826, -47792, -47757, + -47723, -47688, -47654, -47619, -47585, -47550, -47516, -47481, + -47446, -47412, -47377, -47342, -47307, -47273, -47238, -47203, + -47168, -47133, -47098, -47063, -47028, -46993, -46958, -46923, + -46888, -46853, -46818, -46783, -46747, -46712, -46677, -46642, + -46606, -46571, -46536, -46500, -46465, -46429, -46394, -46358, + -46323, -46287, -46251, -46216, -46180, -46145, -46109, -46073, + -46037, -46002, -45966, -45930, -45894, -45858, -45822, -45786, + -45750, -45714, -45678, -45642, -45606, -45570, -45534, -45498, + -45462, -45425, -45389, -45353, -45316, -45280, -45244, -45207, + -45171, -45135, -45098, -45062, -45025, -44989, -44952, -44915, + -44879, -44842, -44806, -44769, -44732, -44695, -44659, -44622, + -44585, -44548, -44511, -44474, -44437, -44400, -44363, -44326, + -44289, -44252, -44215, -44178, -44141, -44104, -44067, -44029, + -43992, -43955, -43918, -43880, -43843, -43806, -43768, -43731, + -43693, -43656, -43618, -43581, -43543, -43506, -43468, -43430, + -43393, -43355, -43317, -43280, -43242, -43204, -43166, -43128, + -43091, -43053, -43015, -42977, -42939, -42901, -42863, -42825, + -42787, -42749, -42711, -42672, -42634, -42596, -42558, -42520, + -42481, -42443, -42405, -42366, -42328, -42290, -42251, -42213, + -42174, -42136, -42097, -42059, -42020, -41982, -41943, -41904, + -41866, -41827, -41788, -41750, -41711, -41672, -41633, -41595, + -41556, -41517, -41478, -41439, -41400, -41361, -41322, -41283, + -41244, -41205, -41166, -41127, -41087, -41048, -41009, -40970, + -40931, -40891, -40852, -40813, -40773, -40734, -40695, -40655, + -40616, -40576, -40537, -40497, -40458, -40418, -40379, -40339, + -40299, -40260, -40220, -40180, -40141, -40101, -40061, -40021, + -39982, -39942, -39902, -39862, -39822, -39782, -39742, -39702, + -39662, -39622, -39582, -39542, -39502, -39462, -39422, -39382, + -39341, -39301, -39261, -39221, -39180, -39140, -39100, -39059, + -39019, -38979, -38938, -38898, -38857, -38817, -38776, -38736, + -38695, -38655, -38614, -38573, -38533, -38492, -38451, -38411, + -38370, -38329, -38288, -38248, -38207, -38166, -38125, -38084, + -38043, -38002, -37961, -37920, -37879, -37838, -37797, -37756, + -37715, -37674, -37633, -37592, -37550, -37509, -37468, -37427, + -37386, -37344, -37303, -37262, -37220, -37179, -37137, -37096, + -37055, -37013, -36972, -36930, -36889, -36847, -36805, -36764, + -36722, -36681, -36639, -36597, -36556, -36514, -36472, -36430, + -36388, -36347, -36305, -36263, -36221, -36179, -36137, -36095, + -36053, -36011, -35969, -35927, -35885, -35843, -35801, -35759, + -35717, -35675, -35633, -35590, -35548, -35506, -35464, -35421, + -35379, -35337, -35294, -35252, -35210, -35167, -35125, -35082, + -35040, -34997, -34955, -34912, -34870, -34827, -34785, -34742, + -34699, -34657, -34614, -34571, -34529, -34486, -34443, -34400, + -34358, -34315, -34272, -34229, -34186, -34143, -34100, -34057, + -34015, -33972, -33929, -33886, -33843, -33799, -33756, -33713, + -33670, -33627, -33584, -33541, -33498, -33454, -33411, -33368, + -33325, -33281, -33238, -33195, -33151, -33108, -33065, -33021, + -32978, -32934, -32891, -32847, -32804, -32760, -32717, -32673, + -32630, -32586, -32542, -32499, -32455, -32411, -32368, -32324, + -32280, -32236, -32193, -32149, -32105, -32061, -32017, -31974, + -31930, -31886, -31842, -31798, -31754, -31710, -31666, -31622, + -31578, -31534, -31490, -31446, -31402, -31357, -31313, -31269, + -31225, -31181, -31136, -31092, -31048, -31004, -30959, -30915, + -30871, -30826, -30782, -30738, -30693, -30649, -30604, -30560, + -30515, -30471, -30426, -30382, -30337, -30293, -30248, -30204, + -30159, -30114, -30070, -30025, -29980, -29936, -29891, -29846, + -29801, -29757, -29712, -29667, -29622, -29577, -29533, -29488, + -29443, -29398, -29353, -29308, -29263, -29218, -29173, -29128, + -29083, -29038, -28993, -28948, -28903, -28858, -28812, -28767, + -28722, -28677, -28632, -28586, -28541, -28496, -28451, -28405, + -28360, -28315, -28269, -28224, -28179, -28133, -28088, -28042, + -27997, -27952, -27906, -27861, -27815, -27770, -27724, -27678, + -27633, -27587, -27542, -27496, -27450, -27405, -27359, -27313, + -27268, -27222, -27176, -27131, -27085, -27039, -26993, -26947, + -26902, -26856, -26810, -26764, -26718, -26672, -26626, -26580, + -26534, -26488, -26442, -26396, -26350, -26304, -26258, -26212, + -26166, -26120, -26074, -26028, -25982, -25936, -25889, -25843, + -25797, -25751, -25705, -25658, -25612, -25566, -25520, -25473, + -25427, -25381, -25334, -25288, -25241, -25195, -25149, -25102, + -25056, -25009, -24963, -24916, -24870, -24823, -24777, -24730, + -24684, -24637, -24591, -24544, -24497, -24451, -24404, -24357, + -24311, -24264, -24217, -24171, -24124, -24077, -24030, -23984, + -23937, -23890, -23843, -23796, -23750, -23703, -23656, -23609, + -23562, -23515, -23468, -23421, -23374, -23327, -23280, -23233, + -23186, -23139, -23092, -23045, -22998, -22951, -22904, -22857, + -22810, -22763, -22716, -22668, -22621, -22574, -22527, -22480, + -22432, -22385, -22338, -22291, -22243, -22196, -22149, -22102, + -22054, -22007, -21960, -21912, -21865, -21817, -21770, -21723, + -21675, -21628, -21580, -21533, -21485, -21438, -21390, -21343, + -21295, -21248, -21200, -21153, -21105, -21057, -21010, -20962, + -20915, -20867, -20819, -20772, -20724, -20676, -20629, -20581, + -20533, -20485, -20438, -20390, -20342, -20294, -20246, -20199, + -20151, -20103, -20055, -20007, -19959, -19912, -19864, -19816, + -19768, -19720, -19672, -19624, -19576, -19528, -19480, -19432, + -19384, -19336, -19288, -19240, -19192, -19144, -19096, -19048, + -19000, -18951, -18903, -18855, -18807, -18759, -18711, -18663, + -18614, -18566, -18518, -18470, -18421, -18373, -18325, -18277, + -18228, -18180, -18132, -18084, -18035, -17987, -17939, -17890, + -17842, -17793, -17745, -17697, -17648, -17600, -17551, -17503, + -17455, -17406, -17358, -17309, -17261, -17212, -17164, -17115, + -17067, -17018, -16970, -16921, -16872, -16824, -16775, -16727, + -16678, -16629, -16581, -16532, -16484, -16435, -16386, -16338, + -16289, -16240, -16191, -16143, -16094, -16045, -15997, -15948, + -15899, -15850, -15802, -15753, -15704, -15655, -15606, -15557, + -15509, -15460, -15411, -15362, -15313, -15264, -15215, -15167, + -15118, -15069, -15020, -14971, -14922, -14873, -14824, -14775, + -14726, -14677, -14628, -14579, -14530, -14481, -14432, -14383, + -14334, -14285, -14236, -14187, -14138, -14089, -14040, -13990, + -13941, -13892, -13843, -13794, -13745, -13696, -13647, -13597, + -13548, -13499, -13450, -13401, -13351, -13302, -13253, -13204, + -13154, -13105, -13056, -13007, -12957, -12908, -12859, -12810, + -12760, -12711, -12662, -12612, -12563, -12514, -12464, -12415, + -12366, -12316, -12267, -12217, -12168, -12119, -12069, -12020, + -11970, -11921, -11872, -11822, -11773, -11723, -11674, -11624, + -11575, -11525, -11476, -11426, -11377, -11327, -11278, -11228, + -11179, -11129, -11080, -11030, -10981, -10931, -10882, -10832, + -10782, -10733, -10683, -10634, -10584, -10534, -10485, -10435, + -10386, -10336, -10286, -10237, -10187, -10137, -10088, -10038, + -9988, -9939, -9889, -9839, -9790, -9740, -9690, -9640, + -9591, -9541, -9491, -9442, -9392, -9342, -9292, -9243, + -9193, -9143, -9093, -9043, -8994, -8944, -8894, -8844, + -8794, -8745, -8695, -8645, -8595, -8545, -8496, -8446, + -8396, -8346, -8296, -8246, -8196, -8147, -8097, -8047, + -7997, -7947, -7897, -7847, -7797, -7747, -7697, -7648, + -7598, -7548, -7498, -7448, -7398, -7348, -7298, -7248, + -7198, -7148, -7098, -7048, -6998, -6948, -6898, -6848, + -6798, -6748, -6698, -6648, -6598, -6548, -6498, -6448, + -6398, -6348, -6298, -6248, -6198, -6148, -6098, -6048, + -5998, -5948, -5898, -5848, -5798, -5747, -5697, -5647, + -5597, -5547, -5497, -5447, -5397, -5347, -5297, -5247, + -5197, -5146, -5096, -5046, -4996, -4946, -4896, -4846, + -4796, -4745, -4695, -4645, -4595, -4545, -4495, -4445, + -4394, -4344, -4294, -4244, -4194, -4144, -4093, -4043, + -3993, -3943, -3893, -3843, -3792, -3742, -3692, -3642, + -3592, -3541, -3491, -3441, -3391, -3341, -3291, -3240, + -3190, -3140, -3090, -3039, -2989, -2939, -2889, -2839, + -2788, -2738, -2688, -2638, -2588, -2537, -2487, -2437, + -2387, -2336, -2286, -2236, -2186, -2135, -2085, -2035, + -1985, -1934, -1884, -1834, -1784, -1733, -1683, -1633, + -1583, -1532, -1482, -1432, -1382, -1331, -1281, -1231, + -1181, -1130, -1080, -1030, -980, -929, -879, -829, + -779, -728, -678, -628, -578, -527, -477, -427, + -376, -326, -276, -226, -175, -125, -75, -25 + }; + /* MAES: Java can't use that much direct init data in a single class (finesine alone is well beyond that) * so a first workaround is to generate the data procedurally. * If this proves to cause accuracy problems, an external data file could be used. * Another workaround is to define the int table in its own file and then import or "implement" it. */ - - // Re-use data, is just PI/2 phase shift. - public static final int[] finecosine=new int[FINEANGLES]; + // Re-use data, is just PI/2 phase shift. + public static final int[] finecosine = new int[FINEANGLES]; - /* MAES: Java can't use that much direct init data in a single class so a first workaround + /* MAES: Java can't use that much direct init data in a single class so a first workaround * s to generate the data procedurally. * If this proves to cause accuracy problems, an external data file could be used. * Another workaround is to define the int table in its own file and then import * or "implement" it. - */ + */ + static { + System.arraycopy(finesine, FINEANGLES / 4, finecosine, 0, FINEANGLES); + } + + private SineCosine() { - static{ - System.arraycopy(finesine, FINEANGLES/4,finecosine, 0, FINEANGLES); - } + } - private SineCosine(){ - - } - } diff --git a/src/data/Tables.java b/src/data/Tables.java index dd7742af..aeddf865 100644 --- a/src/data/Tables.java +++ b/src/data/Tables.java @@ -1,6 +1,7 @@ package data; -import static m.fixed_t.*; +import static m.fixed_t.FRACBITS; +import static m.fixed_t.FRACUNIT; // Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- @@ -122,44 +123,40 @@ // // //----------------------------------------------------------------------------- - public final class Tables { - public static final String rcsid="$Id:"; - - public static final double PI = 3.141592657; - - /** Normally set to 12, and this sets the value of other constants too. - * Howevever changing it will also distort the view, resulting in a - * nightmare-like vision. There are some practical minimum and - * maximums as well. - * - * - */ - - public static final int BITSPRECISION = 12; - public static final int FINEANGLES = 2<>>8)); + public static final int SLOPERANGE = (2 << (BITSPRECISION - 2)); // Normally 2048. + public static final int SLOPEBITS = BITSPRECISION - 1; + public static final int DBITS = FRACBITS - SLOPEBITS; - return ans <= SLOPERANGE ? ans : SLOPERANGE; -} +// typedef unsigned angle_t; + // Effective size is 2049; + // The +1 size is to handle the case when x==y + // without additional checking. + //extern angle_t tantoangle[SLOPERANGE+1]; + /** + * Original size was 10240, but includes 5PI/4 periods. We can get away with + * ints on this one because of the small range. MAES: WTF? -64 ~ 64K + * range... so 17-bit accuracy? heh. + */ + public static final int[] finesine = new int[FINEANGLES + QUARTERMARK]; + public static final int[] finecosine = new int[FINEANGLES]; + + /** Any denominator smaller than 512 will result in + * maximum slope (45 degrees, or an index into tantoangle of 2048) + * The original method used unsigned args. So if this returns NEGATIVES + * in any way, it means you fucked up. Another "consistency" for Doom. + * Even though it was called upon fixed_t signed numbers. + * + */ + public static final int SlopeDiv(long num, long den) { + int ans; + + if (den < 512) { + return SLOPERANGE; + } -/** Finetangent table. It only has 4096 values corresponding roughly - * to -90/+90 angles, with values between are -/+ 2607 for "infinity". - * - * Since in vanilla accesses to the table can overflow way beyond 4096 - * indexes, the access index must be clipped to 4K tops via an accessor, - * or, in order to simulate some aspects of vanilla overflowing, replicate - * 4K of finesine's values AFTER the 4K index. This removes the need - * for access checking, at the cost of some extra memory. It also allows - * a small degree of "vanilla like" compatibility. - * - * - */ + ans = (int) ((num << 3) / (den >>> 8)); -public final static int[] finetangent=new int[2*FINETANS]; + return ans <= SLOPERANGE ? ans : SLOPERANGE; + } + /** Finetangent table. It only has 4096 values corresponding roughly + * to -90/+90 angles, with values between are -/+ 2607 for "infinity". + * + * Since in vanilla accesses to the table can overflow way beyond 4096 + * indexes, the access index must be clipped to 4K tops via an accessor, + * or, in order to simulate some aspects of vanilla overflowing, replicate + * 4K of finesine's values AFTER the 4K index. This removes the need + * for access checking, at the cost of some extra memory. It also allows + * a small degree of "vanilla like" compatibility. + * + * + */ + public final static int[] finetangent = new int[2 * FINETANS]; // MAES: original range 2049 // This obviously // Range goes from 0x00000000 to 0x20000000, so in theory plain ints should be enough... + /** This maps a value 0-2048 to a BAM unsigned integer angle, ranging from 0x0 to 0x2000000: + * + * In practice, this means there are only tangent values for angles up to 45 degrees. + * + * These values are valid BAM measurements in the first quadrant + * + * + */ + public static final int[] tantoangle = new int[SLOPERANGE + 1]; + + /** Use this to get a value from the finesine table. It will be automatically shifte, + * Equivalent to finesine[angle>>>ANGLETOFINESHIFT] + * + * @param angle in BAM units + * @return + */ + public static final int finesine(int angle) { + return finesine[angle >>> ANGLETOFINESHIFT]; + } -/** This maps a value 0-2048 to a BAM unsigned integer angle, ranging from 0x0 to 0x2000000: - * - * In practice, this means there are only tangent values for angles up to 45 degrees. - * - * These values are valid BAM measurements in the first quadrant - * - * - */ - -public static final int[] tantoangle=new int[SLOPERANGE+1]; - -/** Use this to get a value from the finesine table. It will be automatically shifte, - * Equivalent to finesine[angle>>>ANGLETOFINESHIFT] - * - * @param angle in BAM units - * @return - */ -public static final int finesine(int angle){ - return finesine[angle>>>ANGLETOFINESHIFT]; -} - -/** Use this to get a value from the finesine table using a long argument. - * It will automatically shift, apply rollover module and cast. - * - * Equivalent to finesine[(int) ((angle>>ANGLETOFINESHIFT)%ANGLEMODULE)]; - * - * @param angle in BAM units - * @return - */ -public static final int finesine(long angle){ - return finesine[(int) ((angle&BITS32)>>>ANGLETOFINESHIFT)]; -} + /** Use this to get a value from the finesine table using a long argument. + * It will automatically shift, apply rollover module and cast. + * + * Equivalent to finesine[(int) ((angle>>ANGLETOFINESHIFT)%ANGLEMODULE)]; + * + * @param angle in BAM units + * @return + */ + public static final int finesine(long angle) { + return finesine[(int) ((angle & BITS32) >>> ANGLETOFINESHIFT)]; + } -/** Use this to get a value from the finecosine table. It will be automatically shifted, - * Equivalent to finecosine[angle>>>ANGLETOFINESHIFT] - * @param angle in BAM units - * @return - */ -public static final int finecosine(int angle){ - return finecosine[angle>>>ANGLETOFINESHIFT]; -} + /** Use this to get a value from the finecosine table. It will be automatically shifted, + * Equivalent to finecosine[angle>>>ANGLETOFINESHIFT] + * @param angle in BAM units + * @return + */ + public static final int finecosine(int angle) { + return finecosine[angle >>> ANGLETOFINESHIFT]; + } -/** Use this to get a value from the finecosine table. - * It will automatically shift, apply rollover module and cast. - * - * Equivalent to finecosine[(int) ((angle&BITS32)>>>ANGLETOFINESHIFT)] - * @param angle in BAM units - * @return - */ -public static final int finecosine(long angle){ - return finecosine[(int) ((angle&BITS32)>>>ANGLETOFINESHIFT)]; -} + /** Use this to get a value from the finecosine table. + * It will automatically shift, apply rollover module and cast. + * + * Equivalent to finecosine[(int) ((angle&BITS32)>>>ANGLETOFINESHIFT)] + * @param angle in BAM units + * @return + */ + public static final int finecosine(long angle) { + return finecosine[(int) ((angle & BITS32) >>> ANGLETOFINESHIFT)]; + } -/** Compare BAM angles in 32-bit format - * "Greater or Equal" bam0>bam1 - * */ + /** Compare BAM angles in 32-bit format + * "Greater or Equal" bam0>bam1 + * */ + public static final boolean GE(int bam0, int bam1) { + // Handle easy case. + if (bam0 == bam1) { + return true; + } -public static final boolean GE(int bam0, int bam1){ - // Handle easy case. - if (bam0==bam1) return true; - - // bam0 is greater than 180 degrees. - if (bam0<0 && bam1>=0) return true; - // bam1 is greater than 180 degrees. - if (bam0>=0 && bam1<0) return false; - - // Both "greater than 180", No other way to compare. - bam0&=BITS31; - bam1&=BITS31; - return bam0>bam1; -} + // bam0 is greater than 180 degrees. + if (bam0 < 0 && bam1 >= 0) { + return true; + } + // bam1 is greater than 180 degrees. + if (bam0 >= 0 && bam1 < 0) { + return false; + } -public static final boolean GT(int bam0, int bam1){ - // bam0 is greater than 180 degrees. - if (bam0<0 && bam1>=0) return true; - // bam1 is greater than 180 degrees. - if (bam0>=0 && bam1<0) return false; - - // Both "greater than 180", No other way to compare. - bam0&=BITS31; - bam1&=BITS31; - return bam0>bam1; -} + // Both "greater than 180", No other way to compare. + bam0 &= BITS31; + bam1 &= BITS31; + return bam0 > bam1; + } -public static final int BAMDiv(int bam0, int bam1){ - // bam0 is greater than 180 degrees. - if (bam0>=0) return bam0/bam1; - // bam0 is greater than 180 degrees. - // We have to make is so that ANG270 0xC0000000 becomes ANG135, aka 60000000 - if (bam1>=0) - return (int) ((long)(0x0FFFFFFFFL&bam0)/bam1); - - return (int) ((long)(0x0FFFFFFFFL&bam0)/(0x0FFFFFFFFL&bam1)); -} + public static final boolean GT(int bam0, int bam1) { + // bam0 is greater than 180 degrees. + if (bam0 < 0 && bam1 >= 0) { + return true; + } + // bam1 is greater than 180 degrees. + if (bam0 >= 0 && bam1 < 0) { + return false; + } -/** Converts a long angle to a BAM LUT-ready angle (13 bits, between 0-8191). - * Cuts away rollover. - * - * @param angle - * @return - */ + // Both "greater than 180", No other way to compare. + bam0 &= BITS31; + bam1 &= BITS31; + return bam0 > bam1; + } -public static final int toBAMIndex(long angle){ - return (int) ((angle&BITS32)>>>ANGLETOFINESHIFT); -} + public static final int BAMDiv(int bam0, int bam1) { + // bam0 is greater than 180 degrees. + if (bam0 >= 0) { + return bam0 / bam1; + } + // bam0 is greater than 180 degrees. + // We have to make is so that ANG270 0xC0000000 becomes ANG135, aka 60000000 + if (bam1 >= 0) { + return (int) ((long) (0x0FFFFFFFFL & bam0) / bam1); + } -/** Converts a long angle to a TAN BAM LUT-ready angle (12 bits, between 0-4195). - * Cuts away rollover. - * - * @param angle - * @return - */ + return (int) ((long) (0x0FFFFFFFFL & bam0) / (0x0FFFFFFFFL & bam1)); + } -public static final int toFineTanIndex(long angle){ - return (int) ((angle&BITS31)>>>ANGLETOFINESHIFT); -} + /** Converts a long angle to a BAM LUT-ready angle (13 bits, between 0-8191). + * Cuts away rollover. + * + * @param angle + * @return + */ + public static final int toBAMIndex(long angle) { + return (int) ((angle & BITS32) >>> ANGLETOFINESHIFT); + } -/** Converts an 32-bit int angle to a BAM LUT-ready angle (13 bits, between 0-8192). - * - * @param angle - * @return - */ + /** Converts a long angle to a TAN BAM LUT-ready angle (12 bits, between 0-4195). + * Cuts away rollover. + * + * @param angle + * @return + */ + public static final int toFineTanIndex(long angle) { + return (int) ((angle & BITS31) >>> ANGLETOFINESHIFT); + } -public static final int toBAMIndex(int angle){ - return angle>>>ANGLETOFINESHIFT; -} + /** Converts an 32-bit int angle to a BAM LUT-ready angle (13 bits, between 0-8192). + * + * @param angle + * @return + */ + public static final int toBAMIndex(int angle) { + return angle >>> ANGLETOFINESHIFT; + } -/** Add two long angles and correct for overflow */ + /** Add two long angles and correct for overflow */ + public static final long addAngles(long a, long b) { + return ((a + b) & BITS32); + } -public static final long addAngles(long a, long b) { - return ((a+b)&BITS32); -} + /** MAES: I brought this function "back from the dead" since + * Java has some pretty low static limits for statically defined LUTs. + * In order to keep the codebase clutter and static allocation to a minimum, + * I decided to procedurally generate the tables during runtime, + * using the original functions. + * + * The code has been thoroughly checked in both Sun's JDK and GCC and was + * found to, indeed, produce the same values found in the finesine/finecosine + * and finetangent tables, at least on Intel. + * + * The "tantoangle" table is also generated procedurally, but since there + * was no "dead code" to build upon, it was recreated through reverse + * engineering and also found to be 100% faithful to the original data. + * + * + */ + public static void InitTables() { + int i; + float a; + float fv; + int t; + + // viewangle tangent table + for (i = 0; i < FINEANGLES / 2; i++) { + a = (float) ((i - FINEANGLES / 4 + 0.5) * PI * 2) / FINEANGLES; + fv = (float) (FRACUNIT * Math.tan(a)); + t = (int) fv; + finetangent[i] = t; + } -/** MAES: I brought this function "back from the dead" since - * Java has some pretty low static limits for statically defined LUTs. - * In order to keep the codebase clutter and static allocation to a minimum, - * I decided to procedurally generate the tables during runtime, - * using the original functions. - * - * The code has been thoroughly checked in both Sun's JDK and GCC and was - * found to, indeed, produce the same values found in the finesine/finecosine - * and finetangent tables, at least on Intel. - * - * The "tantoangle" table is also generated procedurally, but since there - * was no "dead code" to build upon, it was recreated through reverse - * engineering and also found to be 100% faithful to the original data. - * - * - */ + // finesine table + for (i = 0; i < FINEANGLES + QUARTERMARK; i++) { + // OPTIMIZE: mirror... + a = (float) ((i + 0.5) * PI * 2) / FINEANGLES; + t = (int) (FRACUNIT * Math.sin(a)); + finesine[i] = t; + if (i >= QUARTERMARK) { + finecosine[i - QUARTERMARK] = t; + } + } -public static void InitTables(){ - int i; - float a; - float fv; - int t; - - // viewangle tangent table - for (i=0 ; i=QUARTERMARK){ - finecosine[i-QUARTERMARK] = t; + // HACK: replicate part of finesine after finetangent, to + // simulate overflow behavior and remove need for capping + // indexes + // viewangle tangent table + for (i = FINEANGLES / 2; i < FINEANGLES; i++) { + finetangent[i] = finesine[i - FINEANGLES / 2]; } - } - - // HACK: replicate part of finesine after finetangent, to - // simulate overflow behavior and remove need for capping - // indexes - // viewangle tangent table - for (i=FINEANGLES/2 ; i 0, then it is in use) - public int usefulness; - - // lump number of sfx - public int lumpnum; - - public sfxinfo_t(String name, boolean singularity, int priority, - sfxinfo_t link, int pitch, int volume, byte[] data, - int usefulness, int lumpnum) { - this.name = name; - this.singularity = singularity; - this.priority = priority; - this.link = link; - this.pitch = pitch; - this.volume = volume; - this.data = data; - this.usefulness = usefulness; - this.lumpnum = lumpnum; - } - - /** MAES: Call this constructor if you don't want a cross-linked sound. - * - * @param name - * @param singularity - * @param priority - * @param pitch - * @param volume - * @param usefulness - */ - - public sfxinfo_t(String name, boolean singularity, int priority, - int pitch, int volume, int usefulness) { - this.name = name; - this.singularity = singularity; - this.priority = priority; - this.linked = false; - this.pitch = pitch; - this.volume = volume; - this.usefulness = usefulness; - } - - public sfxinfo_t(String name, boolean singularity, int priority, boolean linked, - int pitch, int volume, int usefulness) { - this.name = name; - this.singularity = singularity; - this.priority = priority; - this.linked = linked; - this.pitch = pitch; - this.volume = volume; - this.usefulness = usefulness; + public sfxinfo_t() { + + } + + /** up to 6-character name */ + public String name; + + /** Sfx singularity (only one at a time) */ + public boolean singularity; + + /** Sfx priority */ + public int priority; + + // referenced sound if a link + // MAES: since in pure hackish C style, a "0" value would be used as a boolean, we'll need to distinguish more + // unambiguously. So for querying, look at the "linked" boolean or a getter. + public boolean linked; + + public sfxinfo_t link; + + public sfxinfo_t getLink() { + if (linked) { + return link; + } else { + return null; } - - public int identify(sfxinfo_t[] array){ - for (int i=0;i 0, then it is in use) + public int usefulness; + + // lump number of sfx + public int lumpnum; + + public sfxinfo_t(String name, boolean singularity, int priority, + sfxinfo_t link, int pitch, int volume, byte[] data, + int usefulness, int lumpnum) { + this.name = name; + this.singularity = singularity; + this.priority = priority; + this.link = link; + this.pitch = pitch; + this.volume = volume; + this.data = data; + this.usefulness = usefulness; + this.lumpnum = lumpnum; + } + + /** MAES: Call this constructor if you don't want a cross-linked sound. + * + * @param name + * @param singularity + * @param priority + * @param pitch + * @param volume + * @param usefulness + */ + public sfxinfo_t(String name, boolean singularity, int priority, + int pitch, int volume, int usefulness) { + this.name = name; + this.singularity = singularity; + this.priority = priority; + this.linked = false; + this.pitch = pitch; + this.volume = volume; + this.usefulness = usefulness; + } + + public sfxinfo_t(String name, boolean singularity, int priority, boolean linked, + int pitch, int volume, int usefulness) { + this.name = name; + this.singularity = singularity; + this.priority = priority; + this.linked = linked; + this.pitch = pitch; + this.volume = volume; + this.usefulness = usefulness; + } + + public int identify(sfxinfo_t[] array) { + for (int i = 0; i < array.length; i++) { + if (array[i] == this) { + return i; + } } - - }; + // Duh + return 0; + } + +}; diff --git a/src/data/sounds.java b/src/data/sounds.java index 7f24d54b..c32e28c3 100644 --- a/src/data/sounds.java +++ b/src/data/sounds.java @@ -37,416 +37,406 @@ // //----------------------------------------------------------------------------- -public class sounds{ +public class sounds { // // Information about all the music // - -public static musicinfo_t[] S_music= -{ - new musicinfo_t(null), - new musicinfo_t( "e1m1", 0 ), - new musicinfo_t( "e1m2", 0 ), - new musicinfo_t( "e1m3", 0 ), - new musicinfo_t( "e1m4", 0 ), - new musicinfo_t( "e1m5", 0 ), - new musicinfo_t( "e1m6", 0 ), - new musicinfo_t( "e1m7", 0 ), - new musicinfo_t( "e1m8", 0 ), - new musicinfo_t( "e1m9", 0 ), - new musicinfo_t( "e2m1", 0 ), - new musicinfo_t( "e2m2", 0 ), - new musicinfo_t( "e2m3", 0 ), - new musicinfo_t( "e2m4", 0 ), - new musicinfo_t( "e2m5", 0 ), - new musicinfo_t( "e2m6", 0 ), - new musicinfo_t( "e2m7", 0 ), - new musicinfo_t( "e2m8", 0 ), - new musicinfo_t( "e2m9", 0 ), - new musicinfo_t( "e3m1", 0 ), - new musicinfo_t( "e3m2", 0 ), - new musicinfo_t( "e3m3", 0 ), - new musicinfo_t( "e3m4", 0 ), - new musicinfo_t( "e3m5", 0 ), - new musicinfo_t( "e3m6", 0 ), - new musicinfo_t( "e3m7", 0 ), - new musicinfo_t( "e3m8", 0 ), - new musicinfo_t( "e3m9", 0 ), - new musicinfo_t( "inter", 0 ), - new musicinfo_t( "intro", 0 ), - new musicinfo_t( "bunny", 0 ), - new musicinfo_t( "victor", 0 ), - new musicinfo_t( "introa", 0 ), - new musicinfo_t( "runnin", 0 ), - new musicinfo_t( "stalks", 0 ), - new musicinfo_t( "countd", 0 ), - new musicinfo_t( "betwee", 0 ), - new musicinfo_t( "doom", 0 ), - new musicinfo_t( "the_da", 0 ), - new musicinfo_t( "shawn", 0 ), - new musicinfo_t( "ddtblu", 0 ), - new musicinfo_t( "in_cit", 0 ), - new musicinfo_t( "dead", 0 ), - new musicinfo_t( "stlks2", 0 ), - new musicinfo_t( "theda2", 0 ), - new musicinfo_t( "doom2", 0 ), - new musicinfo_t( "ddtbl2", 0 ), - new musicinfo_t( "runni2", 0 ), - new musicinfo_t( "dead2", 0 ), - new musicinfo_t( "stlks3", 0 ), - new musicinfo_t( "romero", 0 ), - new musicinfo_t( "shawn2", 0 ), - new musicinfo_t( "messag", 0 ), - new musicinfo_t( "count2", 0 ), - new musicinfo_t( "ddtbl3", 0 ), - new musicinfo_t( "ampie", 0 ), - new musicinfo_t( "theda3", 0 ), - new musicinfo_t( "adrian", 0 ), - new musicinfo_t( "messg2", 0 ), - new musicinfo_t( "romer2", 0 ), - new musicinfo_t( "tense", 0 ), - new musicinfo_t( "shawn3", 0 ), - new musicinfo_t( "openin", 0 ), - new musicinfo_t( "evil", 0 ), - new musicinfo_t( "ultima", 0 ), - new musicinfo_t( "read_m", 0 ), - new musicinfo_t( "dm2ttl", 0 ), - new musicinfo_t( "dm2int", 0 ) -}; - + public static musicinfo_t[] S_music + = { + new musicinfo_t(null), + new musicinfo_t("e1m1", 0), + new musicinfo_t("e1m2", 0), + new musicinfo_t("e1m3", 0), + new musicinfo_t("e1m4", 0), + new musicinfo_t("e1m5", 0), + new musicinfo_t("e1m6", 0), + new musicinfo_t("e1m7", 0), + new musicinfo_t("e1m8", 0), + new musicinfo_t("e1m9", 0), + new musicinfo_t("e2m1", 0), + new musicinfo_t("e2m2", 0), + new musicinfo_t("e2m3", 0), + new musicinfo_t("e2m4", 0), + new musicinfo_t("e2m5", 0), + new musicinfo_t("e2m6", 0), + new musicinfo_t("e2m7", 0), + new musicinfo_t("e2m8", 0), + new musicinfo_t("e2m9", 0), + new musicinfo_t("e3m1", 0), + new musicinfo_t("e3m2", 0), + new musicinfo_t("e3m3", 0), + new musicinfo_t("e3m4", 0), + new musicinfo_t("e3m5", 0), + new musicinfo_t("e3m6", 0), + new musicinfo_t("e3m7", 0), + new musicinfo_t("e3m8", 0), + new musicinfo_t("e3m9", 0), + new musicinfo_t("inter", 0), + new musicinfo_t("intro", 0), + new musicinfo_t("bunny", 0), + new musicinfo_t("victor", 0), + new musicinfo_t("introa", 0), + new musicinfo_t("runnin", 0), + new musicinfo_t("stalks", 0), + new musicinfo_t("countd", 0), + new musicinfo_t("betwee", 0), + new musicinfo_t("doom", 0), + new musicinfo_t("the_da", 0), + new musicinfo_t("shawn", 0), + new musicinfo_t("ddtblu", 0), + new musicinfo_t("in_cit", 0), + new musicinfo_t("dead", 0), + new musicinfo_t("stlks2", 0), + new musicinfo_t("theda2", 0), + new musicinfo_t("doom2", 0), + new musicinfo_t("ddtbl2", 0), + new musicinfo_t("runni2", 0), + new musicinfo_t("dead2", 0), + new musicinfo_t("stlks3", 0), + new musicinfo_t("romero", 0), + new musicinfo_t("shawn2", 0), + new musicinfo_t("messag", 0), + new musicinfo_t("count2", 0), + new musicinfo_t("ddtbl3", 0), + new musicinfo_t("ampie", 0), + new musicinfo_t("theda3", 0), + new musicinfo_t("adrian", 0), + new musicinfo_t("messg2", 0), + new musicinfo_t("romer2", 0), + new musicinfo_t("tense", 0), + new musicinfo_t("shawn3", 0), + new musicinfo_t("openin", 0), + new musicinfo_t("evil", 0), + new musicinfo_t("ultima", 0), + new musicinfo_t("read_m", 0), + new musicinfo_t("dm2ttl", 0), + new musicinfo_t("dm2int", 0) + }; // // Information about all the sfx // + public static sfxinfo_t nullSfxLink; -public static sfxinfo_t nullSfxLink; - -public static sfxinfo_t[] S_sfx = -{ - // S_sfx[0] needs to be a dummy for odd reasons. - new sfxinfo_t( "none", false, 0, -1, -1, 0 ), - - new sfxinfo_t( "pistol", false, 64, -1, -1, 0 ), - new sfxinfo_t( "shotgn", false, 64, -1, -1, 0 ), - new sfxinfo_t( "sgcock", false, 64, -1, -1, 0 ), - new sfxinfo_t( "dshtgn", false, 64, -1, -1, 0 ), - new sfxinfo_t( "dbopn", false, 64, -1, -1, 0 ), - new sfxinfo_t( "dbcls", false, 64, -1, -1, 0 ), - new sfxinfo_t( "dbload", false, 64, -1, -1, 0 ), - new sfxinfo_t( "plasma", false, 64, -1, -1, 0 ), - new sfxinfo_t( "bfg", false, 64, -1, -1, 0 ), - new sfxinfo_t( "sawup", false, 64, -1, -1, 0 ), - new sfxinfo_t( "sawidl", false, 118, -1, -1, 0 ), - new sfxinfo_t( "sawful", false, 64, -1, -1, 0 ), - new sfxinfo_t( "sawhit", false, 64, -1, -1, 0 ), - new sfxinfo_t( "rlaunc", false, 64, -1, -1, 0 ), - new sfxinfo_t( "rxplod", false, 70, -1, -1, 0 ), - new sfxinfo_t( "firsht", false, 70, -1, -1, 0 ), - new sfxinfo_t( "firxpl", false, 70, -1, -1, 0 ), - new sfxinfo_t( "pstart", false, 100, -1, -1, 0 ), - new sfxinfo_t( "pstop", false, 100, -1, -1, 0 ), - new sfxinfo_t( "doropn", false, 100, -1, -1, 0 ), - new sfxinfo_t( "dorcls", false, 100, -1, -1, 0 ), - new sfxinfo_t( "stnmov", false, 119, -1, -1, 0 ), - new sfxinfo_t( "swtchn", false, 78, -1, -1, 0 ), - new sfxinfo_t( "swtchx", false, 78, -1, -1, 0 ), - new sfxinfo_t( "plpain", false, 96, -1, -1, 0 ), - new sfxinfo_t( "dmpain", false, 96, -1, -1, 0 ), - new sfxinfo_t( "popain", false, 96, -1, -1, 0 ), - new sfxinfo_t( "vipain", false, 96, -1, -1, 0 ), - new sfxinfo_t( "mnpain", false, 96, -1, -1, 0 ), - new sfxinfo_t( "pepain", false, 96, -1, -1, 0 ), - new sfxinfo_t( "slop", false, 78, -1, -1, 0 ), - new sfxinfo_t( "itemup", true, 78, -1, -1, 0 ), - new sfxinfo_t( "wpnup", true, 78, -1, -1, 0 ), - new sfxinfo_t( "oof", false, 96, -1, -1, 0 ), - new sfxinfo_t( "telept", false, 32, -1, -1, 0 ), - new sfxinfo_t( "posit1", true, 98, -1, -1, 0 ), - new sfxinfo_t( "posit2", true, 98, -1, -1, 0 ), - new sfxinfo_t( "posit3", true, 98, -1, -1, 0 ), - new sfxinfo_t( "bgsit1", true, 98, -1, -1, 0 ), - new sfxinfo_t( "bgsit2", true, 98, -1, -1, 0 ), - new sfxinfo_t( "sgtsit", true, 98, -1, -1, 0 ), - new sfxinfo_t( "cacsit", true, 98, -1, -1, 0 ), - new sfxinfo_t( "brssit", true, 94, -1, -1, 0 ), - new sfxinfo_t( "cybsit", true, 92, -1, -1, 0 ), - new sfxinfo_t( "spisit", true, 90, -1, -1, 0 ), - new sfxinfo_t( "bspsit", true, 90, -1, -1, 0 ), - new sfxinfo_t( "kntsit", true, 90, -1, -1, 0 ), - new sfxinfo_t( "vilsit", true, 90, -1, -1, 0 ), - new sfxinfo_t( "mansit", true, 90, -1, -1, 0 ), - new sfxinfo_t( "pesit", true, 90, -1, -1, 0 ), - new sfxinfo_t( "sklatk", false, 70, -1, -1, 0 ), - new sfxinfo_t( "sgtatk", false, 70, -1, -1, 0 ), - new sfxinfo_t( "skepch", false, 70, -1, -1, 0 ), - new sfxinfo_t( "vilatk", false, 70, -1, -1, 0 ), - new sfxinfo_t( "claw", false, 70, -1, -1, 0 ), - new sfxinfo_t( "skeswg", false, 70, -1, -1, 0 ), - new sfxinfo_t( "pldeth", false, 32, -1, -1, 0 ), - new sfxinfo_t( "pdiehi", false, 32, -1, -1, 0 ), - new sfxinfo_t( "podth1", false, 70, -1, -1, 0 ), - new sfxinfo_t( "podth2", false, 70, -1, -1, 0 ), - new sfxinfo_t( "podth3", false, 70, -1, -1, 0 ), - new sfxinfo_t( "bgdth1", false, 70, -1, -1, 0 ), - new sfxinfo_t( "bgdth2", false, 70, -1, -1, 0 ), - new sfxinfo_t( "sgtdth", false, 70, -1, -1, 0 ), - new sfxinfo_t( "cacdth", false, 70, -1, -1, 0 ), - new sfxinfo_t( "skldth", false, 70, -1, -1, 0 ), - new sfxinfo_t( "brsdth", false, 32, -1, -1, 0 ), - new sfxinfo_t( "cybdth", false, 32, -1, -1, 0 ), - new sfxinfo_t( "spidth", false, 32, -1, -1, 0 ), - new sfxinfo_t( "bspdth", false, 32, -1, -1, 0 ), - new sfxinfo_t( "vildth", false, 32, -1, -1, 0 ), - new sfxinfo_t( "kntdth", false, 32, -1, -1, 0 ), - new sfxinfo_t( "pedth", false, 32, -1, -1, 0 ), - new sfxinfo_t( "skedth", false, 32, -1, -1, 0 ), - new sfxinfo_t( "posact", true, 120, -1, -1, 0 ), - new sfxinfo_t( "bgact", true, 120, -1, -1, 0 ), - new sfxinfo_t( "dmact", true, 120, -1, -1, 0 ), - new sfxinfo_t( "bspact", true, 100, -1, -1, 0 ), - new sfxinfo_t( "bspwlk", true, 100, -1, -1, 0 ), - new sfxinfo_t( "vilact", true, 100, -1, -1, 0 ), - new sfxinfo_t( "noway", false, 78, -1, -1, 0 ), - new sfxinfo_t( "barexp", false, 60, -1, -1, 0 ), - new sfxinfo_t( "punch", false, 64, -1, -1, 0 ), - new sfxinfo_t( "hoof", false, 70, -1, -1, 0 ), - new sfxinfo_t( "metal", false, 70, -1, -1, 0 ), - // MAES: here C referenced a field before it was defined. - // We'll make do by defining a new "linked" boolean field, and - // handling special cases in a separate initializer. - new sfxinfo_t( "chgun", false, 64, true, 150, 0, 0 ), - new sfxinfo_t( "tink", false, 60, -1, -1, 0 ), - new sfxinfo_t( "bdopn", false, 100, -1, -1, 0 ), - new sfxinfo_t( "bdcls", false, 100, -1, -1, 0 ), - new sfxinfo_t( "itmbk", false, 100, -1, -1, 0 ), - new sfxinfo_t( "flame", false, 32, -1, -1, 0 ), - new sfxinfo_t( "flamst", false, 32, -1, -1, 0 ), - new sfxinfo_t( "getpow", false, 60, -1, -1, 0 ), - new sfxinfo_t( "bospit", false, 70, -1, -1, 0 ), - new sfxinfo_t( "boscub", false, 70, -1, -1, 0 ), - new sfxinfo_t( "bossit", false, 70, -1, -1, 0 ), - new sfxinfo_t( "bospn", false, 70, -1, -1, 0 ), - new sfxinfo_t( "bosdth", false, 70, -1, -1, 0 ), - new sfxinfo_t( "manatk", false, 70, -1, -1, 0 ), - new sfxinfo_t( "mandth", false, 70, -1, -1, 0 ), - new sfxinfo_t( "sssit", false, 70, -1, -1, 0 ), - new sfxinfo_t( "ssdth", false, 70, -1, -1, 0 ), - new sfxinfo_t( "keenpn", false, 70, -1, -1, 0 ), - new sfxinfo_t( "keendt", false, 70, -1, -1, 0 ), - new sfxinfo_t( "skeact", false, 70, -1, -1, 0 ), - new sfxinfo_t( "skesit", false, 70, -1, -1, 0 ), - new sfxinfo_t( "skeatk", false, 70, -1, -1, 0 ), - new sfxinfo_t( "radio", false, 60, -1, -1, 0 ) -}; - -/** MAES: This method is here to handle exceptions in definitions of static sfx. - * Only the chaingun sound needs to be cross-linked to the pistol sound, but in - * Java you can't do that until the array is actually created. So remember to run - * this explicitly, and add any further rules you want! - * - */ + public static sfxinfo_t[] S_sfx + = { + // S_sfx[0] needs to be a dummy for odd reasons. + new sfxinfo_t("none", false, 0, -1, -1, 0), + new sfxinfo_t("pistol", false, 64, -1, -1, 0), + new sfxinfo_t("shotgn", false, 64, -1, -1, 0), + new sfxinfo_t("sgcock", false, 64, -1, -1, 0), + new sfxinfo_t("dshtgn", false, 64, -1, -1, 0), + new sfxinfo_t("dbopn", false, 64, -1, -1, 0), + new sfxinfo_t("dbcls", false, 64, -1, -1, 0), + new sfxinfo_t("dbload", false, 64, -1, -1, 0), + new sfxinfo_t("plasma", false, 64, -1, -1, 0), + new sfxinfo_t("bfg", false, 64, -1, -1, 0), + new sfxinfo_t("sawup", false, 64, -1, -1, 0), + new sfxinfo_t("sawidl", false, 118, -1, -1, 0), + new sfxinfo_t("sawful", false, 64, -1, -1, 0), + new sfxinfo_t("sawhit", false, 64, -1, -1, 0), + new sfxinfo_t("rlaunc", false, 64, -1, -1, 0), + new sfxinfo_t("rxplod", false, 70, -1, -1, 0), + new sfxinfo_t("firsht", false, 70, -1, -1, 0), + new sfxinfo_t("firxpl", false, 70, -1, -1, 0), + new sfxinfo_t("pstart", false, 100, -1, -1, 0), + new sfxinfo_t("pstop", false, 100, -1, -1, 0), + new sfxinfo_t("doropn", false, 100, -1, -1, 0), + new sfxinfo_t("dorcls", false, 100, -1, -1, 0), + new sfxinfo_t("stnmov", false, 119, -1, -1, 0), + new sfxinfo_t("swtchn", false, 78, -1, -1, 0), + new sfxinfo_t("swtchx", false, 78, -1, -1, 0), + new sfxinfo_t("plpain", false, 96, -1, -1, 0), + new sfxinfo_t("dmpain", false, 96, -1, -1, 0), + new sfxinfo_t("popain", false, 96, -1, -1, 0), + new sfxinfo_t("vipain", false, 96, -1, -1, 0), + new sfxinfo_t("mnpain", false, 96, -1, -1, 0), + new sfxinfo_t("pepain", false, 96, -1, -1, 0), + new sfxinfo_t("slop", false, 78, -1, -1, 0), + new sfxinfo_t("itemup", true, 78, -1, -1, 0), + new sfxinfo_t("wpnup", true, 78, -1, -1, 0), + new sfxinfo_t("oof", false, 96, -1, -1, 0), + new sfxinfo_t("telept", false, 32, -1, -1, 0), + new sfxinfo_t("posit1", true, 98, -1, -1, 0), + new sfxinfo_t("posit2", true, 98, -1, -1, 0), + new sfxinfo_t("posit3", true, 98, -1, -1, 0), + new sfxinfo_t("bgsit1", true, 98, -1, -1, 0), + new sfxinfo_t("bgsit2", true, 98, -1, -1, 0), + new sfxinfo_t("sgtsit", true, 98, -1, -1, 0), + new sfxinfo_t("cacsit", true, 98, -1, -1, 0), + new sfxinfo_t("brssit", true, 94, -1, -1, 0), + new sfxinfo_t("cybsit", true, 92, -1, -1, 0), + new sfxinfo_t("spisit", true, 90, -1, -1, 0), + new sfxinfo_t("bspsit", true, 90, -1, -1, 0), + new sfxinfo_t("kntsit", true, 90, -1, -1, 0), + new sfxinfo_t("vilsit", true, 90, -1, -1, 0), + new sfxinfo_t("mansit", true, 90, -1, -1, 0), + new sfxinfo_t("pesit", true, 90, -1, -1, 0), + new sfxinfo_t("sklatk", false, 70, -1, -1, 0), + new sfxinfo_t("sgtatk", false, 70, -1, -1, 0), + new sfxinfo_t("skepch", false, 70, -1, -1, 0), + new sfxinfo_t("vilatk", false, 70, -1, -1, 0), + new sfxinfo_t("claw", false, 70, -1, -1, 0), + new sfxinfo_t("skeswg", false, 70, -1, -1, 0), + new sfxinfo_t("pldeth", false, 32, -1, -1, 0), + new sfxinfo_t("pdiehi", false, 32, -1, -1, 0), + new sfxinfo_t("podth1", false, 70, -1, -1, 0), + new sfxinfo_t("podth2", false, 70, -1, -1, 0), + new sfxinfo_t("podth3", false, 70, -1, -1, 0), + new sfxinfo_t("bgdth1", false, 70, -1, -1, 0), + new sfxinfo_t("bgdth2", false, 70, -1, -1, 0), + new sfxinfo_t("sgtdth", false, 70, -1, -1, 0), + new sfxinfo_t("cacdth", false, 70, -1, -1, 0), + new sfxinfo_t("skldth", false, 70, -1, -1, 0), + new sfxinfo_t("brsdth", false, 32, -1, -1, 0), + new sfxinfo_t("cybdth", false, 32, -1, -1, 0), + new sfxinfo_t("spidth", false, 32, -1, -1, 0), + new sfxinfo_t("bspdth", false, 32, -1, -1, 0), + new sfxinfo_t("vildth", false, 32, -1, -1, 0), + new sfxinfo_t("kntdth", false, 32, -1, -1, 0), + new sfxinfo_t("pedth", false, 32, -1, -1, 0), + new sfxinfo_t("skedth", false, 32, -1, -1, 0), + new sfxinfo_t("posact", true, 120, -1, -1, 0), + new sfxinfo_t("bgact", true, 120, -1, -1, 0), + new sfxinfo_t("dmact", true, 120, -1, -1, 0), + new sfxinfo_t("bspact", true, 100, -1, -1, 0), + new sfxinfo_t("bspwlk", true, 100, -1, -1, 0), + new sfxinfo_t("vilact", true, 100, -1, -1, 0), + new sfxinfo_t("noway", false, 78, -1, -1, 0), + new sfxinfo_t("barexp", false, 60, -1, -1, 0), + new sfxinfo_t("punch", false, 64, -1, -1, 0), + new sfxinfo_t("hoof", false, 70, -1, -1, 0), + new sfxinfo_t("metal", false, 70, -1, -1, 0), + // MAES: here C referenced a field before it was defined. + // We'll make do by defining a new "linked" boolean field, and + // handling special cases in a separate initializer. + new sfxinfo_t("chgun", false, 64, true, 150, 0, 0), + new sfxinfo_t("tink", false, 60, -1, -1, 0), + new sfxinfo_t("bdopn", false, 100, -1, -1, 0), + new sfxinfo_t("bdcls", false, 100, -1, -1, 0), + new sfxinfo_t("itmbk", false, 100, -1, -1, 0), + new sfxinfo_t("flame", false, 32, -1, -1, 0), + new sfxinfo_t("flamst", false, 32, -1, -1, 0), + new sfxinfo_t("getpow", false, 60, -1, -1, 0), + new sfxinfo_t("bospit", false, 70, -1, -1, 0), + new sfxinfo_t("boscub", false, 70, -1, -1, 0), + new sfxinfo_t("bossit", false, 70, -1, -1, 0), + new sfxinfo_t("bospn", false, 70, -1, -1, 0), + new sfxinfo_t("bosdth", false, 70, -1, -1, 0), + new sfxinfo_t("manatk", false, 70, -1, -1, 0), + new sfxinfo_t("mandth", false, 70, -1, -1, 0), + new sfxinfo_t("sssit", false, 70, -1, -1, 0), + new sfxinfo_t("ssdth", false, 70, -1, -1, 0), + new sfxinfo_t("keenpn", false, 70, -1, -1, 0), + new sfxinfo_t("keendt", false, 70, -1, -1, 0), + new sfxinfo_t("skeact", false, 70, -1, -1, 0), + new sfxinfo_t("skesit", false, 70, -1, -1, 0), + new sfxinfo_t("skeatk", false, 70, -1, -1, 0), + new sfxinfo_t("radio", false, 60, -1, -1, 0) + }; -public static void init(){ - for (int i=0;i. */ - package defines; import doom.DoomMain; import java.util.logging.Level; +import java.util.logging.Logger; import mochadoom.Loggers; import utils.C2JUtils; import static utils.C2JUtils.testReadAccess; @@ -36,20 +36,22 @@ public enum DoomVersion { FREEDM_WAD("freedm.wad"), FREEDOOM1_WAD("freedoom1.wad"), FREEDOOM2_WAD("freedoom2.wad"); - + public final String wadFileName; private DoomVersion(String wadFileName) { this.wadFileName = wadFileName; } - - /** + + private static final Logger LOGGER = Loggers.getLogger(DoomVersion.class.getName()); + + /** * Try all versions in given doomwaddir * * @return full path to the wad of success - */ + */ public static String tryAllWads(final DoomMain DOOM, final String doomwaddir) { - for (DoomVersion v: values()) { + for (DoomVersion v : values()) { final String vFullPath = doomwaddir + '/' + v.wadFileName; if (testReadAccess(vFullPath)) { DOOM.setGameMode(GameMode.forVersion(v)); @@ -57,40 +59,40 @@ public static String tryAllWads(final DoomMain DOOM, final String doomwadd // C'est ridicule! // Let's handle languages in config files, okay? DOOM.language = Language_t.french; - System.out.println("French version\n"); + //System.out.println("French version\n"); } - + return vFullPath; } } - + return null; } - - /** + + /** * Try only one IWAD. - * - * @param iwad + * + * @param iwad * @param doomwaddir - * @return game mode - */ - public static GameMode tryOnlyOne(String iwad, String doomwaddir) { + * @return game mode + */ + public static GameMode tryOnlyOne(String iwad, String doomwaddir) { try { // Is it a known and valid version? final DoomVersion v = DoomVersion.valueOf(iwad.trim().toUpperCase().replace('.', '_')); final GameMode tmp = GameMode.forVersion(v); - + // Can we read it? if (tmp != null && C2JUtils.testReadAccess(doomwaddir + iwad)) { return tmp; // Yes, so communicate the gamemode back. } - + } catch (IllegalArgumentException ex) { - Loggers.getLogger(DoomVersion.class.getName()).log(Level.WARNING, iwad, ex); + LOGGER.log(Level.WARNING, iwad, ex); } - // It's either invalid or we can't read it. - // Fuck that. - return null; - } + // It's either invalid or we can't read it. + // Fuck that. + return null; + } } diff --git a/src/defines/GameMission_t.java b/src/defines/GameMission_t.java index e53bd847..d863b688 100644 --- a/src/defines/GameMission_t.java +++ b/src/defines/GameMission_t.java @@ -3,11 +3,10 @@ /** Mission packs - might be useful for TC stuff? * */ -public enum GameMission_t -{ - doom, // DOOM 1 - doom2, // DOOM 2 - pack_tnt, // TNT mission pack - pack_plut, // Plutonia pack - none +public enum GameMission_t { + doom, // DOOM 1 + doom2, // DOOM 2 + pack_tnt, // TNT mission pack + pack_plut, // Plutonia pack + none } diff --git a/src/defines/GameMode.java b/src/defines/GameMode.java index 18c19da3..33ea7dec 100644 --- a/src/defines/GameMode.java +++ b/src/defines/GameMode.java @@ -1,6 +1,17 @@ package defines; -import static defines.DoomVersion.*; +import static defines.DoomVersion.DOOM1_WAD; +import static defines.DoomVersion.DOOM2F_WAD; +import static defines.DoomVersion.DOOM2_WAD; +import static defines.DoomVersion.DOOMU_WAD; +import static defines.DoomVersion.DOOM_WAD; +import static defines.DoomVersion.FREEDM_WAD; +import static defines.DoomVersion.FREEDOOM1_WAD; +import static defines.DoomVersion.FREEDOOM2_WAD; +import static defines.DoomVersion.PLUTONIA_WAD; +import static defines.DoomVersion.TNT_WAD; +import static defines.DoomVersion.UDOOM_WAD; +import static defines.DoomVersion.XBLA_WAD; import doom.CommandVariable; /** @@ -19,13 +30,13 @@ public enum GameMode { freedoom1("data_se", FREEDOOM1_WAD, CommandVariable.FR1DEV), // Freedoom phase 1 freedoom2("cdata", FREEDOOM2_WAD, CommandVariable.FR2DEV), // Freedoom phase 2 indetermined("data_se", null, null); // Well, no IWAD found. - + public final String devDir; public final DoomVersion version; public final CommandVariable devVar; - + public static GameMode forVersion(DoomVersion v) { - switch(v) { + switch (v) { case DOOM1_WAD: return shareware; case DOOM2F_WAD: @@ -57,7 +68,7 @@ private GameMode(String devDir, DoomVersion version, CommandVariable devVar) { this.version = version; this.devVar = devVar; } - + public boolean hasTexture2() { return !(this == GameMode.shareware || this == GameMode.freedoom2 || this == GameMode.commercial); } diff --git a/src/defines/Language_t.java b/src/defines/Language_t.java index 69646fa5..8b911c97 100644 --- a/src/defines/Language_t.java +++ b/src/defines/Language_t.java @@ -6,5 +6,4 @@ public enum Language_t { french, german, unknown - } - +} diff --git a/src/defines/ammotype_t.java b/src/defines/ammotype_t.java index 1b9212a6..9a10fabe 100644 --- a/src/defines/ammotype_t.java +++ b/src/defines/ammotype_t.java @@ -1,13 +1,12 @@ package defines; //Ammunition types defined. -public enum ammotype_t -{ - am_clip, // Pistol / chaingun ammo. - am_shell, // Shotgun / double barreled shotgun. - am_cell, // Plasma rifle, BFG. - am_misl, // Missile launcher. +public enum ammotype_t { + am_clip, // Pistol / chaingun ammo. + am_shell, // Shotgun / double barreled shotgun. + am_cell, // Plasma rifle, BFG. + am_misl, // Missile launcher. NUMAMMO, am_noammo // Unlimited for chainsaw / fist. -} \ No newline at end of file +} diff --git a/src/defines/card_t.java b/src/defines/card_t.java index e534baaa..f0cf08ae 100644 --- a/src/defines/card_t.java +++ b/src/defines/card_t.java @@ -3,15 +3,13 @@ /** * Key cards. */ -public enum card_t -{ - it_bluecard, - it_yellowcard, - it_redcard, - it_blueskull, - it_yellowskull, - it_redskull, - - NUMCARDS - +public enum card_t { + it_bluecard, + it_yellowcard, + it_redcard, + it_blueskull, + it_yellowskull, + it_redskull, + NUMCARDS + } diff --git a/src/defines/gamestate_t.java b/src/defines/gamestate_t.java index 6419e243..ff031928 100644 --- a/src/defines/gamestate_t.java +++ b/src/defines/gamestate_t.java @@ -2,12 +2,11 @@ /** The current state of the game: whether we are playing, gazing at the intermission screen, - the game final animation, or a demo. */ -public enum gamestate_t -{ - GS_LEVEL, - GS_INTERMISSION, - GS_FINALE, - GS_DEMOSCREEN, - GS_MINUS_ONE // hack used for the "-1" state + the game final animation, or a demo. */ +public enum gamestate_t { + GS_LEVEL, + GS_INTERMISSION, + GS_FINALE, + GS_DEMOSCREEN, + GS_MINUS_ONE // hack used for the "-1" state } diff --git a/src/defines/skill_t.java b/src/defines/skill_t.java index 75e2cadd..08e49f1f 100644 --- a/src/defines/skill_t.java +++ b/src/defines/skill_t.java @@ -1,8 +1,6 @@ package defines; - -public enum skill_t -{ +public enum skill_t { sk_baby, sk_easy, sk_medium, diff --git a/src/defines/slopetype_t.java b/src/defines/slopetype_t.java index 6d92b922..86fbab74 100644 --- a/src/defines/slopetype_t.java +++ b/src/defines/slopetype_t.java @@ -1,12 +1,10 @@ package defines; /** Move clipping aid for LineDefs. */ +public enum slopetype_t { + ST_HORIZONTAL, + ST_VERTICAL, + ST_POSITIVE, + ST_NEGATIVE -public enum slopetype_t -{ -ST_HORIZONTAL, -ST_VERTICAL, -ST_POSITIVE, -ST_NEGATIVE - -} +} diff --git a/src/defines/statenum_t.java b/src/defines/statenum_t.java index 61961ab3..511a07d5 100644 --- a/src/defines/statenum_t.java +++ b/src/defines/statenum_t.java @@ -968,5 +968,5 @@ public enum statenum_t { S_TECH2LAMP2, S_TECH2LAMP3, S_TECH2LAMP4, - NUMSTATES -} \ No newline at end of file + NUMSTATES +} diff --git a/src/demo/IDemoTicCmd.java b/src/demo/IDemoTicCmd.java index 688e9169..996733ed 100644 --- a/src/demo/IDemoTicCmd.java +++ b/src/demo/IDemoTicCmd.java @@ -1,7 +1,7 @@ package demo; -import w.IWritableDoomObject; import doom.ticcmd_t; +import w.IWritableDoomObject; /** Demo Tic Commands can be read/written to disk/buffers, * and are not necessarily equal to the in-game ticcmd_t. @@ -11,18 +11,18 @@ * @author admin * */ +public interface IDemoTicCmd extends IWritableDoomObject { -public interface IDemoTicCmd extends IWritableDoomObject{ /** Decode this IDemoTicCmd into a standard ticcmd_t. * * @param source */ public void decode(ticcmd_t dest); - + /** Encode this IDemoTicCmd from a standard ticcmd_t. * * @param dest */ public void encode(ticcmd_t source); - + } diff --git a/src/demo/IDoomDemo.java b/src/demo/IDoomDemo.java index a4ab7297..ac9e2b6a 100644 --- a/src/demo/IDoomDemo.java +++ b/src/demo/IDoomDemo.java @@ -1,15 +1,13 @@ package demo; -import w.IWritableDoomObject; import defines.skill_t; +import w.IWritableDoomObject; + +public interface IDoomDemo extends IWritableDoomObject { -public interface IDoomDemo extends IWritableDoomObject{ - - /** Vanilla end demo marker, to append at the end of recorded demos */ - - public static final int DEMOMARKER =0x80; - + public static final int DEMOMARKER = 0x80; + /** Get next demo command, in its raw format. Use * its own adapters if you need it converted to a * standard ticcmd_t. @@ -17,7 +15,7 @@ public interface IDoomDemo extends IWritableDoomObject{ * @return */ IDemoTicCmd getNextTic(); - + /** Record a demo command in the IDoomDemo's native format. * Use the IDemoTicCmd's objects adaptors to convert it. * @@ -46,13 +44,13 @@ public interface IDoomDemo extends IWritableDoomObject{ void setDeathmatch(boolean deathmatch); boolean isRespawnparm(); - + void setRespawnparm(boolean respawnparm); boolean isFastparm(); void setFastparm(boolean fastparm); - + boolean isNomonsters(); void setNomonsters(boolean nomonsters); @@ -67,7 +65,4 @@ public interface IDoomDemo extends IWritableDoomObject{ void resetDemo(); - - - } diff --git a/src/demo/VanillaDoomDemo.java b/src/demo/VanillaDoomDemo.java index 1a415a5f..7df08ce8 100644 --- a/src/demo/VanillaDoomDemo.java +++ b/src/demo/VanillaDoomDemo.java @@ -12,7 +12,7 @@ import w.DoomBuffer; import w.DoomIO; -public class VanillaDoomDemo implements IDoomDemo,CacheableDoomObject{ +public class VanillaDoomDemo implements IDoomDemo, CacheableDoomObject { // This stuff is in the demo header, in the order it appears // However everything is byte-sized when read from disk or to memory. @@ -37,12 +37,12 @@ public class VanillaDoomDemo implements IDoomDemo,CacheableDoomObject{ // (e.g. there is no consistency) and their handling is modified. VanillaTiccmd[] commands; List demorecorder; - + public VanillaDoomDemo() { - this.demorecorder = new ArrayList(); + this.demorecorder = new ArrayList<>(); } - - @Override + + @Override public void unpack(ByteBuffer b) { // Just the Header info for vanilla should be 13 bytes. // 1 byte at the end is the end-demo marker @@ -66,7 +66,7 @@ public void unpack(ByteBuffer b) { } catch (Exception e) { skill = null; } - + episode = b.get(); map = b.get(); deathmatch = b.get() != 0; @@ -92,11 +92,12 @@ public void unpack(ByteBuffer b) { @Override public IDemoTicCmd getNextTic() { - if ((commands!=null)&&(p_demoforwardmove = ((signed char)*demo_p++); - //cmd->sidemove = ((signed char)*demo_p++); - //cmd->angleturn = ((unsigned char)*demo_p++)<<8; - //cmd->buttons = (unsigned char)*demo_p++; - - forwardmove=f.get(); - sidemove= f.get(); + //cmd->forwardmove = ((signed char)*demo_p++); + //cmd->sidemove = ((signed char)*demo_p++); + //cmd->angleturn = ((unsigned char)*demo_p++)<<8; + //cmd->buttons = (unsigned char)*demo_p++; + forwardmove = f.get(); + sidemove = f.get(); // Even if they use the "unsigned char" syntax, angleturn is signed. - angleturn=f.get(); - buttons=f.get(); - + angleturn = f.get(); + buttons = f.get(); + } - + /** Ditto, we only pack some of the fields. * * @param f @@ -65,23 +61,23 @@ public void unpack(ByteBuffer f) */ public void pack(ByteBuffer f) throws IOException { - + f.put(forwardmove); f.put(sidemove); f.put(angleturn); - f.put(buttons); + f.put(buttons); } - - private static StringBuilder sb=new StringBuilder(); - - public String toString(){ + + private static StringBuilder sb = new StringBuilder(); + + public String toString() { sb.setLength(0); sb.append(" forwardmove "); - sb.append(this.forwardmove); + sb.append(this.forwardmove); sb.append(" sidemove "); - sb.append(this.sidemove); + sb.append(this.sidemove); sb.append(" angleturn "); - sb.append(this.angleturn); + sb.append(this.angleturn); sb.append(" buttons "); sb.append(Integer.toHexString(this.buttons)); return sb.toString(); @@ -90,22 +86,22 @@ public String toString(){ @Override public void decode(ticcmd_t dest) { // Decode - dest.forwardmove=this.forwardmove; - dest.sidemove=this.sidemove; - dest.angleturn=(short) (this.angleturn<<8); - dest.buttons=(char) (C2JUtils.toUnsignedByte(this.buttons)); - } + dest.forwardmove = this.forwardmove; + dest.sidemove = this.sidemove; + dest.angleturn = (short) (this.angleturn << 8); + dest.buttons = (char) (C2JUtils.toUnsignedByte(this.buttons)); + } @Override public void encode(ticcmd_t source) { // Note: we can get away with a simple copy because // Demoticcmds have already been "decoded". - this.forwardmove=source.forwardmove; - this.sidemove=source.sidemove; + this.forwardmove = source.forwardmove; + this.sidemove = source.sidemove; // OUCH!!! NASTY PRECISION REDUCTION... but it's the // One True Vanilla way. - this.angleturn=(byte) (source.angleturn>>>8); - this.buttons=(byte) (source.buttons&0x00FF); + this.angleturn = (byte) (source.angleturn >>> 8); + this.buttons = (byte) (source.buttons & 0x00FF); } @Override @@ -114,7 +110,7 @@ public void write(DataOutputStream f) f.writeByte(forwardmove); f.writeByte(sidemove); f.writeByte(angleturn); - f.writeByte(buttons); + f.writeByte(buttons); } } diff --git a/src/doom/CVarManager.java b/src/doom/CVarManager.java index c8176eed..8d49dfad 100644 --- a/src/doom/CVarManager.java +++ b/src/doom/CVarManager.java @@ -25,6 +25,7 @@ import java.util.Optional; import java.util.function.Consumer; import java.util.logging.Level; +import java.util.logging.Logger; import mochadoom.Loggers; import utils.ResourceIO; @@ -38,13 +39,16 @@ * @author Good Sign */ public class CVarManager { - + + private static final Logger LOGGER = Loggers.getLogger(CVarManager.class.getName()); + private final EnumMap cVarMap = new EnumMap<>(CommandVariable.class); public CVarManager(final List commandList) { - System.out.println(processAllArgs(commandList) + " command-line variables"); + LOGGER.log(Level.INFO, + String.format("%d command-line variable(s).", processAllArgs(commandList))); } - + /** * Checks that CVar of switch-type is passed as Command Line Argument * @param cv @@ -53,7 +57,7 @@ public CVarManager(final List commandList) { public boolean bool(final CommandVariable cv) { return cv.getType() == CommandVariable.Type.SWITCH && cVarMap.containsKey(cv); } - + /** * Checks that CVar of any type is passed as Command Line Argument with proper value(s) * @param cv @@ -62,7 +66,7 @@ public boolean bool(final CommandVariable cv) { public boolean present(final CommandVariable cv) { return cVarMap.get(cv) != null; } - + /** * Checks that CVar of any type is passed as Command Line Argument * @param cv @@ -71,26 +75,26 @@ public boolean present(final CommandVariable cv) { public boolean specified(final CommandVariable cv) { return cVarMap.containsKey(cv); } - + /** * Gets an Optional with or without a value of CVar argument at position * @param cv * @return Optional */ - public Optional get(final CommandVariable cv, final Class itemType, final int position) { + public Optional get(final CommandVariable cv, final Class itemType, final int position) { if (cv.arguments[position] == itemType) { if (!cVarMap.containsKey(cv)) { return Optional.empty(); } - + @SuppressWarnings("unchecked") final T ret = (T) cVarMap.get(cv)[position]; return Optional.ofNullable(ret); } - + throw new IllegalArgumentException("CVar argument at position " + position + " is not of class " + itemType.getName()); } - + /** * Tries to apply a CVar argument at position to the consuming function * The magic is that you declare a lambda function or reference some method @@ -115,7 +119,7 @@ public boolean with(final CommandVariable cv, final int position, final Cons if (mapped == null) { return false; } - + @SuppressWarnings("unchecked") final T item = (T) mapped[position]; action.accept(item); @@ -124,7 +128,7 @@ public boolean with(final CommandVariable cv, final int position, final Cons return false; } } - + /** * Tries to replace the CVar argument if already present or add it along with CVar * @param cv @@ -136,64 +140,61 @@ public boolean override(final CommandVariable cv, final T value, final int p if (position < 0 || position >= cv.arguments.length) { return false; } - + if (!cv.arguments[position].isInstance(value)) { return false; } - + cVarMap.compute(cv, (key, array) -> { if (array == null) { array = new Object[cv.arguments.length]; } - + array[position] = value; return array; }); - + return true; } - + private void readResponseFile(final String filename) { final ResponseReader r = new ResponseReader(); if (new ResourceIO(filename).readLines(r)) { - System.out.println(String.format("Found response file %s, read %d command line variables", filename, r.cVarCount)); + LOGGER.log(Level.INFO, String.format("Found response file %s, read %d command line variables", filename, r.cVarCount)); } else { - System.out.println(String.format("No such response file %s!", filename)); + LOGGER.log(Level.WARNING, String.format("No such response file %s!", filename)); System.exit(1); } } private int processAllArgs(final List commandList) { int cVarCount = 0, position = 0; - - for ( - final int limit = commandList.size(); - limit > position; - position = processCVar(commandList, position), - ++position, - ++cVarCount - ) {} - + + for (final int limit = commandList.size(); + limit > position; + position = processCVar(commandList, position), ++position, ++cVarCount) { + } + return cVarCount; } private int processCVar(final List commandList, int position) { final String arg = commandList.get(position); - + if (!isCommandArgument(arg)) { return position; } - + final char cVarPrefix = arg.charAt(0); final String cVarName = arg.substring(1); - + if (cVarPrefix == '@') { readResponseFile(cVarName); return position; } else try { final CommandVariable cVar = CommandVariable.valueOf(cVarName.toUpperCase()); if (cVar.prefix == cVarPrefix) { - switch(cVar.getType()) { + switch (cVar.getType()) { case PARAMETER: cVarMap.put(cVar, null); case VARARG: @@ -204,10 +205,11 @@ private int processCVar(final List commandList, int position) { return position; } } - } catch (IllegalArgumentException ex) {} // ignore + } catch (IllegalArgumentException ex) { + } // ignore return position; } - + private int processCVarSubArgs(final List commandList, int position, final CommandVariable cVar) { final Object[] cVarMappings = new Object[cVar.arguments.length]; for (int j = 0; j < cVar.arguments.length; ++j) { @@ -253,7 +255,7 @@ private Object formatArgValue(final Class format, final String arg) { try { return Integer.parseInt(arg); } catch (NumberFormatException ex) { - Loggers.getLogger(CommandVariable.class.getName()).log(Level.WARNING, null, ex); + LOGGER.log(Level.WARNING, "formatArgValue failure", ex); return null; } } else if (format == String.class) { @@ -261,34 +263,34 @@ private Object formatArgValue(final Class format, final String arg) { } try { return format.getDeclaredConstructor(String.class).newInstance(arg); - } catch ( - NoSuchMethodException - | SecurityException - | InstantiationException - | IllegalAccessException - | IllegalArgumentException - | InvocationTargetException ex - ) { - Loggers.getLogger(CommandVariable.class.getName()).log(Level.SEVERE, null, ex); + } catch (NoSuchMethodException + | SecurityException + | InstantiationException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException ex) { + LOGGER.log(Level.SEVERE, "formatArgValue failure", ex); return null; } } private boolean isCommandArgument(final String arg) { - if (arg.length() < CommandVariable.MIN_CVAR_LENGTH) + if (arg.length() < CommandVariable.MIN_CVAR_LENGTH) { return false; - + } + switch (arg.charAt(0)) { case '-': case '+': case '@': return true; } - + return false; } - + private class ResponseReader implements Consumer { + int cVarCount = 0; @Override diff --git a/src/doom/CommandVariable.java b/src/doom/CommandVariable.java index 73be4967..e9df6c11 100644 --- a/src/doom/CommandVariable.java +++ b/src/doom/CommandVariable.java @@ -26,13 +26,10 @@ public enum CommandVariable { PLAYDEMO(String.class), FASTDEMO(String.class), TIMEDEMO(String.class), RECORD(String.class), STATCOPY(String.class), TURBO(Integer.class), SKILL(Integer.class), EPISODE(Integer.class), TIMER(Integer.class), PORT(Integer.class), MULTIPLY(Integer.class), WIDTH(Integer.class), HEIGHT(Integer.class), - PARALLELRENDERER(Integer.class, Integer.class, Integer.class), PARALLELRENDERER2(Integer.class, Integer.class, Integer.class), - LOADGAME(Character.class), DUP(Character.class), NET(Character.class, String[].class), - WART(Integer.class, Integer.class), WARP(WarpFormat.class), MAP('+', MapFormat.class), @@ -40,7 +37,6 @@ public enum CommandVariable { IWAD(String.class), NOVERT(ForbidFormat.class), NOVOLATILEIMAGE(ForbidFormat.class), - AWTFRAME, DEBUGFILE, SHDEV, @@ -80,38 +76,41 @@ public enum CommandVariable { SHOWFPS, JAVARANDOM, GREYPAL; - + public final char prefix; public final Class[] arguments; public final static int MIN_CVAR_LENGTH = 4; - + CommandVariable(final char prefix, final Class... arguments) { this.prefix = prefix; this.arguments = arguments; } - + CommandVariable(final Class... arguments) { this('-', arguments); } - + public Type getType() { return arguments.length > 0 - ? ( - arguments[arguments.length - 1].isArray() + ? (arguments[arguments.length - 1].isArray() ? Type.VARARG - : Type.PARAMETER - ) - : Type.SWITCH; + : Type.PARAMETER) + : Type.SWITCH; + } + + public enum Type { + PARAMETER, VARARG, SWITCH; } - - public enum Type { PARAMETER, VARARG, SWITCH; } - + public interface WarpMetric { + int getEpisode(); + int getMap(); } - + public static class ForbidFormat { + public static ForbidFormat FORBID = new ForbidFormat("disable"); public static ForbidFormat ALLOW = new ForbidFormat(null); private final boolean isForbidden; @@ -142,30 +141,32 @@ public boolean equals(Object obj) { return this.isForbidden == other.isForbidden; } } - + public static class WarpFormat { + final int warpInt; - + public WarpFormat(final int warpInt) { this.warpInt = warpInt; } - + public WarpFormat(final String warpString) { int tryParse; try { tryParse = Integer.parseInt(warpString); - } catch (NumberFormatException e){ + } catch (NumberFormatException e) { // swallow exception. No warp. tryParse = 0; } this.warpInt = tryParse; } - + public WarpMetric getMetric(final boolean commercial) { return new Metric(commercial); } private class Metric implements WarpMetric { + final int episode; final int map; @@ -175,9 +176,9 @@ private class Metric implements WarpMetric { map = WarpFormat.this.warpInt; } else { final int evalInt = WarpFormat.this.warpInt > 99 - ? WarpFormat.this.warpInt % 100 - : WarpFormat.this.warpInt; - + ? WarpFormat.this.warpInt % 100 + : WarpFormat.this.warpInt; + episode = evalInt / 10; map = evalInt % 10; } @@ -194,49 +195,51 @@ public int getMap() { } } } - + public static class MapFormat { + final String mapString; - + public MapFormat(final String mapString) { this.mapString = mapString.toLowerCase(); } - + protected int parseAsMapXX() { if (mapString.length() != 5 || mapString.lastIndexOf("map") != 0) { return -1; // Meh. } - + final int map; try { map = Integer.parseInt(mapString.substring(3)); - } catch (NumberFormatException e){ + } catch (NumberFormatException e) { return -1; // eww } return map; } - + protected int parseAsExMx() { if (mapString.length() != 4 || mapString.charAt(0) != 'e' || mapString.charAt(2) != 'm') { return -1; // Nah. } - + final char episode = mapString.charAt(1); final char mission = mapString.charAt(3); - - if (episode < '0' || episode > '9' || mission < '0' || mission > '9') + + if (episode < '0' || episode > '9' || mission < '0' || mission > '9') { return -1; + } return (episode - '0') * 10 + (mission - '0'); } - + public WarpMetric getMetric(final boolean commercial) { final int parse = commercial - ? parseAsMapXX() - : parseAsExMx(); - + ? parseAsMapXX() + : parseAsExMx(); + return new WarpFormat(Math.max(parse, 0)).getMetric(commercial); } } -} \ No newline at end of file +} diff --git a/src/doom/ConfigBase.java b/src/doom/ConfigBase.java index 06e61290..4fc68f1f 100644 --- a/src/doom/ConfigBase.java +++ b/src/doom/ConfigBase.java @@ -14,17 +14,17 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package doom; import data.dstrings; -import mochadoom.Engine; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; +import java.util.Objects; import java.util.Optional; import m.Settings; +import mochadoom.Engine; import utils.OSValidator; import utils.ResourceIO; @@ -46,10 +46,9 @@ public enum ConfigBase { /** * Reference these in Settings.java to set which file they will go on by default */ - public static final Files - FILE_DOOM = new Files(CURRENT.defaultConfigName, Enum::compareTo), - FILE_MOCHADOOM = new Files("mochadoom.cfg"); - + public static final Files FILE_DOOM = new Files(CURRENT.defaultConfigName, Enum::compareTo), + FILE_MOCHADOOM = new Files("mochadoom.cfg"); + public final String defaultConfigName; public final String env; @@ -59,34 +58,72 @@ public enum ConfigBase { } public static class Files { + private static String folder; public final Comparator comparator; public final String fileName; + // flags that configuration is provided by the -config argument + public final boolean alternate; + public boolean changed = true; - private String[] paths; - + public Files(String fileName) { - this(fileName, Comparator.comparing(Enum::name, String::compareTo)); + this(fileName, false); + } + + public Files(String fileName, boolean alternate) { + this(fileName, Comparator.comparing(Enum::name, String::compareTo), alternate); } public Files(String fileName, Comparator comparator) { + this(fileName, comparator, false); + } + + public Files(String fileName, Comparator comparator, boolean alternate) { this.fileName = fileName; this.comparator = comparator; + this.alternate = alternate; } - + public Optional firstValidPathIO() { return Arrays.stream(getPaths()) - .map(ResourceIO::new) - .filter(ResourceIO::exists) - .findFirst(); + .map(ResourceIO::new) + .filter(ResourceIO::exists) + .findFirst(); } - + public ResourceIO workDirIO() { return new ResourceIO(getFolder() + fileName); } - + + @Override + public int hashCode() { + int hash = 7; + hash = 53 * hash + Objects.hashCode(this.fileName); + hash = 53 * hash + (this.alternate ? 1 : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Files other = (Files) obj; + if (this.alternate != other.alternate) { + return false; + } + return Objects.equals(this.fileName, other.fileName); + } + /** * Get file / paths combinations * @@ -96,44 +133,43 @@ private String[] getPaths() { if (paths != null) { return paths; } - + String getPath = null; try { // get it if have rights to do, otherwise ignore and use only current folder getPath = System.getenv(CURRENT.env); - } catch (SecurityException ex) {} + } catch (SecurityException ex) { + } if (getPath == null || "".equals(getPath)) { - return new String[] {folder}; + return new String[]{folder}; } - + getPath += System.getProperty("file.separator"); - return paths = new String[] { + return paths = new String[]{ /** * Uncomment the next line and it will load default.cfg and mochadoom.cfg from user home dir * I find it undesirable - it can load some unrelated file and even write it at exit * - Good Sign 2017/04/19 */ - //getPath + folder + fileName, getFolder() + fileName }; } - + private static String getFolder() { - return folder != null ? folder : (folder = - Engine.getCVM().bool(CommandVariable.SHDEV) || - Engine.getCVM().bool(CommandVariable.REGDEV) || - Engine.getCVM().bool(CommandVariable.FR1DEV) || - Engine.getCVM().bool(CommandVariable.FRDMDEV) || - Engine.getCVM().bool(CommandVariable.FR2DEV) || - Engine.getCVM().bool(CommandVariable.COMDEV) + return folder != null ? folder : (folder + = Engine.getCVM().bool(CommandVariable.SHDEV) + || Engine.getCVM().bool(CommandVariable.REGDEV) + || Engine.getCVM().bool(CommandVariable.FR1DEV) + || Engine.getCVM().bool(CommandVariable.FRDMDEV) + || Engine.getCVM().bool(CommandVariable.FR2DEV) + || Engine.getCVM().bool(CommandVariable.COMDEV) ? dstrings.DEVDATA + System.getProperty("file.separator") - : "" - ); + : ""); } } - + /** * To be able to look for config in several places * Still unfinished @@ -145,17 +181,15 @@ public static List getFiles() { * If user supplied -config argument, it will only use the values from these files instead of defaults */ if (!Engine.getCVM() - .with(CommandVariable.CONFIG, 0, (String[] fileNames) -> - Arrays.stream(fileNames).map(Files::new).forEach(ret::add)) - - /** - * If there is no such argument, load default.cfg (or .doomrc) and mochadoom.cfg - */ - ) { + .with(CommandVariable.CONFIG, 0, (String[] fileNames) + -> Arrays.stream(fileNames).map(fileName -> new Files(fileName, true)).forEach(ret::add)) /** + * If there is no such argument, load default.cfg (or .doomrc) and mochadoom.cfg + */ + ) { ret.add(FILE_DOOM); ret.add(FILE_MOCHADOOM); } - + return ret; } } diff --git a/src/doom/ConfigManager.java b/src/doom/ConfigManager.java index 34b3082e..9897b676 100644 --- a/src/doom/ConfigManager.java +++ b/src/doom/ConfigManager.java @@ -24,9 +24,12 @@ import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; import java.util.regex.Pattern; import m.Settings; import static m.Settings.SETTINGS_MAP; +import mochadoom.Loggers; import utils.ParseString; import utils.QuoteType; import utils.ResourceIO; @@ -37,49 +40,51 @@ * @author Good Sign */ public class ConfigManager { + + private static final Logger LOGGER = Loggers.getLogger(ConfigManager.class.getName()); + private static final Pattern SPLITTER = Pattern.compile("[ \t\n\r\f]+"); - + private final List configFiles = ConfigBase.getFiles(); private final EnumMap configMap = new EnumMap<>(Settings.class); - + public enum UpdateStatus { UNCHANGED, UPDATED, INVALID; } - + public ConfigManager() { LoadDefaults(); } - + public UpdateStatus update(final Settings setting, final String value) { if (setting.valueType == String.class) { return setting.hasChange(!Objects.equals(configMap.put(setting, value), value)); } else if (setting.valueType == Character.class - || setting.valueType == Long.class - || setting.valueType == Integer.class - || setting.valueType == Boolean.class) - { + || setting.valueType == Long.class + || setting.valueType == Integer.class + || setting.valueType == Boolean.class) { final Object parse = ParseString.parseString(value); if (setting.valueType.isInstance(parse)) { return setting.hasChange(!Objects.equals(configMap.put(setting, parse), parse)); } } else if (setting.valueType.getSuperclass() == Enum.class) { // Enum search by name - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) final Object enumerated = Enum.valueOf((Class) setting.valueType, value); return setting.hasChange(!Objects.equals(configMap.put(setting, enumerated), enumerated)); } - + return UpdateStatus.INVALID; } - + public UpdateStatus update(final Settings setting, final Object value) { if (setting.valueType == String.class) { return setting.hasChange(!Objects.equals(configMap.put(setting, value.toString()), value.toString())); } - + return UpdateStatus.INVALID; } - + public UpdateStatus update(final Settings setting, final int value) { if (setting.valueType == Integer.class) { return setting.hasChange(!Objects.equals(configMap.put(setting, value), value)); @@ -92,10 +97,10 @@ public UpdateStatus update(final Settings setting, final int value) { return setting.hasChange(!Objects.equals(configMap.put(setting, enumValues[value]), enumValues[value])); } } - + return UpdateStatus.INVALID; } - + public UpdateStatus update(final Settings setting, final long value) { if (setting.valueType == Long.class) { return setting.hasChange(!Objects.equals(configMap.put(setting, value), value)); @@ -103,10 +108,10 @@ public UpdateStatus update(final Settings setting, final long value) { final String valStr = Long.toString(value); return setting.hasChange(!Objects.equals(configMap.put(setting, valStr), valStr)); } - + return UpdateStatus.INVALID; } - + public UpdateStatus update(final Settings setting, final double value) { if (setting.valueType == Double.class) { return setting.hasChange(!Objects.equals(configMap.put(setting, value), value)); @@ -114,10 +119,10 @@ public UpdateStatus update(final Settings setting, final double value) { final String valStr = Double.toString(value); return setting.hasChange(!Objects.equals(configMap.put(setting, valStr), valStr)); } - + return UpdateStatus.INVALID; } - + public UpdateStatus update(final Settings setting, final char value) { if (setting.valueType == Character.class) { return setting.hasChange(!Objects.equals(configMap.put(setting, value), value)); @@ -125,7 +130,7 @@ public UpdateStatus update(final Settings setting, final char value) { final String valStr = Character.toString(value); return setting.hasChange(!Objects.equals(configMap.put(setting, valStr), valStr)); } - + return UpdateStatus.INVALID; } @@ -136,32 +141,32 @@ public UpdateStatus update(final Settings setting, final boolean value) { final String valStr = Boolean.toString(value); return setting.hasChange(!Objects.equals(configMap.put(setting, valStr), valStr)); } - + return UpdateStatus.INVALID; } private String export(final Settings setting) { return setting.quoteType().map(qt -> { return new StringBuilder() - .append(setting.name()) - .append("\t\t") - .append(qt.quoteChar) - .append(configMap.get(setting)) - .append(qt.quoteChar) - .toString(); + .append(setting.name()) + .append("\t\t") + .append(qt.quoteChar) + .append(configMap.get(setting)) + .append(qt.quoteChar) + .toString(); }).orElseGet(() -> { return new StringBuilder() - .append(setting.name()) - .append("\t\t") - .append(configMap.get(setting)) - .toString(); + .append(setting.name()) + .append("\t\t") + .append(configMap.get(setting)) + .toString(); }); } - + public boolean equals(final Settings setting, final Object obj) { return obj.equals(configMap.get(setting)); } - + @SuppressWarnings("unchecked") public T getValue(final Settings setting, final Class valueType) { if (setting.valueType == valueType) { @@ -170,10 +175,9 @@ public T getValue(final Settings setting, final Class valueType) { return (T) configMap.get(setting).toString(); } else if (setting.valueType == String.class) { if (valueType == Character.class - || valueType == Long.class - || valueType == Integer.class - || valueType == Boolean.class) - { + || valueType == Long.class + || valueType == Integer.class + || valueType == Boolean.class) { final Object parse = ParseString.parseString(configMap.get(setting).toString()); if (valueType.isInstance(parse)) { return (T) parse; @@ -182,17 +186,23 @@ public T getValue(final Settings setting, final Class valueType) { } else if (valueType == Integer.class && setting.valueType.getSuperclass() == Enum.class) { return (T) ((Integer) ((Enum) configMap.get(setting)).ordinal()); } - + throw new IllegalArgumentException("Unsupported cast: " + setting.valueType + " to " + valueType); } - + public void SaveDefaults() { SETTINGS_MAP.forEach((file, settings) -> { + // skip writing settings which are not part of the loaded config files, + // this helps to not overwrite default.cfg with empty content in case we're using the -config argument + if (!this.configFiles.contains(file)) { + return; + } + // do not write unless there is changes if (!file.changed) { return; } - + // choose existing config file or create one in current working directory final ResourceIO rio = file.firstValidPathIO().orElseGet(file::workDirIO); final Iterator it = settings.stream().sorted(file.comparator).iterator(); @@ -208,34 +218,34 @@ public void SaveDefaults() { } }); } - + /** * Handles variables and settings from default.cfg and other config files * They can be load even earlier then other systems */ private void LoadDefaults() { Arrays.stream(Settings.values()) - .forEach(setting -> { - configMap.put(setting, setting.defaultValue); - }); - - System.out.print("M_LoadDefaults: Load system defaults.\n"); + .forEach(setting -> { + configMap.put(setting, setting.defaultValue); + }); + + LOGGER.log(Level.INFO, "M_LoadDefaults: Load system defaults."); this.configFiles.forEach(file -> { final Optional maybeRIO = file.firstValidPathIO(); - + /** * Each file successfully read marked as not changed, and as changed - those who don't exist * */ file.changed = !(maybeRIO.isPresent() && readFoundConfig(file, maybeRIO.get())); }); - + // create files who don't exist (it will skip those with changed = false - all who exists) SaveDefaults(); } private boolean readFoundConfig(Files file, ResourceIO rio) { - System.out.print(String.format("M_LoadDefaults: Using config %s.\n", rio.getFileame())); + LOGGER.log(Level.INFO, String.format("M_LoadDefaults: Using config %s.", rio.getFileame())); if (rio.readLines(line -> { final String[] split = SPLITTER.split(line, 2); if (split.length < 2) { @@ -251,18 +261,19 @@ private boolean readFoundConfig(Files file, ResourceIO rio) { .orElse(split[1]); if (update(setting, value) == UpdateStatus.INVALID) { - System.err.printf("WARNING: invalid config value for: %s in %s \n", name, rio.getFileame()); + LOGGER.log(Level.WARNING, String.format("WARNING: invalid config value for: %s in %s", name, rio.getFileame())); } else { setting.rebase(file); } - } catch (IllegalArgumentException ex) {} + } catch (IllegalArgumentException ex) { + } })) { return true; // successfully read a file } - + // Something went bad, but this won't destroy successfully read values, though. - System.err.printf("Can't read the settings file %s\n", rio.getFileame()); + LOGGER.log(Level.SEVERE, String.format("Can't read the settings file %s", rio.getFileame())); return false; } - -} \ No newline at end of file + +} diff --git a/src/doom/DoomContext.java b/src/doom/DoomContext.java index 8aa7b7a8..9682c582 100644 --- a/src/doom/DoomContext.java +++ b/src/doom/DoomContext.java @@ -31,7 +31,6 @@ * @author velktron * */ - -public final class DoomContext{ +public final class DoomContext { } diff --git a/src/doom/DoomMain.java b/src/doom/DoomMain.java index a93b8074..ba457d0e 100644 --- a/src/doom/DoomMain.java +++ b/src/doom/DoomMain.java @@ -1,36 +1,131 @@ package doom; import automap.IAutoMap; -import static data.Defines.*; -import static data.Limits.*; +import static data.Defines.BACKUPTICS; +import static data.Defines.BTS_PAUSE; +import static data.Defines.BTS_SAVEGAME; +import static data.Defines.BTS_SAVEMASK; +import static data.Defines.BTS_SAVESHIFT; +import static data.Defines.BT_ATTACK; +import static data.Defines.BT_CHANGE; +import static data.Defines.BT_SPECIAL; +import static data.Defines.BT_SPECIALMASK; +import static data.Defines.BT_USE; +import static data.Defines.BT_WEAPONSHIFT; +import static data.Defines.JAVARANDOM_MASK; +import static data.Defines.NORMALUNIX; +import static data.Defines.NUMWEAPONS; +import static data.Defines.PST_DEAD; +import static data.Defines.PST_LIVE; +import static data.Defines.PST_REBORN; +import static data.Defines.PU_CACHE; +import static data.Defines.PU_STATIC; +import static data.Defines.SKYFLATNAME; +import static data.Defines.TICRATE; +import static data.Defines.TOCENTER; +import static data.Defines.VERSION; +import static data.Limits.MAXEVENTS; +import static data.Limits.MAXINT; +import static data.Limits.MAXNETNODES; +import static data.Limits.MAXPLAYERS; import data.Tables; -import static data.Tables.*; +import static data.Tables.ANG45; +import static data.Tables.ANGLETOFINESHIFT; +import static data.Tables.finecosine; +import static data.Tables.finesine; import data.dstrings; -import static data.dstrings.*; +import static data.dstrings.DEVMAPS; +import static data.dstrings.SAVEGAMENAME; import static data.info.mobjinfo; import static data.info.states; import data.mapthing_t; import data.mobjtype_t; import data.sounds.musicenum_t; import data.sounds.sfxenum_t; -import defines.*; -import static defines.gamestate_t.*; +import defines.DoomVersion; +import defines.GameMission_t; +import defines.GameMode; +import defines.Language_t; +import defines.gamestate_t; +import static defines.gamestate_t.GS_DEMOSCREEN; +import static defines.gamestate_t.GS_FINALE; +import static defines.gamestate_t.GS_INTERMISSION; +import static defines.gamestate_t.GS_LEVEL; +import static defines.gamestate_t.GS_MINUS_ONE; +import defines.skill_t; +import defines.statenum_t; import demo.IDemoTicCmd; import demo.VanillaDoomDemo; import demo.VanillaTiccmd; -import static doom.NetConsts.*; +import static doom.NetConsts.CMD_GET; +import static doom.NetConsts.CMD_SEND; +import static doom.NetConsts.DOOMCOM_ID; +import static doom.NetConsts.NCMD_CHECKSUM; +import static doom.NetConsts.NCMD_EXIT; +import static doom.NetConsts.NCMD_KILL; +import static doom.NetConsts.NCMD_RETRANSMIT; +import static doom.NetConsts.NCMD_SETUP; import doom.SourceCode.CauseOfDesyncProbability; import doom.SourceCode.D_Main; -import static doom.SourceCode.D_Main.*; +import static doom.SourceCode.D_Main.D_DoomLoop; +import static doom.SourceCode.D_Main.D_ProcessEvents; import doom.SourceCode.G_Game; -import static doom.SourceCode.G_Game.*; -import static doom.englsh.*; -import static doom.evtype_t.*; -import static doom.gameaction_t.*; +import static doom.SourceCode.G_Game.G_BeginRecording; +import static doom.SourceCode.G_Game.G_BuildTiccmd; +import static doom.SourceCode.G_Game.G_CheckSpot; +import static doom.SourceCode.G_Game.G_DeathMatchSpawnPlayer; +import static doom.SourceCode.G_Game.G_DoCompleted; +import static doom.SourceCode.G_Game.G_DoLoadGame; +import static doom.SourceCode.G_Game.G_DoLoadLevel; +import static doom.SourceCode.G_Game.G_DoNewGame; +import static doom.SourceCode.G_Game.G_DoPlayDemo; +import static doom.SourceCode.G_Game.G_DoReborn; +import static doom.SourceCode.G_Game.G_DoSaveGame; +import static doom.SourceCode.G_Game.G_InitNew; +import static doom.SourceCode.G_Game.G_Responder; +import static doom.SourceCode.G_Game.G_Ticker; +import static doom.englsh.D_CDROM; +import static doom.englsh.D_DEVSTR; +import static doom.englsh.GGSAVED; +import static doom.englsh.SCREENSHOT; +import static doom.evtype_t.ev_joystick; +import static doom.evtype_t.ev_keydown; +import static doom.evtype_t.ev_keyup; +import static doom.evtype_t.ev_mouse; +import static doom.gameaction_t.ga_completed; +import static doom.gameaction_t.ga_failure; +import static doom.gameaction_t.ga_loadgame; +import static doom.gameaction_t.ga_loadlevel; +import static doom.gameaction_t.ga_newgame; +import static doom.gameaction_t.ga_nothing; +import static doom.gameaction_t.ga_playdemo; +import static doom.gameaction_t.ga_savegame; +import static doom.gameaction_t.ga_screenshot; +import static doom.gameaction_t.ga_victory; +import static doom.gameaction_t.ga_worlddone; import f.EndLevel; import f.Finale; import f.Wiper; -import static g.Signals.ScanCode.*; +import g.Signals; +import static g.Signals.ScanCode.SC_CAPSLK; +import static g.Signals.ScanCode.SC_DOWN; +import static g.Signals.ScanCode.SC_ESCAPE; +import static g.Signals.ScanCode.SC_F12; +import static g.Signals.ScanCode.SC_LALT; +import static g.Signals.ScanCode.SC_LCTRL; +import static g.Signals.ScanCode.SC_LEFT; +import static g.Signals.ScanCode.SC_LSHIFT; +import static g.Signals.ScanCode.SC_NUMKEY2; +import static g.Signals.ScanCode.SC_NUMKEY4; +import static g.Signals.ScanCode.SC_NUMKEY6; +import static g.Signals.ScanCode.SC_NUMKEY8; +import static g.Signals.ScanCode.SC_PAUSE; +import static g.Signals.ScanCode.SC_RALT; +import static g.Signals.ScanCode.SC_RCTRL; +import static g.Signals.ScanCode.SC_RIGHT; +import static g.Signals.ScanCode.SC_RSHIFT; +import static g.Signals.ScanCode.SC_SEMICOLON; +import static g.Signals.ScanCode.SC_UP; import hu.HU; import i.DiskDrawer; import i.DoomSystem; @@ -47,6 +142,10 @@ import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; +import java.util.Objects; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Collectors; import m.DelegateRandom; import m.IDoomMenu; import m.Menu; @@ -55,6 +154,7 @@ import static m.fixed_t.FRACBITS; import static m.fixed_t.MAPFRACUNIT; import mochadoom.Engine; +import mochadoom.Loggers; import n.DoomSystemNetworking; import n.DummyNetworkDriver; import p.AbstractLevelLoader; @@ -80,10 +180,13 @@ import timing.ITicker; import timing.MilliTicker; import utils.C2JUtils; -import static utils.C2JUtils.*; +import static utils.C2JUtils.eval; +import static utils.C2JUtils.flags; +import static utils.C2JUtils.memcpy; +import static utils.C2JUtils.memset; import v.DoomGraphicSystem; import v.renderers.BppMode; -import static v.renderers.DoomScreen.*; +import static v.renderers.DoomScreen.FG; import v.renderers.RendererFactory; import v.scale.VideoScale; import v.scale.VisualSettings; @@ -116,7 +219,6 @@ // In Mocha Doom, this was unified with d_game and doomstat.c // //----------------------------------------------------------------------------- - @SuppressWarnings({ "UseOfSystemOutOrSystemErr", "MalformedFormatString", @@ -126,6 +228,8 @@ }) public class DoomMain extends DoomStatus implements IDoomGameNetworking, IDoomGame, IDoom { + private static final Logger LOGGER = Loggers.getLogger(DoomMain.class.getName()); + public static final String RCSID = "$Id: DoomMain.java,v 1.109 2012/11/06 16:04:58 velktron Exp $"; // @@ -161,29 +265,32 @@ public void PostEvent(event_t ev) { /** * D_ProcessEvents * Send all the events of the given timestamp down the responder chain - */ + */ @D_Main.C(D_ProcessEvents) public void ProcessEvents() { // IF STORE DEMO, DO NOT ACCEPT INPUT if ((isCommercial())) { - W_CheckNumForName: { + W_CheckNumForName: + { if ((wadLoader.CheckNumForName("MAP01") < 0)) { - return; + return; } } } - for(; eventtail != eventhead; eventtail = (++eventtail) & (MAXEVENTS - 1)) { + for (; eventtail != eventhead; eventtail = (++eventtail) & (MAXEVENTS - 1)) { final event_t ev = events[eventtail]; ev.withMouse(event_t.mouseevent_t::processedNotify); - - M_Responder: { + + M_Responder: + { if (menu.Responder(ev)) { continue; // menu ate the event } } - - G_Responder: { + + G_Responder: + { Responder(ev); } } @@ -219,7 +326,7 @@ public void Display() throws IOException { // change the view size if needed if (sceneRenderer.getSetSizeNeeded()) { - sceneRenderer.ExecuteSetViewSize (); + sceneRenderer.ExecuteSetViewSize(); // force background redraw oldgamestate = GS_MINUS_ONE; borderdrawcount = 3; @@ -234,23 +341,22 @@ public void Display() throws IOException { if (gamestate == GS_LEVEL && eval(gametic)) { headsUp.Erase(); } - + // do buffered drawing switch (gamestate) { case GS_LEVEL: if (!eval(gametic)) { - break; + break; } - + if (automapactive) { autoMap.Drawer(); } - + if (wipe - || (!sceneRenderer.isFullHeight() && fullscreen) - || (inhelpscreensstate && !inhelpscreens) - || (diskDrawer.justDoneReading())) - { + || (!sceneRenderer.isFullHeight() && fullscreen) + || (inhelpscreensstate && !inhelpscreens) + || (diskDrawer.justDoneReading())) { redrawsbar = true; // just put away the help screen } statusBar.Drawer(sceneRenderer.isFullHeight(), redrawsbar); @@ -266,7 +372,7 @@ public void Display() throws IOException { PageDrawer(); break; default: - break; + break; } // draw the view directly @@ -304,7 +410,7 @@ public void Display() throws IOException { if (eval(borderdrawcount)) { // erase old menu stuff - sceneRenderer.DrawViewBorder (); + sceneRenderer.DrawViewBorder(); borderdrawcount--; } } @@ -321,9 +427,9 @@ public void Display() throws IOException { } else { y = view.getViewWindowY() + 4 * graphicSystem.getScalingY(); } - + final patch_t pause = wadLoader.CachePatchName("M_PAUSE", PU_CACHE); - graphicSystem.DrawPatchCenteredScaled(FG, pause , vs, y, DoomGraphicSystem.V_NOSCALESTART); + graphicSystem.DrawPatchCenteredScaled(FG, pause, vs, y, DoomGraphicSystem.V_NOSCALESTART); } // menus go directly to the screen @@ -332,7 +438,7 @@ public void Display() throws IOException { // Disk access goes after everything. diskDrawer.Drawer(); - + // normal update if (!wipe) { //System.out.print("Tick "+gametic+"\t"); @@ -346,7 +452,7 @@ public void Display() throws IOException { // Jesus Christ with a Super Shotgun! wiper.EndScreen(0, 0, vs.getScreenWidth(), vs.getScreenHeight()); - wipestart = ticker.GetTime () - 1; + wipestart = ticker.GetTime() - 1; do { do { @@ -399,50 +505,59 @@ public void Display() throws IOException { @D_Main.C(D_DoomLoop) public void DoomLoop() throws IOException { if (demorecording) { - G_BeginRecording: { + G_BeginRecording: + { BeginRecording(); } } - M_CheckParm: { + M_CheckParm: + { if (cVarManager.bool(CommandVariable.DEBUGFILE)) { String filename = "debug" + consoleplayer + ".txt"; - System.out.println("debug output to: " + filename); + LOGGER.log(Level.INFO, String.format("Debug output to: %s", filename)); try { debugfile = new OutputStreamWriter(new FileOutputStream(filename)); } catch (FileNotFoundException e) { - System.err.println("Couldn't open debugfile. Now, that sucks some putrid shit out of John Romero's asshole!"); - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Couldn't open debugfile.", e); } } } - - I_InitGraphics: { + + I_InitGraphics: + { view = sceneRenderer.getView(); } - + while (true) { // frame syncronous IO operations - I_StartFrame:; - + I_StartFrame: + ; + // process one or more tics if (singletics) { - I_StartTic:; - D_ProcessEvents: { + I_StartTic: + ; + D_ProcessEvents: + { ProcessEvents(); } - G_BuildTiccmd: { + G_BuildTiccmd: + { BuildTiccmd(netcmds[consoleplayer][maketic % BACKUPTICS]); } if (advancedemo) { - D_DoAdvanceDemo: { + D_DoAdvanceDemo: + { DoAdvanceDemo(); } } - M_Ticker: { + M_Ticker: + { menu.Ticker(); } - G_Ticker: { + G_Ticker: + { Ticker(); } gametic++; @@ -450,10 +565,12 @@ public void DoomLoop() throws IOException { } else { gameNetworking.TryRunTics(); // will run at least one tic (in NET) } - S_UpdateSounds: { + S_UpdateSounds: + { doomSound.UpdateSounds(players[consoleplayer].mo); // move positional sounds } - D_Display: { // Update display, next frame, with current state. + D_Display: + { // Update display, next frame, with current state. Display(); } //#ifndef SNDSERV @@ -467,7 +584,7 @@ public void DoomLoop() throws IOException { //#endif } } - + // To keep an "eye" on the renderer. protected ViewVars view; @@ -478,7 +595,6 @@ public void DoomLoop() throws IOException { int pagetic; String pagename; - /** * D_PageTicker * Handles timing for warped projection @@ -500,13 +616,11 @@ public final void PageDrawer() { } } - /** * D_AdvanceDemo * Called after each demo or intro demosequence finishes */ - public void AdvanceDemo () - { + public void AdvanceDemo() { advancedemo = true; } @@ -610,11 +724,11 @@ public void StartTitle() { */ private void AddFile(String file) { int numwadfiles; - for (numwadfiles = 0; eval(wadfiles[numwadfiles]); numwadfiles++) {} + for (numwadfiles = 0; eval(wadfiles[numwadfiles]); numwadfiles++) { + } wadfiles[numwadfiles] = file; } - /** * IdentifyVersion * Checks availability of IWAD files by name, @@ -629,7 +743,7 @@ public final String IdentifyVersion() { // First, check for -iwad parameter. // If valid, then it trumps all others. if (cVarManager.present(CommandVariable.IWAD)) { - System.out.println("-iwad specified. Will be used with priority\n"); + LOGGER.log(Level.INFO, "-iwad specified. Will be used with priority"); // It might be quoted. final String test = C2JUtils.unquoteIfQuoted(cVarManager.get(CommandVariable.IWAD, String.class, 0).get(), '"'); final String separator = System.getProperty("file.separator"); @@ -649,7 +763,7 @@ public final String IdentifyVersion() { doomwaddir = System.getenv("DOOMWADDIR"); if (doomwaddir != null) { - System.out.println("DOOMWADDIR found. Will be used with priority\n"); + LOGGER.log(Level.INFO, "DOOMWADDIR found. Will be used with priority"); } // None found, using current. @@ -658,15 +772,15 @@ public final String IdentifyVersion() { } } - for (GameMode mode: GameMode.values()) { + for (GameMode mode : GameMode.values()) { if (mode != GameMode.indetermined && cVarManager.bool(mode.devVar)) { return devParmOn(mode); } } - + final String wadFullPath = DoomVersion.tryAllWads(this, doomwaddir); if (wadFullPath == null) { - System.out.println("Game mode indeterminate.\n"); + LOGGER.log(Level.INFO, "Game mode indeterminate."); setGameMode(GameMode.indetermined); // We don't abort. Let's see what the PWAD contains. //exit(1); @@ -674,7 +788,7 @@ public final String IdentifyVersion() { } else { AddFile(wadFullPath); } - + return wadFullPath; } @@ -694,11 +808,10 @@ private String devParmOn(GameMode mode) { * */ protected final void CheckForPWADSInShareware() { - if (modifiedgame) - { + if (modifiedgame) { // These are the lumps that will be checked in IWAD, // if any one is not present, execution will be aborted. - String[] name= { + String[] name = { "e2m1", "e2m2", "e2m3", "e2m4", "e2m5", "e2m6", "e2m7", "e2m8", "e2m9", "e3m1", "e3m3", "e3m3", "e3m4", "e3m5", "e3m6", "e3m7", "e3m8", "e3m9", "dphoof", "bfgga0", "heada1", "cybra1", "spida1d1" @@ -707,15 +820,15 @@ protected final void CheckForPWADSInShareware() { // Oh yes I can. if (isShareware()) { - System.out.println("\nYou cannot -file with the shareware version. Register!"); + LOGGER.log(Level.WARNING, "You cannot -file with the shareware version. Register!"); } // Check for fake IWAD with right name, // but w/o all the lumps of the registered version. if (isRegistered()) { - for (i = 0;i < 23; i++) { - if (wadLoader.CheckNumForName(name[i].toUpperCase())<0) { - doomSystem.Error("\nThis is not the registered version: "+name[i]); + for (i = 0; i < 23; i++) { + if (wadLoader.CheckNumForName(name[i].toUpperCase()) < 0) { + doomSystem.Error("This is not the registered version: " + name[i]); } } } @@ -728,22 +841,22 @@ protected final void CheckForPWADSInShareware() { * */ protected final void CheckForUltimateDoom(WadLoader W) { - if (isRegistered()) - { + if (isRegistered()) { // These are the lumps that will be checked in IWAD, // if any one is not present, execution will be aborted. String[] lumps = {"e4m1", "e4m2", "e4m3", "e4m4", "e4m5", "e4m6", "e4m7", "e4m8", "e4m9"}; // Check for fake IWAD with right name, // but w/o all the lumps of the registered version. - if (!CheckForLumps(lumps,W)) return; + if (!CheckForLumps(lumps, W)) { + return; + } // Checks passed, so we can set the mode to Ultimate setGameMode(GameMode.retail); } } - /** Check if ALL of the lumps exist. * * @param name @@ -753,113 +866,85 @@ protected boolean CheckForLumps(String[] name, WadLoader W) { for (String name1 : name) { if (W.CheckNumForName(name1.toUpperCase()) < 0) { // Even one is missing? Not OK. - return false; + return false; } } return true; } - - /** - * - */ protected final void GenerateTitle() { - switch ( getGameMode() ) - { - case retail: - title.append(" "); - title.append("The Ultimate DOOM Startup v"); - title.append(VERSION/100); - title.append("."); - title.append(VERSION%100); - title.append(" "); - break; - case shareware: - title.append(" "); - title.append("DOOM Shareware Startup v"); - title.append(VERSION/100); - title.append("."); - title.append(VERSION%100); - title.append(" "); - break; - case registered: - title.append(" "); - title.append("DOOM Registered Startup v"); - title.append(VERSION/100); - title.append("."); - title.append(VERSION%100); - title.append(" "); - break; - case commercial: - title.append(" "); - title.append("DOOM 2: Hell on Earth v"); - title.append(VERSION/100); - title.append("."); - title.append(VERSION%100); - title.append(" "); - - break; - case pack_plut: - title.append(" "); - title.append("DOOM 2: Plutonia Experiment v"); - title.append(VERSION/100); - title.append("."); - title.append(VERSION%100); - title.append(" "); - break; - case pack_tnt: - title.append(" "); - title.append("DOOM 2: TNT - Evilution v"); - title.append(VERSION/100); - title.append("."); - title.append(VERSION%100); - title.append(" "); - break; - case pack_xbla: - title.append(" "); - title.append("DOOM 2: No Rest for the Living v"); - title.append(VERSION/100); - title.append("."); - title.append(VERSION%100); - title.append(" "); - break; - case freedm: - title.append(" "); - title.append("FreeDM v"); - title.append(VERSION/100); - title.append("."); - title.append(VERSION%100); - title.append(" "); - break; - case freedoom1: - title.append(" "); - title.append("FreeDoom: Phase 1 v"); - title.append(VERSION/100); - title.append("."); - title.append(VERSION%100); - title.append(" "); - break; - case freedoom2: - title.append(" "); - title.append("FreeDoom: Phase 2 v"); - title.append(VERSION/100); - title.append("."); - title.append(VERSION%100); - title.append(" "); - break; - default: - title.append(" "); - title.append("Public DOOM - v"); - title.append(VERSION/100); - title.append("."); - title.append(VERSION%100); - title.append(" "); - break; + switch (getGameMode()) { + case retail: + title.append("The Ultimate DOOM Startup v"); + title.append(VERSION / 100); + title.append("."); + title.append(VERSION % 100); + break; + case shareware: + title.append("DOOM Shareware Startup v"); + title.append(VERSION / 100); + title.append("."); + title.append(VERSION % 100); + break; + case registered: + title.append("DOOM Registered Startup v"); + title.append(VERSION / 100); + title.append("."); + title.append(VERSION % 100); + break; + case commercial: + title.append("DOOM 2: Hell on Earth v"); + title.append(VERSION / 100); + title.append("."); + title.append(VERSION % 100); + break; + case pack_plut: + title.append("DOOM 2: Plutonia Experiment v"); + title.append(VERSION / 100); + title.append("."); + title.append(VERSION % 100); + break; + case pack_tnt: + title.append("DOOM 2: TNT - Evilution v"); + title.append(VERSION / 100); + title.append("."); + title.append(VERSION % 100); + break; + case pack_xbla: + title.append("DOOM 2: No Rest for the Living v"); + title.append(VERSION / 100); + title.append("."); + title.append(VERSION % 100); + break; + case freedm: + title.append("FreeDM v"); + title.append(VERSION / 100); + title.append("."); + title.append(VERSION % 100); + break; + case freedoom1: + title.append("FreeDoom: Phase 1 v"); + title.append(VERSION / 100); + title.append("."); + title.append(VERSION % 100); + break; + case freedoom2: + title.append("FreeDoom: Phase 2 v"); + title.append(VERSION / 100); + title.append("."); + title.append(VERSION % 100); + break; + default: + title.append("Public DOOM - v"); + title.append(VERSION / 100); + title.append("."); + title.append(VERSION % 100); + break; } } // Used in BuildTiccmd. - protected ticcmd_t base=new ticcmd_t(); + protected ticcmd_t base = new ticcmd_t(); /** * G_BuildTiccmd @@ -872,11 +957,9 @@ protected final void GenerateTitle() { * So look there for any fuckups in constructing them. * */ - @SourceCode.Compatible @G_Game.C(G_BuildTiccmd) - private void BuildTiccmd (ticcmd_t cmd) - { + private void BuildTiccmd(ticcmd_t cmd) { int i; boolean strafe; boolean bstrafe; @@ -885,11 +968,12 @@ private void BuildTiccmd (ticcmd_t cmd) int side; int look; - I_BaseTiccmd:; // empty, or external driver + I_BaseTiccmd: + ; // empty, or external driver base.copyTo(cmd); cmd.consistancy = consistancy[consoleplayer][maketic % BACKUPTICS]; - + strafe = gamekeydown[key_strafe] || mousebuttons(mousebstrafe) || joybuttons(joybstrafe); speed = ((gamekeydown[key_speed] ^ alwaysrun) || joybuttons(joybspeed)) ? 1 : 0; @@ -898,9 +982,9 @@ private void BuildTiccmd (ticcmd_t cmd) // use two stage accelerative turning // on the keyboard and joystick if (joyxmove < 0 || joyxmove > 0 || gamekeydown[key_right] || gamekeydown[key_left]) { - turnheld += ticdup; + turnheld += ticdup; } else { - turnheld = 0; + turnheld = 0; } tspeed = turnheld < SLOWTURNTICS ? 2 /* slowturn */ : speed; @@ -910,94 +994,89 @@ private void BuildTiccmd (ticcmd_t cmd) } else { lookheld = 0; } - + lspeed = lookheld < SLOWTURNTICS ? 1 : 2; - + // let movement keys cancel each other out - if (strafe) { + if (strafe) { if (gamekeydown[key_right]) { // fprintf(stderr, "strafe right\n"); - side += sidemove[speed]; + side += sidemove[speed]; } - + if (gamekeydown[key_left]) { // fprintf(stderr, "strafe left\n"); - side -= sidemove[speed]; + side -= sidemove[speed]; } - + if (joyxmove > 0) { - side += sidemove[speed]; + side += sidemove[speed]; } else if (joyxmove < 0) { side -= sidemove[speed]; } - } else { + } else { if (gamekeydown[key_right]) { - cmd.angleturn -= angleturn[tspeed]; + cmd.angleturn -= angleturn[tspeed]; } - + if (gamekeydown[key_left]) { - cmd.angleturn += angleturn[tspeed]; + cmd.angleturn += angleturn[tspeed]; } - + if (joyxmove > 0) { - cmd.angleturn -= angleturn[tspeed]; + cmd.angleturn -= angleturn[tspeed]; } else if (joyxmove < 0) { cmd.angleturn += angleturn[tspeed]; } - } + } if (gamekeydown[key_up]) { - //System.err.print("up\n"); - forward += forwardmove[speed]; + forward += forwardmove[speed]; } - + if (gamekeydown[key_down]) { - //System.err.print("down\n"); - forward -= forwardmove[speed]; - } - + forward -= forwardmove[speed]; + } + if (joyymove < 0) { - forward += forwardmove[speed]; + forward += forwardmove[speed]; } else if (joyymove > 0) { - forward -= forwardmove[speed]; + forward -= forwardmove[speed]; } - + if (gamekeydown[key_straferight]) { - side += sidemove[speed]; + side += sidemove[speed]; } - + if (gamekeydown[key_strafeleft]) { side -= sidemove[speed]; } - // Look up/down/center keys - if(gamekeydown[key_lookup]) { - System.err.print("Look up\n"); - look = lspeed; - } - - if(gamekeydown[key_lookdown]) { - System.err.print("Look down\n"); - look = -lspeed; - } - - if(gamekeydown[key_lookcenter]) { - System.err.print("Center look\n"); - look = TOCENTER; - } - + // Look up/down/center keys + if (gamekeydown[key_lookup]) { + look = lspeed; + } + + if (gamekeydown[key_lookdown]) { + look = -lspeed; + } + + if (gamekeydown[key_lookcenter]) { + look = TOCENTER; + } + // buttons - cmd.chatchar = headsUp.dequeueChatChar(); + cmd.chatchar = headsUp.dequeueChatChar(); if (gamekeydown[key_fire] || mousebuttons(mousebfire) || joybuttons(joybfire)) { - cmd.buttons |= BT_ATTACK; + cmd.buttons |= BT_ATTACK; } - if (gamekeydown[key_use] || joybuttons(joybuse)) { + if (gamekeydown[key_use] || joybuttons(joybuse)) { cmd.buttons |= BT_USE; // clear double clicks if hit use button - dclicks = 0; - } + dclicks = 0; + } // chainsaw overrides for (i = 0; i < NUMWEAPONS - 1; i++) { @@ -1066,7 +1145,7 @@ private void BuildTiccmd (ticcmd_t cmd) cmd.angleturn -= mousex * 0x8; } - mousex = mousey = 0; + mousex = mousey = 0; if (forward > MAXPLMOVE()) { forward = MAXPLMOVE(); @@ -1079,7 +1158,7 @@ private void BuildTiccmd (ticcmd_t cmd) side = -MAXPLMOVE(); } - cmd.forwardmove += forward; + cmd.forwardmove += forward; cmd.sidemove += side; if (players[consoleplayer].playerstate == PST_LIVE) { @@ -1100,8 +1179,7 @@ private void BuildTiccmd (ticcmd_t cmd) sendsave = false; cmd.buttons = (char) (BT_SPECIAL | BTS_SAVEGAME | (savegameslot << BTS_SAVESHIFT)); } - } - + } /** * G_DoLoadLevel @@ -1110,7 +1188,7 @@ private void BuildTiccmd (ticcmd_t cmd) */ @SourceCode.Suspicious(CauseOfDesyncProbability.LOW) @G_Game.C(G_DoLoadLevel) - public boolean DoLoadLevel() { + public boolean DoLoadLevel() { /** * Added a config switch to this fix * - Good Sign 2017/04/26 @@ -1124,9 +1202,8 @@ public boolean DoLoadLevel() { * @SourceCode.Compatible */ if (Engine.getConfig().equals(Settings.fix_sky_change, Boolean.TRUE) && (isCommercial() - || ( gamemission == GameMission_t.pack_tnt ) - || ( gamemission == GameMission_t.pack_plut ))) - { + || (gamemission == GameMission_t.pack_tnt) + || (gamemission == GameMission_t.pack_plut))) { // Set the sky map. // First thing, we have a dummy sky texture name, // a flat. The data is in the WAD only because @@ -1134,22 +1211,22 @@ public boolean DoLoadLevel() { // setting one. textureManager.setSkyFlatNum(textureManager.FlatNumForName(SKYFLATNAME)); - textureManager.setSkyTexture(textureManager.TextureNumForName ("SKY3")); + textureManager.setSkyTexture(textureManager.TextureNumForName("SKY3")); if (gamemap < 12) { - textureManager.setSkyTexture(textureManager.TextureNumForName ("SKY1")); + textureManager.setSkyTexture(textureManager.TextureNumForName("SKY1")); } else { if (gamemap < 21) { - textureManager.setSkyTexture(textureManager.TextureNumForName ("SKY2")); + textureManager.setSkyTexture(textureManager.TextureNumForName("SKY2")); } } } levelstarttic = gametic; // for time calculation - if (wipegamestate == GS_LEVEL) + if (wipegamestate == GS_LEVEL) { wipegamestate = GS_MINUS_ONE; // force a wipe - - gamestate = GS_LEVEL; + } + gamestate = GS_LEVEL; for (int i = 0; i < MAXPLAYERS; i++) { if (playeringame[i] && players[i].playerstate == PST_DEAD) { @@ -1160,57 +1237,58 @@ public boolean DoLoadLevel() { } try { - P_SetupLevel: { + P_SetupLevel: + { levelLoader.SetupLevel(gameepisode, gamemap, 0, gameskill); } } catch (IOException e) { - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Failure loading level.", e); // Failure loading level. return false; } - + displayplayer = consoleplayer; // view the guy you are playing - I_GetTime: { + I_GetTime: + { starttime = ticker.GetTime(); } - gameaction = ga_nothing; - Z_CheckHeap:; + gameaction = ga_nothing; + Z_CheckHeap: + ; // clear cmd building stuff memset(gamekeydown, false, gamekeydown.length); keysCleared = true; - joyxmove = joyymove = 0; - mousex = mousey = 0; - sendpause = sendsave = paused = false; + joyxmove = joyymove = 0; + mousex = mousey = 0; + sendpause = sendsave = paused = false; memset(mousearray, false, mousearray.length); memset(joyarray, false, joyarray.length); - + /** * Probably no desync-effect * - GoodSign 2017/05/07 * * @SourceCode.Suspicious */ - // killough 5/13/98: in case netdemo has consoleplayer other than green statusBar.Start(); headsUp.Start(); - + // killough: make -timedemo work on multilevel demos // Move to end of function to minimize noise -- killough 2/22/98: - if (timingdemo) { if (first) { starttime = RealTime.GetTime(); first = false; } } - + // Try reclaiming some memory from limit-expanded buffers. sceneRenderer.resetLimits(); return true; - } - + } + protected boolean first = true; /** @@ -1235,10 +1313,10 @@ public boolean Responder(event_t ev) { // any other key pops up menu if in demos if (gameaction == ga_nothing && !singledemo && (demoplayback || gamestate == GS_DEMOSCREEN)) { if (ev.isType(ev_keydown) - || ev.ifMouse(ev_mouse, event_t::hasData) - || ev.ifJoy(ev_joystick, event_t::hasData)) - { - M_StartControlPanel: { + || (use_mouse && ev.ifMouse(ev_mouse, event_t::hasData)) + || (use_joystick && ev.ifJoy(ev_joystick, event_t::hasData))) { + M_StartControlPanel: + { menu.StartControlPanel(); } return true; @@ -1248,23 +1326,27 @@ public boolean Responder(event_t ev) { if (gamestate == GS_LEVEL) { if (devparm && ev.isKey(SC_SEMICOLON, ev_keydown)) { - G_DeathMatchSpawnPlayer: { + G_DeathMatchSpawnPlayer: + { DeathMatchSpawnPlayer(0); } return true; } - HU_Responder: { + HU_Responder: + { if (headsUp.Responder(ev)) { return true; // chat ate the event } } - ST_Responder: { + ST_Responder: + { if (statusBar.Responder(ev)) { return true; // status window ate it } } - AM_Responder: { + AM_Responder: + { if (autoMap.Responder(ev)) { return true; // automap ate it } @@ -1272,14 +1354,15 @@ public boolean Responder(event_t ev) { } if (gamestate == GS_FINALE) { - F_Responder: { + F_Responder: + { if (finale.Responder(ev)) { return true; // finale ate the event } } } - switch (ev.type()) { + switch (ev.type()) { case ev_keydown: if (ev.isKey(SC_PAUSE)) { sendpause = true; @@ -1289,21 +1372,7 @@ public boolean Responder(event_t ev) { ev.withKey(sc -> { gamekeydown[sc.ordinal()] = true; if (vanillaKeyBehavior) { - switch(sc) { - case SC_LSHIFT: - case SC_RSHIFT: - gamekeydown[SC_RSHIFT.ordinal()] = gamekeydown[SC_LSHIFT.ordinal()] = true; - break; - case SC_LCTRL: - case SC_RCTRL: - gamekeydown[SC_RCTRL.ordinal()] = gamekeydown[SC_LCTRL.ordinal()] = true; - break; - case SC_LALT: - case SC_RALT: - gamekeydown[SC_RALT.ordinal()] = gamekeydown[SC_LALT.ordinal()] = true; - break; - default: break; - } + handleVanillaKeys(sc, true); } }); return true; // eat key down events @@ -1318,21 +1387,7 @@ public boolean Responder(event_t ev) { ev.withKey(sc -> { gamekeydown[sc.ordinal()] = false; if (vanillaKeyBehavior) { - switch(sc) { - case SC_LSHIFT: - case SC_RSHIFT: - gamekeydown[SC_RSHIFT.ordinal()] = gamekeydown[SC_LSHIFT.ordinal()] = false; - break; - case SC_LCTRL: - case SC_RCTRL: - gamekeydown[SC_RCTRL.ordinal()] = gamekeydown[SC_LCTRL.ordinal()] = false; - break; - case SC_LALT: - case SC_RALT: - gamekeydown[SC_RALT.ordinal()] = gamekeydown[SC_LALT.ordinal()] = false; - break; - default: break; - } + handleVanillaKeys(sc, false); } }); return false; // always let key up events filter down @@ -1368,7 +1423,38 @@ public boolean Responder(event_t ev) { return false; } - private final String turbomessage="is turbo!"; + private void handleVanillaKeys(Signals.ScanCode sc, boolean keyDown) { + switch (sc) { + case SC_LSHIFT: + case SC_RSHIFT: + gamekeydown[SC_RSHIFT.ordinal()] = gamekeydown[SC_LSHIFT.ordinal()] = keyDown; + break; + case SC_LCTRL: + case SC_RCTRL: + gamekeydown[SC_RCTRL.ordinal()] = gamekeydown[SC_LCTRL.ordinal()] = keyDown; + break; + case SC_LALT: + case SC_RALT: + gamekeydown[SC_RALT.ordinal()] = gamekeydown[SC_LALT.ordinal()] = keyDown; + break; + case SC_UP: + gamekeydown[SC_NUMKEY8.ordinal()] = keyDown; + break; + case SC_DOWN: + gamekeydown[SC_NUMKEY2.ordinal()] = keyDown; + break; + case SC_LEFT: + gamekeydown[SC_NUMKEY4.ordinal()] = keyDown; + break; + case SC_RIGHT: + gamekeydown[SC_NUMKEY6.ordinal()] = keyDown; + break; + default: + break; + } + } + + private final String turbomessage = "is turbo!"; /** * G_Ticker @@ -1376,46 +1462,53 @@ public boolean Responder(event_t ev) { * Make ticcmd_ts for the players. */ @G_Game.C(G_Ticker) - public void Ticker() { + public void Ticker() { // do player reborns if needed for (int i = 0; i < MAXPLAYERS; i++) { if (playeringame[i] && players[i].playerstate == PST_REBORN) { - G_DoReborn: { + G_DoReborn: + { DoReborn(i); } } } // do things to change the game state - while (gameaction != ga_nothing) { - switch (gameaction) { + while (gameaction != ga_nothing) { + switch (gameaction) { case ga_loadlevel: - G_DoLoadLevel: { + G_DoLoadLevel: + { DoLoadLevel(); } break; case ga_newgame: - G_DoNewGame: { + G_DoNewGame: + { DoNewGame(); } break; case ga_loadgame: - G_DoLoadGame: { + G_DoLoadGame: + { DoLoadGame(); } break; case ga_savegame: - G_DoSaveGame: { + G_DoSaveGame: + { DoSaveGame(); } break; case ga_playdemo: - G_DoPlayDemo: { + G_DoPlayDemo: + { DoPlayDemo(); } break; case ga_completed: - G_DoCompleted: { + G_DoCompleted: + { DoCompleted(); } break; @@ -1432,7 +1525,7 @@ public void Ticker() { case ga_nothing: break; default: - break; + break; } } @@ -1453,7 +1546,7 @@ public void Ticker() { if (demoplayback) { ReadDemoTiccmd(cmd); } - + if (demorecording) { WriteDemoTiccmd(cmd); } @@ -1469,7 +1562,7 @@ public void Ticker() { if (gametic > BACKUPTICS && consistancy[i][buf] != cmd.consistancy) { doomSystem.Error("consistency failure (%d should be %d)", cmd.consistancy, consistancy[i][buf]); } - + if (players[i].mo != null) { consistancy[i][buf] = (short) players[i].mo.x; } else { @@ -1525,17 +1618,16 @@ public void Ticker() { case GS_DEMOSCREEN: PageTicker(); break; - + default: - break; + break; } - } + } // // PLAYER STRUCTURE FUNCTIONS // also see P_SpawnPlayer in P_Things // - /** * G_InitPlayer * Called at the start. @@ -1572,7 +1664,8 @@ private boolean CheckSpot(int playernum, mapthing_t mthing) { final int x = mthing.x << FRACBITS, y = mthing.y << FRACBITS; - P_CheckPosition: { + P_CheckPosition: + { if (!actions.CheckPosition(players[playernum].mo, x, y)) { return false; } @@ -1580,7 +1673,8 @@ private boolean CheckSpot(int playernum, mapthing_t mthing) { // flush an old corpse if needed if (bodyqueslot >= BODYQUESIZE) { - P_RemoveMobj: { + P_RemoveMobj: + { actions.RemoveMobj(bodyque[bodyqueslot % BODYQUESIZE]); } } @@ -1589,27 +1683,29 @@ private boolean CheckSpot(int playernum, mapthing_t mthing) { // spawn a teleport fog final subsector_t ss; - R_PointInSubsector: { + R_PointInSubsector: + { ss = levelLoader.PointInSubsector(x, y); } // Angles stored in things are supposed to be "sanitized" against rollovers. final int angle = (int) ((ANG45 * (mthing.angle / 45)) >>> ANGLETOFINESHIFT); final mobj_t mo; - P_SpawnMobj: { - mo = actions.SpawnMobj(x + 20 * finecosine[angle], y + 20 * finesine[angle], ss.sector.floorheight, mobjtype_t.MT_TFOG); + P_SpawnMobj: + { + mo = actions.SpawnMobj(x + 20 * finecosine[angle], y + 20 * finesine[angle], ss.sector.floorheight, mobjtype_t.MT_TFOG); } // FIXME: maybe false fix if (players[consoleplayer].viewz != 1) { - S_StartSound: { + S_StartSound: + { doomSound.StartSound(mo, sfxenum_t.sfx_telept); // don't start sound on first frame } } - + return true; } - // // G_DeathMatchSpawnPlayer // Spawns a player at one of the random death match spots @@ -1619,22 +1715,26 @@ private boolean CheckSpot(int playernum, mapthing_t mthing) { @SourceCode.Exact @G_Game.C(G_DeathMatchSpawnPlayer) public void DeathMatchSpawnPlayer(int playernum) { - final int selections = deathmatch_p; - if (selections < 4) { - I_Error: { + final int selections = deathmatch_p; + if (selections < 4) { + I_Error: + { doomSystem.Error("Only %d deathmatch spots, 4 required", selections); - } + } } for (int j = 0; j < 20; j++) { final int i; - P_Random: { + P_Random: + { i = random.P_Random() % selections; } - G_CheckSpot: { + G_CheckSpot: + { if (CheckSpot(playernum, deathmatchstarts[i])) { deathmatchstarts[i].type = (short) (playernum + 1); - P_SpawnPlayer: { + P_SpawnPlayer: + { actions.SpawnPlayer(deathmatchstarts[i]); } return; @@ -1644,7 +1744,8 @@ public void DeathMatchSpawnPlayer(int playernum) { // no good spot, so the player will probably get stuck // MAES: seriously, fuck him. - P_SpawnPlayer: { + P_SpawnPlayer: + { actions.SpawnPlayer(playerstarts[playernum]); } } @@ -1654,27 +1755,30 @@ public void DeathMatchSpawnPlayer(int playernum) { */ @SourceCode.Exact @G_Game.C(G_DoReborn) - public void DoReborn (int playernum) { + public void DoReborn(int playernum) { if (!netgame) { // reload the level from scratch - gameaction = ga_loadlevel; + gameaction = ga_loadlevel; } else { // respawn at the start // first dissasociate the corpse - players[playernum].mo.player = null; + players[playernum].mo.player = null; // spawn at random spot if in death match if (deathmatch) { - G_DeathMatchSpawnPlayer: { + G_DeathMatchSpawnPlayer: + { DeathMatchSpawnPlayer(playernum); } return; } - G_CheckSpot: { + G_CheckSpot: + { if (CheckSpot(playernum, playerstarts[playernum])) { - P_SpawnPlayer: { + P_SpawnPlayer: + { actions.SpawnPlayer(playerstarts[playernum]); } return; @@ -1683,10 +1787,12 @@ public void DoReborn (int playernum) { // try to spawn at one of the other players spots for (int i = 0; i < MAXPLAYERS; i++) { - G_CheckSpot: { + G_CheckSpot: + { if (CheckSpot(playernum, playerstarts[i])) { playerstarts[i].type = (short) (playernum + 1); // fake as other player - P_SpawnPlayer: { + P_SpawnPlayer: + { actions.SpawnPlayer(playerstarts[i]); } playerstarts[i].type = (short) (i + 1); // restore @@ -1696,30 +1802,30 @@ public void DoReborn (int playernum) { // he's going to be inside something. Too bad. // MAES: Yeah, they're like, fuck him. } - - P_SpawnPlayer: { + + P_SpawnPlayer: + { actions.SpawnPlayer(playerstarts[playernum]); } - } - } + } + } /** DOOM Par Times [4][10] */ - final int[][] pars = { - {0}, - {0,30,75,120,90,165,180,180,30,165}, - {0,90,90,90,120,90,360,240,30,170}, - {0,90,45,90,150,90,90,165,30,135} - }; + final int[][] pars = { + {0}, + {0, 30, 75, 120, 90, 165, 180, 180, 30, 165}, + {0, 90, 90, 90, 120, 90, 360, 240, 30, 170}, + {0, 90, 45, 90, 150, 90, 90, 165, 30, 135} + }; /** DOOM II Par Times */ final int[] cpars = { - 30,90,120,120,90,150,120,120,270,90, // 1-10 - 210,150,150,150,210,150,420,150,210,150, // 11-20 - 240,150,180,150,150,300,330,420,300,180, // 21-30 - 120,30 // 31-32 + 30, 90, 120, 120, 90, 150, 120, 120, 270, 90, // 1-10 + 210, 150, 150, 150, 210, 150, 420, 150, 210, 150, // 11-20 + 240, 150, 180, 150, 150, 300, 330, 420, 300, 180, // 21-30 + 120, 30 // 31-32 }; - // // G_DoCompleted // @@ -1744,14 +1850,16 @@ protected void DoCompleted() { for (int i = 0; i < MAXPLAYERS; i++) { if (playeringame[i]) { - G_PlayerFinishLevel: { // take away cards and stuff + G_PlayerFinishLevel: + { // take away cards and stuff players[i].PlayerFinishLevel(); } } } if (automapactive) { - AM_Stop: { + AM_Stop: + { autoMap.Stop(); } } @@ -1780,7 +1888,7 @@ protected void DoCompleted() { // wminfo.next is 0 biased, unlike gamemap if (isCommercial()) { if (secretexit) { - switch(gamemap) { + switch (gamemap) { case 2: wminfo.next = 32; //Fix Doom 3 BFG Edition, MAP02 secret exit to MAP33 Betray break; @@ -1793,16 +1901,18 @@ protected void DoCompleted() { default: break; } - } else switch(gamemap) { - case 31: - case 32: - wminfo.next = 15; - break; - case 33: - wminfo.next = 2; //Fix Doom 3 BFG Edition, MAP33 Betray exit back to MAP03 - break; - default: - wminfo.next = gamemap; + } else { + switch (gamemap) { + case 31: + case 32: + wminfo.next = 15; + break; + case 33: + wminfo.next = 2; //Fix Doom 3 BFG Edition, MAP33 Betray exit back to MAP03 + break; + default: + wminfo.next = gamemap; + } } } else { if (secretexit) { @@ -1834,7 +1944,7 @@ protected void DoCompleted() { wminfo.maxitems = totalitems; wminfo.maxsecret = totalsecret; wminfo.maxfrags = 0; - + if (isCommercial()) { wminfo.partime = 35 * cpars[gamemap - 1]; } else if (gameepisode >= pars.length) { @@ -1842,8 +1952,8 @@ protected void DoCompleted() { } else { wminfo.partime = 35 * pars[gameepisode][gamemap]; } - - wminfo.pnum = consoleplayer; + + wminfo.pnum = consoleplayer; for (int i = 0; i < MAXPLAYERS; i++) { wminfo.plyr[i].in = playeringame[i]; @@ -1852,27 +1962,27 @@ protected void DoCompleted() { wminfo.plyr[i].ssecret = players[i].secretcount; wminfo.plyr[i].stime = leveltime; memcpy(wminfo.plyr[i].frags, players[i].frags, wminfo.plyr[i].frags.length); - } + } - gamestate = GS_INTERMISSION; - viewactive = false; - automapactive = false; + gamestate = GS_INTERMISSION; + viewactive = false; + automapactive = false; if (statcopy != null) { memcpy(statcopy, wminfo, 1); } - WI_Start: { + WI_Start: + { endLevel.Start(wminfo); - } - } - + } + } /** * G_WorldDone */ public void WorldDone() { - gameaction = ga_worlddone; + gameaction = ga_worlddone; if (secretexit) { players[consoleplayer].didsecret = true; @@ -1893,7 +2003,7 @@ public void WorldDone() { break; } } - } + } public void DoWorldDone() { gamestate = GS_LEVEL; @@ -1901,7 +2011,7 @@ public void DoWorldDone() { DoLoadLevel(); gameaction = ga_nothing; viewactive = true; - } + } // // G_InitFromSavegame @@ -1952,7 +2062,8 @@ protected void DoLoadGame() { System.arraycopy(header.getPlayeringame(), 0, playeringame, 0, MAXPLAYERS); // load a base level - G_InitNew: { + G_InitNew: + { InitNew(gameskill, gameepisode, gamemap); } @@ -1970,9 +2081,10 @@ protected void DoLoadGame() { boolean ok; // dearchive all the modifications P_UnArchivePlayers: - P_UnArchiveWorld: + P_UnArchiveWorld: P_UnArchiveThinkers: - P_UnArchiveSpecials: { + P_UnArchiveSpecials: + { ok = dsg.doLoad(f); } f.close(); @@ -1984,7 +2096,8 @@ protected void DoLoadGame() { // a "tentative loading" subsystem, which will only alter the game // if everything works out without errors. But who cares :-p if (!ok) { - I_Error: { + I_Error: + { doomSystem.Error("Bad savegame"); } } @@ -1992,17 +2105,19 @@ protected void DoLoadGame() { // done //Z_Free (savebuffer); if (sceneRenderer.getSetSizeNeeded()) { - R_ExecuteSetViewSize: { + R_ExecuteSetViewSize: + { sceneRenderer.ExecuteSetViewSize(); } } // draw the pattern into the back screen - R_FillBackScreen: { + R_FillBackScreen: + { sceneRenderer.FillBackScreen(); } } catch (IOException e) { - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Failure loading game.", e); } } @@ -2029,12 +2144,13 @@ protected void DoSaveGame() { IDoomSaveGameHeader header = new VanillaDSGHeader(); IDoomSaveGame dsg = new VanillaDSG<>(this); - M_CheckParm: { + M_CheckParm: + { if (cVarManager.bool(CommandVariable.CDROM)) { build.append("c:\\doomdata\\"); } } - + build.append(String.format("%s%d.dsg", SAVEGAMENAME, savegameslot)); name = build.toString(); @@ -2050,16 +2166,17 @@ protected void DoSaveGame() { dsg.setHeader(header); // Try opening a save file. No intermediate buffer (performance?) - try (DataOutputStream f = new DataOutputStream(new FileOutputStream(name))) { + try ( DataOutputStream f = new DataOutputStream(new FileOutputStream(name))) { P_ArchivePlayers: P_ArchiveWorld: P_ArchiveThinkers: - P_ArchiveSpecials: { + P_ArchiveSpecials: + { boolean ok = dsg.doSave(f); } } } catch (IOException e) { - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Failure saving game.", e); } // Saving is not as destructive as loading. @@ -2069,7 +2186,8 @@ protected void DoSaveGame() { players[consoleplayer].message = GGSAVED; // draw the pattern into the back screen - R_FillBackScreen: { + R_FillBackScreen: + { sceneRenderer.FillBackScreen(); } } @@ -2079,11 +2197,11 @@ protected void DoSaveGame() { int d_map; public void DeferedInitNew(skill_t skill, int episode, int map) { - d_skill = skill; - d_episode = episode; - d_map = map; - gameaction = ga_newgame; - } + d_skill = skill; + d_episode = episode; + d_map = map; + gameaction = ga_newgame; + } @SourceCode.Exact @G_Game.C(G_DoNewGame) @@ -2097,11 +2215,12 @@ public void DoNewGame() { fastparm = false; nomonsters = false; consoleplayer = 0; - G_InitNew: { + G_InitNew: + { InitNew(d_skill, d_episode, d_map); } gameaction = ga_nothing; - } + } /** * G_InitNew @@ -2110,14 +2229,18 @@ public void DoNewGame() { */ @SourceCode.Compatible @G_Game.C(G_InitNew) - public void InitNew(skill_t skill, int episode, int map) { InitNew(skill, episode, map, false); } + public void InitNew(skill_t skill, int episode, int map) { + InitNew(skill, episode, map, false); + } + private void InitNew(skill_t skill, int episode, int map, boolean noSwitchRandom) { - if (paused) { - paused = false; - S_ResumeSound: { + if (paused) { + paused = false; + S_ResumeSound: + { doomSound.ResumeSound(); - } - } + } + } if (skill.ordinal() > skill_t.sk_nightmare.ordinal()) { skill = skill_t.sk_nightmare; @@ -2144,8 +2267,9 @@ private void InitNew(skill_t skill, int episode, int map, boolean noSwitchRandom } } - if (map < 1) + if (map < 1) { map = 1; + } if ((map > 9) && (!isCommercial())) { map = 9; @@ -2165,18 +2289,19 @@ private void InitNew(skill_t skill, int episode, int map, boolean noSwitchRandom } } - M_ClearRandom: { - random.ClearRandom (); + M_ClearRandom: + { + random.ClearRandom(); } - + respawnmonsters = skill == skill_t.sk_nightmare || respawnparm; // If on nightmare/fast monsters make everything MOAR pimp. - if (fastparm || (skill == skill_t.sk_nightmare && gameskill != skill_t.sk_nightmare) ) { + if (fastparm || (skill == skill_t.sk_nightmare && gameskill != skill_t.sk_nightmare)) { for (int i = statenum_t.S_SARG_RUN1.ordinal(); i <= statenum_t.S_SARG_PAIN2.ordinal(); i++) { states[i].tics >>= 1; } - + mobjinfo[mobjtype_t.MT_BRUISERSHOT.ordinal()].speed = 20 * MAPFRACUNIT; mobjinfo[mobjtype_t.MT_HEADSHOT.ordinal()].speed = 20 * MAPFRACUNIT; mobjinfo[mobjtype_t.MT_TROOPSHOT.ordinal()].speed = 20 * MAPFRACUNIT; @@ -2184,11 +2309,11 @@ private void InitNew(skill_t skill, int episode, int map, boolean noSwitchRandom for (int i = statenum_t.S_SARG_RUN1.ordinal(); i <= statenum_t.S_SARG_PAIN2.ordinal(); i++) { states[i].tics <<= 1; } - + mobjinfo[mobjtype_t.MT_BRUISERSHOT.ordinal()].speed = 15 * MAPFRACUNIT; mobjinfo[mobjtype_t.MT_HEADSHOT.ordinal()].speed = 10 * MAPFRACUNIT; mobjinfo[mobjtype_t.MT_TROOPSHOT.ordinal()].speed = 10 * MAPFRACUNIT; - } + } // force players to be initialized upon first level load for (int i = 0; i < MAXPLAYERS; i++) { @@ -2197,13 +2322,13 @@ private void InitNew(skill_t skill, int episode, int map, boolean noSwitchRandom // will be set false if a demo usergame = true; - paused = false; - demoplayback = false; - automapactive = false; - viewactive = true; - gameepisode = episode; - gamemap = map; - gameskill = skill; + paused = false; + demoplayback = false; + automapactive = false; + viewactive = true; + gameepisode = episode; + gamemap = map; + gameskill = skill; viewactive = true; // set the sky map for the episode @@ -2233,15 +2358,16 @@ private void InitNew(skill_t skill, int episode, int map, boolean noSwitchRandom } } - G_DoLoadLevel: { + G_DoLoadLevel: + { if (!DoLoadLevel()) { levelLoadFailure(); } } - } + } protected void levelLoadFailure() { - boolean endgame = doomSystem.GenerateAlert(Strings.LEVEL_FAILURE_TITLE, Strings.LEVEL_FAILURE_CAUSE); + boolean endgame = doomSystem.GenerateAlert(Strings.LEVEL_FAILURE_TITLE, Strings.LEVEL_FAILURE_CAUSE, true); // Initiate endgame if (endgame) { @@ -2259,25 +2385,25 @@ protected void levelLoadFailure() { // DEMO RECORDING // public void ReadDemoTiccmd(ticcmd_t cmd) { - final IDemoTicCmd democmd=demobuffer.getNextTic(); - if (democmd == null) { + final IDemoTicCmd democmd = demobuffer.getNextTic(); + if (democmd == null) { // end of demo data stream - CheckDemoStatus (); + CheckDemoStatus(); // Force status resetting this.demobuffer.resetDemo(); - return; + return; } - democmd.decode(cmd); - } + democmd.decode(cmd); + } public void WriteDemoTiccmd(ticcmd_t cmd) { // press q to end demo recording if (gamekeydown[key_recordstop]) { CheckDemoStatus(); } - + final IDemoTicCmd reccmd = new VanillaTiccmd(); reccmd.encode(cmd); demobuffer.putTic(reccmd); @@ -2294,17 +2420,16 @@ public void WriteDemoTiccmd(ticcmd_t cmd) { // no more space CheckDemoStatus (); return; - } */ - + } */ //ReadDemoTiccmd (cmd); // make SURE it is exactly the same // MAES: this is NOT the way to do in Mocha, because we are not manipulating // the demo index directly anymore. Instead, decode what we have just saved. reccmd.decode(cmd); - } + } /** * G_RecordDemo - */ + */ public void RecordDemo(String name) { StringBuffer buf = new StringBuffer(); usergame = false; @@ -2328,9 +2453,9 @@ public void BeginRecording() { demobuffer.setConsoleplayer(consoleplayer); demobuffer.setPlayeringame(playeringame); } - + String defdemoname; - + /** * G_PlayDemo */ @@ -2350,7 +2475,8 @@ public void DoPlayDemo() { gameaction = ga_nothing; // MAES: Yeah, it's OO all the way now, baby ;-) - W_CacheLumpName: { + W_CacheLumpName: + { try { demobuffer = wadLoader.CacheLumpName(defdemoname.toUpperCase(), PU_STATIC, VanillaDoomDemo.class); } catch (Exception e) { @@ -2362,12 +2488,12 @@ public void DoPlayDemo() { final int version; if (fail || ((version = demobuffer.getVersion() & 0xFF) & ~JAVARANDOM_MASK) != VERSION) { - System.err.println("Demo is from a different game version!\n"); - System.err.println("Version code read: " + demobuffer.getVersion()); + LOGGER.log(Level.WARNING, String.format("Demo is from a different game version, version code read: %d", + demobuffer.getVersion())); gameaction = ga_nothing; return; } - + random.requireRandom(version); skill = demobuffer.getSkill(); @@ -2392,7 +2518,8 @@ public void DoPlayDemo() { // don't spend a lot of time in loadlevel precache = false; - G_InitNew: { + G_InitNew: + { InitNew(skill, episode, map, true); } precache = true; @@ -2405,47 +2532,42 @@ public void DoPlayDemo() { // // G_TimeDemo // - public void TimeDemo (String name) - { + public void TimeDemo(String name) { nodrawers = cVarManager.bool(CommandVariable.NODRAW); noblit = cVarManager.bool(CommandVariable.NOBLIT); - timingdemo = true; + timingdemo = true; singletics = true; defdemoname = name; - gameaction = ga_playdemo; - } + gameaction = ga_playdemo; + } - /** G_CheckDemoStatus * * Called after a death or level completion to allow demos to be cleaned up * Returns true if a new demo loop action will take place * - */ + */ + public boolean CheckDemoStatus() { + int endtime; - public boolean CheckDemoStatus () - { - int endtime; - - if (timingdemo) - { - endtime = RealTime.GetTime (); + if (timingdemo) { + endtime = RealTime.GetTime(); // killough -- added fps information and made it work for longer demos: - long realtics=endtime-starttime; - + long realtics = endtime - starttime; + this.commit(); CM.SaveDefaults(); - doomSystem.Error ("timed %d gametics in %d realtics = %f frames per second",gametic - , realtics, gametic*(double)(TICRATE)/realtics); + doomSystem.Error("timed %d gametics in %d realtics = %f frames per second", gametic, + realtics, gametic * (double) (TICRATE) / realtics); } - if (demoplayback) - { - if (singledemo) - doomSystem.Quit (); + if (demoplayback) { + if (singledemo) { + doomSystem.Quit(); + } // Z_ChangeTag (demobuffer, PU_CACHE); - demoplayback = false; + demoplayback = false; netdemo = false; netgame = false; deathmatch = false; @@ -2454,29 +2576,28 @@ public boolean CheckDemoStatus () fastparm = false; nomonsters = false; consoleplayer = 0; - AdvanceDemo (); - return true; - } + AdvanceDemo(); + return true; + } - if (demorecording) - { + if (demorecording) { //demobuffer[demo_p++] = (byte) DEMOMARKER; - MenuMisc.WriteFile(demoname, demobuffer); + MenuMisc.WriteFile(demoname, demobuffer); //Z_Free (demobuffer); - demorecording = false; - doomSystem.Error ("Demo %s recorded",demoname); - } + demorecording = false; + doomSystem.Error("Demo %s recorded", demoname); + } - return false; - } + return false; + } /** This should always be available for real timing */ protected ITicker RealTime; - + // Bookkeeping on players - state. public player_t[] players; - + public DelegateRandom random; public final CVarManager cVarManager; public final IWadLoader wadLoader; @@ -2498,7 +2619,7 @@ public boolean CheckDemoStatus () public final Wiper wiper; public final TextureManager textureManager; public final ISpriteManager spriteManager; - public final ITicker ticker; + public final ITicker ticker; public final IDiskDrawer diskDrawer; public final IDoomSystem doomSystem; public final BppMode bppMode; @@ -2522,7 +2643,7 @@ public DoomMain() throws IOException { super(); // Init players - players = new player_t[MAXPLAYERS]; + players = new player_t[MAXPLAYERS]; Arrays.setAll(players, i -> new player_t(this)); // Init objects @@ -2533,42 +2654,41 @@ public DoomMain() throws IOException { // Create DoomSystem this.doomSystem = new DoomSystem(this); - + // Choose bppMode depending on CVar's // TODO: add config options this.bppMode = BppMode.chooseBppMode(cVarManager); - + // Create real time ticker this.RealTime = new MilliTicker(); // Doommain is both "main" and handles most of the game status. this.gameNetworking = this; // DoomMain also handles its own Game Networking. - + // Set ticker. It is a shared status object, but not a holder itself. this.ticker = ITicker.createTicker(cVarManager); - + // Network "driver" this.systemNetworking = new DummyNetworkDriver<>(this); - + // Random number generator, but we can have others too. this.random = new DelegateRandom(); - System.out.print(String.format("M_Random: Using %s.\n", random.getClass().getSimpleName())); - + LOGGER.log(Level.INFO, String.format("M_Random: Using %s.", random.getClass().getSimpleName())); + // Sound can be left until later, in Start this.wadLoader = new WadLoader(this.doomSystem); // The wadloader is a "weak" status holder. - + // TODO: find out if we have requests for a specific resolution, // and try honouring them as closely as possible. - // 23/5/2011: Experimental dynamic resolution subsystem this.vs = VisualSettings.parse(cVarManager); this.spriteManager = new SpriteManager<>(this); - + // Heads-up, Menu, Level Loader this.headsUp = new HU(this); this.menu = new Menu<>(this); this.levelLoader = new BoomLevelLoader(this); - + // Renderer, Actions, StatusBar, AutoMap this.sceneRenderer = bppMode.sceneRenderer(this); this.actions = new ActionFunctions(this); @@ -2579,32 +2699,32 @@ public DoomMain() throws IOException { // Instantiating EndLevel, Finale this.endLevel = new EndLevel<>(this); this.finale = selectFinale(); - + readCVars(); - System.out.print("W_Init: Init WADfiles.\n"); + LOGGER.log(Level.INFO, String.format("W_Init: Init WAD files: [%s]", + Arrays.stream(wadfiles).filter(Objects::nonNull).collect(Collectors.joining(", ")))); try { wadLoader.InitMultipleFiles(wadfiles); } catch (Exception e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); + LOGGER.log(Level.SEVERE, "Could not init WAD files", e1); } - + // Video Renderer - this.graphicSystem = RendererFactory. newBuilder() - .setVideoScale(vs).setBppMode(bppMode).setWadLoader(wadLoader) - .build(); - - System.out.print("V_Init: allocate screens.\n"); - + this.graphicSystem = RendererFactory.newBuilder() + .setVideoScale(vs).setBppMode(bppMode).setWadLoader(wadLoader) + .build(); + + LOGGER.log(Level.INFO, "V_Init: Allocate screens."); + // Disk access visualizer this.diskDrawer = new DiskDrawer(this, DiskDrawer.STDISK); - + // init subsystems - System.out.print("AM_Init: Init Automap colors - \n"); + LOGGER.log(Level.INFO, "AM_Init: Init Automap colors."); this.autoMap = new automap.Map<>(this); this.wiper = graphicSystem.createWiper(random); - + // Update variables and stuff NOW. this.update(); @@ -2613,26 +2733,25 @@ public DoomMain() throws IOException { printGameInfo(); - System.out.print("Tables.InitTables: Init trigonometric LUTs.\n"); + LOGGER.log(Level.INFO, "Tables.InitTables: Init trigonometric LUTs."); Tables.InitTables(); - System.out.print("M_Init: Init miscellaneous info.\n"); + LOGGER.log(Level.INFO, "M_Init: Init miscellaneous info."); menu.Init(); - System.out.print("R_Init: Init DOOM refresh daemon - "); + LOGGER.log(Level.INFO, "R_Init: Init DOOM refresh daemon."); sceneRenderer.Init(); - System.out.print("\nP_Init: Init Playloop state.\n"); + LOGGER.log(Level.INFO, "P_Init: Init Playloop state."); actions.Init(); - System.out.print("I_Init: Setting up machine state.\n"); + LOGGER.log(Level.INFO, "I_Init: Setting up machine state."); doomSystem.Init(); - System.out.print("D_CheckNetGame: Checking network game status.\n"); + LOGGER.log(Level.INFO, "D_CheckNetGame: Checking network game status."); CheckNetGame(); - System.out.print("S_Init: Setting up sound.\n"); - + LOGGER.log(Level.INFO, "S_Init: Setting up sound."); // Sound "drivers" before the game sound controller. this.music = IMusic.chooseModule(cVarManager); this.soundDriver = ISoundDriver.chooseModule(this, cVarManager); @@ -2641,14 +2760,14 @@ public DoomMain() throws IOException { music.InitMusic(); doomSound.Init(snd_SfxVolume * 8, snd_MusicVolume * 8); - System.out.print("HU_Init: Setting up heads up display.\n"); + LOGGER.log(Level.INFO, "HU_Init: Setting up heads up display."); headsUp.Init(); - System.out.print("ST_Init: Init status bar.\n"); + LOGGER.log(Level.INFO, "ST_Init: Init status bar."); statusBar.Init(); if (statcopy != null) { - System.out.print("External statistics registered.\n"); + LOGGER.log(Level.INFO, "External statistics registered."); } // NOW it's safe to init the disk reader. @@ -2688,13 +2807,13 @@ public final void commit() { CM.update(Settings.valueOf(String.format("chatmacro%d", i)), this.headsUp.chat_macros[i]); } } - + public void setupLoop() throws IOException { // check for a driver that wants intermission stats cVarManager.with(CommandVariable.STATCOPY, 0, (String s) -> { // TODO: this should be chained to a logger statcopy = s; - System.out.print("External statistics registered.\n"); + LOGGER.log(Level.INFO, "External statistics registered."); }); // start the apropriate game based on parms @@ -2704,7 +2823,8 @@ public void setupLoop() throws IOException { }); //p = CM.CheckParm ("-timedemo"); - ChooseLoop: { + ChooseLoop: + { if (singletics) { TimeDemo(loaddemo); autostart = true; @@ -2738,19 +2858,17 @@ private void printGameInfo() { // Iff additonal PWAD files are used, print modified banner if (modifiedgame) // Generate WAD loading alert. Abort upon denial. { - if (!doomSystem.GenerateAlert(Strings.MODIFIED_GAME_TITLE, Strings.MODIFIED_GAME_DIALOG)) { + if (!doomSystem.GenerateAlert(Strings.MODIFIED_GAME_TITLE, Strings.MODIFIED_GAME_DIALOG, true)) { wadLoader.CloseAllHandles(); System.exit(-2); } } - + // Check and print which version is executed. switch (getGameMode()) { case shareware: case indetermined: - System.out.print("===========================================================================\n"); - System.out.print(" Shareware!\n"); - System.out.print("===========================================================================\n"); + LOGGER.log(Level.INFO, "Game Info: Shareware!"); break; case registered: case retail: @@ -2758,19 +2876,14 @@ private void printGameInfo() { case pack_tnt: case pack_plut: case pack_xbla: - System.out.print("===========================================================================\n"); - System.out.print(" Commercial product - do not distribute!\n"); - System.out.print(" Please report software piracy to the SPA: 1-800-388-PIR8\n"); - System.out.print("===========================================================================\n"); + LOGGER.log(Level.INFO, "Game Info: Commercial product - do not distribute!"); + LOGGER.log(Level.INFO, "Game Note: Please report software piracy to the SPA: 1-800-388-PIR8"); break; case freedoom1: case freedoom2: case freedm: - System.out.print("===========================================================================\n"); - System.out.print(" Copyright © 2001-2017 Contributors to the Freedoom project.\n"); - System.out.print(" All rights reserved.\n"); - System.out.print(" See: https://github.com/freedoom/freedoom/blob/master/COPYING.adoc\n"); - System.out.print("===========================================================================\n"); + LOGGER.log(Level.INFO, "Game Info: Copyright (c) 2001-2017 Contributors to the Freedoom project. All rights reserved."); + LOGGER.log(Level.INFO, "Game Note: See https://github.com/freedoom/freedoom/blob/master/COPYING.adoc"); break; default: // Ouch. @@ -2784,14 +2897,14 @@ private void readCVars() { * * Completes the job started by Init. Here everything priority-critical is called and created in more detail. */ - + final StringBuffer file = new StringBuffer(); final String iwadfilename = IdentifyVersion(); nomonsters = cVarManager.bool(CommandVariable.NOMONSTERS); respawnparm = cVarManager.bool(CommandVariable.RESPAWN); fastparm = cVarManager.bool(CommandVariable.FAST); devparm = cVarManager.bool(CommandVariable.DEVPARM); - + if (!(altdeath = cVarManager.bool(CommandVariable.ALTDEATH))) { deathmatch = cVarManager.bool(CommandVariable.DEATHMATCH); } @@ -2800,29 +2913,32 @@ private void readCVars() { final WadLoader tmpwad = new WadLoader(); try { tmpwad.InitFile(iwadfilename); + // Check using a reloadable hack. + CheckForUltimateDoom(tmpwad); } catch (Exception e2) { // TODO Auto-generated catch block - e2.printStackTrace(); + LOGGER.log(Level.SEVERE, "Failure reading CVars.", e2); + } finally { + tmpwad.CloseAllHandles(); } - // Check using a reloadable hack. - CheckForUltimateDoom(tmpwad); + // MAES: better extract a method for this. GenerateTitle(); // Print ticker info. It has already been set at Init() though. if (cVarManager.bool(CommandVariable.MILLIS)) { - System.out.println("ITicker: Using millisecond accuracy timer."); + LOGGER.log(Level.INFO, "ITicker: Using millisecond accuracy timer."); } else if (cVarManager.bool(CommandVariable.FASTTIC)) { - System.out.println("ITicker: Using fastest possible timer."); + LOGGER.log(Level.INFO, "ITicker: Using fastest possible timer."); } else { - System.out.println("ITicker: Using nanosecond accuracy timer."); + LOGGER.log(Level.INFO, "ITicker: Using nanosecond accuracy timer."); } - System.out.println(title.toString()); + LOGGER.log(Level.INFO, title.toString()); if (devparm) { - System.out.println(D_DEVSTR); + LOGGER.log(Level.INFO, D_DEVSTR); } // Running from CDROM? if (cVarManager.bool(CommandVariable.CDROM)) { - System.out.println(D_CDROM); + LOGGER.log(Level.INFO, D_CDROM); //System.get("c:\\doomdata",0); //System.out.println (Settings.basedefault+"c:/doomdata/default.cfg"); } @@ -2838,7 +2954,7 @@ private void readCVars() { if (scale > 400) { scale = 400; } - System.out.println("turbo scale: " + scale); + LOGGER.log(Level.INFO, String.format("turbo scale: %d", scale)); forwardmove[0] = forwardmove[0] * scale / 100; forwardmove[1] = forwardmove[1] * scale / 100; sidemove[0] = sidemove[0] * scale / 100; @@ -2882,38 +2998,38 @@ private void readCVars() { } AddFile(file.toString()); } - + if (cVarManager.present(CommandVariable.FILE)) { // the parms after p are wadfile/lump names, // until end of parms or another - preceded parm modifiedgame = true; // homebrew levels cVarManager.with(CommandVariable.FILE, 0, (String[] a) -> { Arrays.stream(a) - .map(s -> C2JUtils.unquoteIfQuoted(s, '"')) - .forEach(this::AddFile); + .map(s -> C2JUtils.unquoteIfQuoted(s, '"')) + .forEach(this::AddFile); }); } - + if (cVarManager.present(CommandVariable.PLAYDEMO)) { normaldemo = true; loaddemo = cVarManager.get(CommandVariable.PLAYDEMO, String.class, 0).get(); } else if (cVarManager.present(CommandVariable.FASTDEMO)) { - System.out.println("Fastdemo mode. Boundless clock!"); + LOGGER.log(Level.INFO, "Fastdemo mode. Boundless clock!"); fastdemo = true; loaddemo = cVarManager.get(CommandVariable.FASTDEMO, String.class, 0).get(); } else if (cVarManager.present(CommandVariable.TIMEDEMO)) { singletics = true; loaddemo = cVarManager.get(CommandVariable.TIMEDEMO, String.class, 0).get(); } - + // If any of the previous succeeded, try grabbing the filename. if (loaddemo != null) { loaddemo = C2JUtils.unquoteIfQuoted(loaddemo, '"'); AddFile(loaddemo + ".lmp"); - System.out.printf("Playing demo %s.lmp.\n", loaddemo); + LOGGER.log(Level.INFO, String.format("Playing demo %s.lmp.", loaddemo)); autostart = true; } - + // Subsequent uses of loaddemo use only the lump name. loaddemo = C2JUtils.extractFileBase(loaddemo, 0, true); // get skill / episode / map from parms @@ -2925,13 +3041,13 @@ private void readCVars() { if (cVarManager.present(CommandVariable.NOVERT)) { novert = cVarManager.get(CommandVariable.NOVERT, CommandVariable.ForbidFormat.class, 0) - .filter(CommandVariable.ForbidFormat.FORBID::equals) - .isPresent(); - + .filter(CommandVariable.ForbidFormat.FORBID::equals) + .isPresent(); + if (!novert) { - System.out.println("-novert ENABLED (default)"); + LOGGER.log(Level.INFO, "-novert ENABLED (default)"); } else { - System.out.println("-novert DISABLED. Hope you know what you're doing..."); + LOGGER.log(Level.INFO, "-novert DISABLED. Hope you know what you're doing..."); } } @@ -2945,21 +3061,17 @@ private void readCVars() { startmap = 1; autostart = true; }); - + if (cVarManager.present(CommandVariable.TIMER) && deathmatch) { // Good Sign (2017/03/31) How this should work? final int time = cVarManager.get(CommandVariable.TIMER, Integer.class, 0).get(); - System.out.print("Levels will end after " + time + " minute"); - if (time > 1) { - System.out.print("s"); - } - System.out.print(".\n"); + LOGGER.log(Level.INFO, String.format("Levels will end after %d minute(s)", time)); } // OK, and exactly how is this enforced? if (cVarManager.bool(CommandVariable.AVG) && deathmatch) { - System.out.print("Austin Virtual Gaming: Levels will end after 20 minutes\n"); + LOGGER.log(Level.INFO, "Austin Virtual Gaming: Levels will end after 20 minutes"); } - + // MAES 31/5/2011: added support for +map variation. cVarManager.with(CommandVariable.WARP, 0, (CommandVariable.WarpFormat w) -> { final CommandVariable.WarpMetric metric = w.getMetric(isCommercial()); @@ -2981,7 +3093,7 @@ private void readCVars() { if (cVarManager.bool(CommandVariable.CDROM)) { file.append("c:\\doomdata\\"); } - + file.append(String.format("%s%d.dsg", SAVEGAMENAME, c)); LoadGame(file.toString()); }); @@ -2990,12 +3102,10 @@ private void readCVars() { /** * Since it's so intimately tied, it's less troublesome to merge the "main" and "network" code. */ - /** To be initialized by the DoomNetworkingInterface via a setter */ //private doomcom_t doomcom; //private doomdata_t netbuffer; // points inside doomcom - protected StringBuilder sb=new StringBuilder(); - + protected StringBuilder sb = new StringBuilder(); // // NETWORKING @@ -3006,9 +3116,7 @@ private void readCVars() { // // a gametic cannot be run until nettics[] > gametic for all players // - //ticcmd_t[] localcmds= new ticcmd_t[BACKUPTICS]; - //ticcmd_t [][] netcmds=new ticcmd_t [MAXPLAYERS][BACKUPTICS]; int[] nettics = new int[MAXNETNODES]; boolean[] nodeingame = new boolean[MAXNETNODES]; // set false as nodes leave game @@ -3032,22 +3140,18 @@ public void setTicdup(int ticdup) { } int maxsend; // BACKUPTICS/(2*ticdup)-1; - + //void D_ProcessEvents (void); //void G_BuildTiccmd (ticcmd_t *cmd); //void D_DoAdvanceDemo (void); - // _D_ - boolean reboundpacket = false; - doomdata_t reboundstore = new doomdata_t(); - - + boolean reboundpacket = false; + doomdata_t reboundstore = new doomdata_t(); /** * MAES: interesting. After testing it was found to return the following size: * (8*(netbuffer.numtics+1)); */ - int NetbufferSize() { // return (int)(((doomdata_t)0).cmds[netbuffer.numtics]); return (8 * (netbuffer.numtics + 1)); @@ -3068,12 +3172,12 @@ protected long NetbufferChecksum() { final int l = (NetbufferSize() - 4) / 4; long c = 0x1234567L; for (int i = 0; i < l; i++) { // TODO: checksum would be better computer in the netbuffer itself. - // The C code actually takes all fields into account. + // The C code actually takes all fields into account. c += 0;// TODO: (netbuffer->retransmitfrom)[i] * (i+1); } return c & NCMD_CHECKSUM; } - + protected int ExpandTics(int low) { int delta; @@ -3082,11 +3186,11 @@ protected int ExpandTics(int low) { if (delta >= -64 && delta <= 64) { return (maketic & ~0xff) + low; } - + if (delta > 64) { return (maketic & ~0xff) - 256 + low; } - + if (delta < -64) { return (maketic & ~0xff) + 256 + low; } @@ -3155,12 +3259,10 @@ void HSendPacket(int node, int flags) { // HGetPacket // Returns false if no packet is waiting // - private boolean HGetPacket () - { + private boolean HGetPacket() { // Fugly way of "clearing" the buffer. sb.setLength(0); - if (reboundpacket) - { + if (reboundpacket) { // FIXME: MAES: this looks like a struct copy netbuffer.copyFrom(reboundstore); doomcom.remotenode = 0; @@ -3169,46 +3271,48 @@ private boolean HGetPacket () } // If not actually a netgame (e.g. single player, demo) return. - if (!netgame) + if (!netgame) { return false; + } - if (demoplayback) + if (demoplayback) { return false; + } doomcom.command = CMD_GET; - systemNetworking.NetCmd (); + systemNetworking.NetCmd(); // Invalid node? - if (doomcom.remotenode == -1) + if (doomcom.remotenode == -1) { return false; + } - if (doomcom.datalength != NetbufferSize ()) - { - if (eval(debugfile)) - logger(debugfile,"bad packet length "+doomcom.datalength+"\n"); + if (doomcom.datalength != NetbufferSize()) { + if (eval(debugfile)) { + logger(debugfile, "bad packet length " + doomcom.datalength + "\n"); + } return false; } - if (NetbufferChecksum () != (netbuffer.checksum&NCMD_CHECKSUM) ) - { - if (eval(debugfile)) - logger(debugfile,"bad packet checksum\n"); + if (NetbufferChecksum() != (netbuffer.checksum & NCMD_CHECKSUM)) { + if (eval(debugfile)) { + logger(debugfile, "bad packet checksum\n"); + } return false; } - if (eval(debugfile)) - { - int realretrans; + if (eval(debugfile)) { + int realretrans; int i; - if (flags(netbuffer.checksum , NCMD_SETUP)) - logger(debugfile,"setup packet\n"); - else - { - if (flags(netbuffer.checksum , NCMD_RETRANSMIT)) - realretrans = ExpandTics (netbuffer.retransmitfrom); - else + if (flags(netbuffer.checksum, NCMD_SETUP)) { + logger(debugfile, "setup packet\n"); + } else { + if (flags(netbuffer.checksum, NCMD_RETRANSMIT)) { + realretrans = ExpandTics(netbuffer.retransmitfrom); + } else { realretrans = -1; + } sb.append("get "); sb.append(doomcom.remotenode); @@ -3222,7 +3326,7 @@ private boolean HGetPacket () sb.append(doomcom.datalength); sb.append("]"); - logger(debugfile,sb.toString()); + logger(debugfile, sb.toString()); // Trick: force update of internal buffer. netbuffer.pack(); @@ -3232,23 +3336,20 @@ private boolean HGetPacket () * A doomcom object has a lot of header info, and a single "raw" data placeholder, which by now * should be inside netbuffer....right? **/ - - try{ + try { for (i = 0; i < doomcom.datalength; i++) { debugfile.write(Integer.toHexString(netbuffer.cached()[i])); debugfile.write('\n'); } - } - catch( IOException e){} // "Drown" IOExceptions here. + } catch (IOException e) { + } // "Drown" IOExceptions here. } } - return true; + return true; } - //// GetPackets - - StringBuilder exitmsg=new StringBuilder(80); + StringBuilder exitmsg = new StringBuilder(80); public void GetPackets() { int netconsole; @@ -3376,7 +3477,7 @@ protected void logger(OutputStreamWriter debugfile, String string) { debugfile.write(string); } catch (IOException e) { // TODO Auto-generated catch block - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Failure writing debug file.", e); } } @@ -3459,25 +3560,25 @@ public void NetUpdate() { // // CheckAbort // - private void CheckAbort () - { + private void CheckAbort() { event_t ev; - int stoptic; + int stoptic; - stoptic = ticker.GetTime () + 2; - while (ticker.GetTime() < stoptic) {} - //videoInterface.StartTic (); + stoptic = ticker.GetTime() + 2; + while (ticker.GetTime() < stoptic) { + } + //videoInterface.StartTic (); //videoInterface.StartTic (); for (; eventtail != eventhead; eventtail = (++eventtail) & (MAXEVENTS - 1)) { - ev = events[eventtail]; + ev = events[eventtail]; if (ev.isKey(SC_ESCAPE, ev_keydown)) { - doomSystem.Error ("Network game synchronization aborted."); + doomSystem.Error("Network game synchronization aborted."); } - } + } } - boolean[] gotinfo=new boolean[MAXNETNODES]; + boolean[] gotinfo = new boolean[MAXNETNODES]; /** * D_ArbitrateNetStart @@ -3485,8 +3586,7 @@ private void CheckAbort () * * */ - public void ArbitrateNetStart() throws IOException - { + public void ArbitrateNetStart() throws IOException { int i; autostart = true; @@ -3494,7 +3594,7 @@ public void ArbitrateNetStart() throws IOException memset(gotinfo, false, gotinfo.length); if (doomcom.consoleplayer != 0) { // listen for setup info from key player - System.out.println("listening for network start info...\n"); + LOGGER.log(Level.INFO, "listening for network start info..."); while (true) { CheckAbort(); if (!HGetPacket()) { @@ -3523,7 +3623,7 @@ public void ArbitrateNetStart() throws IOException } } else { // key player, send the setup info - System.out.println("sending network start info...\n"); + LOGGER.log(Level.INFO, "sending network start info..."); do { CheckAbort(); for (i = 0; i < doomcom.numnodes; i++) { @@ -3533,15 +3633,15 @@ public void ArbitrateNetStart() throws IOException } else if (altdeath) { netbuffer.retransmitfrom |= (2 << 6); } - + if (nomonsters) { netbuffer.retransmitfrom |= 0x20; } - + if (respawnparm) { netbuffer.retransmitfrom |= 0x10; } - + netbuffer.starttic = (byte) (startepisode * 64 + startmap); netbuffer.player = VERSION; netbuffer.numtics = 0; @@ -3559,7 +3659,7 @@ public void ArbitrateNetStart() throws IOException { gotinfo[netbuffer.player&0x7f] = true; } - */ + */ for (i = 1; i < doomcom.numnodes; i++) { if (!gotinfo[i]) { @@ -3595,8 +3695,8 @@ private void CheckNetGame() throws IOException { ArbitrateNetStart(); } - System.out.printf("startskill %s deathmatch: %s startmap: %d startepisode: %d\n", - startskill.toString(), Boolean.toString(deathmatch), startmap, startepisode); + LOGGER.log(Level.FINE, String.format("startskill %s, deathmatch: %s, startmap: %d, startepisode: %d", + startskill.toString(), Boolean.toString(deathmatch), startmap, startepisode)); // read values out of doomcom ticdup = doomcom.ticdup; @@ -3609,12 +3709,12 @@ private void CheckNetGame() throws IOException { for (int i = 0; i < doomcom.numplayers; i++) { playeringame[i] = true; } - + for (int i = 0; i < doomcom.numnodes; i++) { nodeingame[i] = true; } - System.out.printf("player %d of %d (%d nodes)\n", (consoleplayer + 1), doomcom.numplayers, doomcom.numnodes); + LOGGER.log(Level.INFO, String.format("Player %d of %d (%d node(s))", (consoleplayer + 1), doomcom.numplayers, doomcom.numnodes)); } /** @@ -3628,7 +3728,7 @@ public void QuitNetGame() throws IOException { try { debugfile.close(); } catch (IOException e) { - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Quit net game failure.", e); } } @@ -3730,13 +3830,13 @@ public void TryRunTics() throws IOException { } else { if (nettics[0] <= nettics[nodeforplayer[i]]) { gametime--; - System.out.print("-"); + //System.out.print("-"); } frameskip[frameon & 3] = oldnettics > nettics[nodeforplayer[i]]; oldnettics = nettics[0]; if (frameskip[0] && frameskip[1] && frameskip[2] && frameskip[3]) { skiptics = 1; - System.out.print("+"); + //System.out.print("+"); } } } // demoplayback @@ -3805,16 +3905,16 @@ public doomcom_t getDoomCom() { @Override public void setDoomCom(doomcom_t doomcom) { - this.doomcom=doomcom; + this.doomcom = doomcom; } @Override public void setGameAction(gameaction_t action) { - this.gameaction=action; + this.gameaction = action; } @Override - public gameaction_t getGameAction() { + public gameaction_t getGameAction() { return this.gameaction; } @@ -3827,7 +3927,7 @@ public boolean shouldPollLockingKeys() { } return false; } - + private String findFileNameToSave() { String format = "DOOM%d%d%d%d.png"; String lbmname = null; @@ -3855,17 +3955,17 @@ protected final Finale selectFinale() { } /** - * M_Screenshot - * - * Currently saves PCX screenshots, and only in devparm. - * Very oldschool ;-) - * - * TODO: add non-devparm hotkey for screenshots, sequential screenshot - * messages, option to save as either PCX or PNG. Also, request - * current palette from VI (otherwise gamma settings and palette effects - * don't show up). - * - */ + * M_Screenshot + * + * Currently saves PCX screenshots, and only in devparm. + * Very oldschool ;-) + * + * TODO: add non-devparm hotkey for screenshots, sequential screenshot + * messages, option to save as either PCX or PNG. Also, request + * current palette from VI (otherwise gamma settings and palette effects + * don't show up). + * + */ public void ScreenShot() { // find a file name to save it to final String lbmname = findFileNameToSave(); // file doesn't exist diff --git a/src/doom/DoomStatus.java b/src/doom/DoomStatus.java index 178c23de..838ffbea 100644 --- a/src/doom/DoomStatus.java +++ b/src/doom/DoomStatus.java @@ -1,12 +1,41 @@ package doom; -import static data.Defines.*; -import static data.Limits.*; +import static data.Defines.BACKUPTICS; +import static data.Limits.MAXPLAYERS; +import static data.Limits.MAXWADFILES; +import static data.Limits.MAX_DM_STARTS; import data.mapthing_t; -import defines.*; +import defines.GameMission_t; +import defines.GameMode; +import defines.Language_t; +import defines.gamestate_t; +import defines.skill_t; import demo.IDoomDemo; import f.Finale; -import static g.Signals.ScanCode.*; +import static g.Signals.ScanCode.SC_0; +import static g.Signals.ScanCode.SC_1; +import static g.Signals.ScanCode.SC_2; +import static g.Signals.ScanCode.SC_3; +import static g.Signals.ScanCode.SC_4; +import static g.Signals.ScanCode.SC_5; +import static g.Signals.ScanCode.SC_6; +import static g.Signals.ScanCode.SC_7; +import static g.Signals.ScanCode.SC_8; +import static g.Signals.ScanCode.SC_9; +import static g.Signals.ScanCode.SC_A; +import static g.Signals.ScanCode.SC_D; +import static g.Signals.ScanCode.SC_END; +import static g.Signals.ScanCode.SC_LALT; +import static g.Signals.ScanCode.SC_LCTRL; +import static g.Signals.ScanCode.SC_NUMKEY4; +import static g.Signals.ScanCode.SC_PGDOWN; +import static g.Signals.ScanCode.SC_PGUP; +import static g.Signals.ScanCode.SC_Q; +import static g.Signals.ScanCode.SC_NUMKEY6; +import static g.Signals.ScanCode.SC_RSHIFT; +import static g.Signals.ScanCode.SC_S; +import static g.Signals.ScanCode.SC_SPACE; +import static g.Signals.ScanCode.SC_W; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.stream.Stream; @@ -23,18 +52,17 @@ * either as a local definition, or as an extern share. The very least, I'll * document where everything is supposed to come from/reside. */ +public abstract class DoomStatus { -public abstract class DoomStatus { + public static final int BGCOLOR = 7; + public static final int FGCOLOR = 8; + public static int RESENDCOUNT = 10; + public static int PL_DRONE = 0x80; // bit flag in doomdata->player - public static final int BGCOLOR= 7; - public static final int FGCOLOR =8; - public static int RESENDCOUNT =10; - public static int PL_DRONE =0x80; // bit flag in doomdata->player + public String[] wadfiles = new String[MAXWADFILES]; - public String[] wadfiles=new String[MAXWADFILES]; + boolean drone; - boolean drone; - /** Command line parametersm, actually defined in d_main.c */ public boolean nomonsters; // checkparm of -nomonsters @@ -44,72 +72,67 @@ public abstract class DoomStatus { public boolean devparm; // DEBUG: launched with -devparm - // MAES: declared as "extern", shared with Menu.java - public boolean inhelpscreens; + // MAES: declared as "extern", shared with Menu.java + public boolean inhelpscreens; + + boolean advancedemo; - boolean advancedemo; - /////////// Local to doomstat.c //////////// // TODO: hide those behind getters - /** Game Mode - identify IWAD as shareware, retail etc. * This is now hidden behind getters so some cases like plutonia * etc. can be handled more cleanly. * */ - private GameMode gamemode; - - public void setGameMode(GameMode mode){ - this.gamemode=mode; + + public void setGameMode(GameMode mode) { + this.gamemode = mode; } - - public GameMode getGameMode(){ - return gamemode; + + public GameMode getGameMode() { + return gamemode; } - - public boolean isShareware(){ - return (gamemode== GameMode.shareware); - } - + + public boolean isShareware() { + return (gamemode == GameMode.shareware); + } + /** Commercial means Doom 2, Plutonia, TNT, and possibly others like XBLA. * * @return */ - public boolean isCommercial(){ - return (gamemode== GameMode.commercial || - gamemode== GameMode.pack_plut || - gamemode== GameMode.pack_tnt || - gamemode== GameMode.pack_xbla || - gamemode== GameMode.freedoom2 || - gamemode== GameMode.freedm); + public boolean isCommercial() { + return (gamemode == GameMode.commercial + || gamemode == GameMode.pack_plut + || gamemode == GameMode.pack_tnt + || gamemode == GameMode.pack_xbla + || gamemode == GameMode.freedoom2 + || gamemode == GameMode.freedm); } - + /** Retail means Ultimate. * * @return */ - public boolean isRetail(){ - return (gamemode== GameMode.retail || gamemode == GameMode.freedoom1 ); + public boolean isRetail() { + return (gamemode == GameMode.retail || gamemode == GameMode.freedoom1); } - + /** Registered is a subset of Ultimate * * @return */ - - public boolean isRegistered(){ - return (gamemode== GameMode.registered || gamemode== GameMode.retail || gamemode == GameMode.freedoom1 ); + public boolean isRegistered() { + return (gamemode == GameMode.registered || gamemode == GameMode.retail || gamemode == GameMode.freedoom1); } - + public GameMission_t gamemission; /** Language. */ public Language_t language; // /////////// Normally found in d_main.c /////////////// - // Selected skill type, map etc. - /** Defaults for menu, methinks. */ public skill_t startskill; @@ -140,24 +163,22 @@ public boolean isRegistered(){ /** Use this instead of "deathmatch=2" which is bullshit. */ public boolean altdeath; - + //////////// STUFF SHARED WITH THE RENDERER /////////////// - // ------------------------- // Status flags for refresh. // - public boolean nodrawers; public boolean noblit; - + public boolean viewactive; - + // Player taking events, and displaying. public int consoleplayer; public int displayplayer; - + // Depending on view size - no status bar? // Note that there is no way to disable the // status bar explicitely. @@ -166,7 +187,7 @@ public boolean isRegistered(){ public boolean automapactive; // In AutoMap mode? public boolean menuactive; // Menu overlayed? - + public boolean mousecaptured = true; public boolean paused; // Game Pause? @@ -176,7 +197,6 @@ public boolean isRegistered(){ // These have been taken from the DOS version, // but are not (yet) supported with Linux // (e.g. no sound volume adjustment with menu. - // These are not used, but should be (menu). // From m_menu.c: // Sound FX volume has default, 0 - 15 @@ -204,7 +224,6 @@ public boolean isRegistered(){ public int snd_DesiredSfxDevice; - // ------------------------------------- // Scores, rating. // Statistics on a given map, for intermission. @@ -216,11 +235,11 @@ public boolean isRegistered(){ public int totalsecret; /** TNTHOM "cheat" for flashing HOM-detecting BG */ - public boolean flashing_hom; - + public boolean flashing_hom; + // Added for prBoom+ code public int totallive; - + // Timer, for scores. public int levelstarttic; // gametic at level start @@ -239,7 +258,7 @@ public boolean isRegistered(){ // Quit after playing a demo from cmdline. public boolean singledemo; - + public boolean mapstrobe; /** @@ -253,7 +272,6 @@ public boolean isRegistered(){ // These are set by the engine, and not changed // according to user inputs. Partly load from // WAD, partly set at startup time. - public int gametic; // Alive? Disconnected? @@ -274,15 +292,13 @@ public boolean isRegistered(){ /** LUT of ammunition limits for each kind. This doubles with BackPack powerup item. NOTE: this "maxammo" is treated like a global. - */ - public final static int[] maxammo = {200, 50, 300, 50}; + */ + public final static int[] maxammo = {200, 50, 300, 50}; // ----------------------------------------- // Internal parameters, used for engine. // - // File handling stuff. - public OutputStreamWriter debugfile; // if true, load all graphics at level load @@ -294,31 +310,29 @@ public boolean isRegistered(){ public gamestate_t wipegamestate = gamestate_t.GS_DEMOSCREEN; public int mouseSensitivity = 5; // AX: Fix wrong defaut mouseSensitivity - + /** Set if homebrew PWAD stuff has been added. */ public boolean modifiedgame = false; - + /** debug flag to cancel adaptiveness set to true during timedemos. */ public boolean singletics = false; - + /* A "fastdemo" is a demo with a clock that tics as * fast as possible, yet it maintains adaptiveness and doesn't * try to render everything at all costs. */ protected boolean fastdemo; protected boolean normaldemo; - + protected String loaddemo = null; - + public int bodyqueslot; // Needed to store the number of the dummy sky flat. // Used for rendering, // as well as tracking projectiles etc. //public int skyflatnum; - // TODO: Netgame stuff (buffers and pointers, i.e. indices). - // TODO: This is ??? public doomcom_t doomcom; @@ -330,7 +344,7 @@ public boolean isRegistered(){ public int rndindex; public ticcmd_t[][] netcmds;// [MAXPLAYERS][BACKUPTICS]; - + /** MAES: this WAS NOT in the original. * Remember to call it! */ @@ -344,16 +358,15 @@ protected final void initNetGameStuff() { Arrays.setAll(netcmds[i], j -> new ticcmd_t()); } } - + // Fields used for selecting variable BPP implementations. - protected abstract Finale selectFinale(); - + // MAES: Fields specific to DoomGame. A lot of them were // duplicated/externalized // in d_game.c and d_game.h, so it makes sense adopting a more unified // approach. - protected gameaction_t gameaction=gameaction_t.ga_nothing; + protected gameaction_t gameaction = gameaction_t.ga_nothing; public boolean sendpause; // send a pause event next tic @@ -372,19 +385,16 @@ public void setPaused(boolean paused) { } // ////////// DEMO SPECIFIC STUFF///////////// - protected String demoname; protected boolean netdemo; //protected IDemoTicCmd[] demobuffer; - protected IDoomDemo demobuffer; /** pointers */ // USELESS protected int demo_p; - // USELESS protected int demoend; - + // USELESS protected int demoend; protected short[][] consistancy = new short[MAXPLAYERS][BACKUPTICS]; protected byte[] savebuffer; @@ -405,13 +415,13 @@ public void setPaused(boolean paused) { public int key_recordstop = SC_Q.ordinal(); public int[] key_numbers = Stream.of(SC_1, SC_2, SC_3, SC_4, SC_5, SC_6, SC_7, SC_8, SC_9, SC_0) - .mapToInt(Enum::ordinal).toArray(); - + .mapToInt(Enum::ordinal).toArray(); + // Heretic stuff public int key_lookup = SC_PGUP.ordinal(); public int key_lookdown = SC_PGDOWN.ordinal(); public int key_lookcenter = SC_END.ordinal(); - + public int mousebfire = 0; public int mousebstrafe = 2; // AX: Fixed - Now we use the right mouse buttons public int mousebforward = 1; // AX: Fixed - Now we use the right mouse buttons @@ -423,9 +433,9 @@ public void setPaused(boolean paused) { public int joybuse; public int joybspeed; - + /** Cancel vertical mouse movement by default */ - protected boolean novert=false; // AX: The good default + protected boolean novert = true; protected int MAXPLMOVE() { return forwardmove[1]; @@ -434,11 +444,11 @@ protected int MAXPLMOVE() { protected static final int TURBOTHRESHOLD = 0x32; /** fixed_t */ - protected final int[] forwardmove = { 0x19, 0x32 }; // + slow turn + protected final int[] forwardmove = {0x19, 0x32}; // + slow turn - protected final int[] sidemove = { 0x18, 0x28 }; + protected final int[] sidemove = {0x18, 0x28}; - protected final int[] angleturn = { 640, 1280, 320 }; + protected final int[] angleturn = {640, 1280, 320}; protected static final int SLOWTURNTICS = 6; @@ -447,7 +457,7 @@ protected int MAXPLMOVE() { protected boolean[] gamekeydown = new boolean[NUMKEYS]; protected boolean keysCleared; - + public boolean alwaysrun; protected int turnheld; // for accelerative turning @@ -506,27 +516,22 @@ protected void joybuttons(int i, int value) { public String statcopy; // for statistics driver - - /** Not documented/used in linuxdoom. I supposed it could be used to * ignore mouse input? */ - - public boolean use_mouse,use_joystick; - - + public boolean use_mouse, use_joystick; + /** More prBoom+ stuff. Used mostly for code uhm..reuse, rather * than to actually change the way stuff works. * */ - public static int compatibility_level; - + public final ConfigManager CM = Engine.getConfig(); - + public DoomStatus() { - this.wminfo=new wbstartstruct_t(); - initNetGameStuff(); + this.wminfo = new wbstartstruct_t(); + initNetGameStuff(); } public void update() { @@ -562,13 +567,13 @@ public void update() { // Sound this.numChannels = CM.getValue(Settings.snd_channels, Integer.class); - + // Map strobe this.mapstrobe = CM.equals(Settings.vestrobe, Boolean.TRUE); - + // Mouse sensitivity this.mouseSensitivity = CM.getValue(Settings.mouse_sensitivity, Integer.class); - + // This should indicate keyboard behavior should be as close as possible to vanilla this.vanillaKeyBehavior = CM.equals(Settings.vanilla_key_behavior, Boolean.TRUE); } @@ -605,10 +610,10 @@ public void commit() { // Sound CM.update(Settings.snd_channels, this.numChannels); - + // Map strobe CM.update(Settings.vestrobe, this.mapstrobe); - + // Mouse sensitivity CM.update(Settings.mouse_sensitivity, this.mouseSensitivity); } @@ -680,4 +685,4 @@ public void commit() { // // Revision 1.18 2011/05/24 17:44:37 velktron // usemouse added for defaults -// \ No newline at end of file +// diff --git a/src/doom/IDatagramSerializable.java b/src/doom/IDatagramSerializable.java index 6abec43b..4137e55c 100644 --- a/src/doom/IDatagramSerializable.java +++ b/src/doom/IDatagramSerializable.java @@ -10,47 +10,43 @@ * @author admin * */ - public interface IDatagramSerializable { - - /** Packs object into a byte array suitable to send over - * datagram networks. Typically, objects cache this array - * for later use, and is availabe through cached() - * - * @return - */ - - public byte[] pack(); - - /** Packs object into a byte array suitable to send over - * datagram networks. The array is supplied externally - * (good for daisy-chaining stuff into a single packet). - * - * @return - */ - - public void pack(byte[] buf, int offset); - - /** Deserializes an object from a given byte buffer. - * Only the first (sizeof) bytes will be used, dependant - * on each object's implementation. Will NOT also copy - * the byte[] caches. - */ - - public void unpack(byte[] buf); - - /** Deserializes an object from a given byte buffer. - * Only the first (sizeof) bytes will be used, starting - * from a specified offset, dependant on each object's - * implementation. - */ - public void unpack(byte[] buf, int offset); - - /** Only use this if you are 100% sure that the object's content - * won't have changed since the last call of pack(). - * - * @return Should return the underlying byte[] array directly. - */ - public byte[] cached(); - + + /** Packs object into a byte array suitable to send over + * datagram networks. Typically, objects cache this array + * for later use, and is availabe through cached() + * + * @return + */ + public byte[] pack(); + + /** Packs object into a byte array suitable to send over + * datagram networks. The array is supplied externally + * (good for daisy-chaining stuff into a single packet). + * + * @return + */ + public void pack(byte[] buf, int offset); + + /** Deserializes an object from a given byte buffer. + * Only the first (sizeof) bytes will be used, dependant + * on each object's implementation. Will NOT also copy + * the byte[] caches. + */ + public void unpack(byte[] buf); + + /** Deserializes an object from a given byte buffer. + * Only the first (sizeof) bytes will be used, starting + * from a specified offset, dependant on each object's + * implementation. + */ + public void unpack(byte[] buf, int offset); + + /** Only use this if you are 100% sure that the object's content + * won't have changed since the last call of pack(). + * + * @return Should return the underlying byte[] array directly. + */ + public byte[] cached(); + } diff --git a/src/doom/IDoom.java b/src/doom/IDoom.java index 99adca5b..bada870d 100644 --- a/src/doom/IDoom.java +++ b/src/doom/IDoom.java @@ -7,17 +7,19 @@ * @author Maes * */ +public interface IDoom { + /** Called by IO functions when input is detected. */ + void PostEvent(event_t ev); -public interface IDoom { + void PageTicker(); + + void PageDrawer(); + + void AdvanceDemo(); + void StartTitle(); - /** Called by IO functions when input is detected. */ - void PostEvent (event_t ev); - void PageTicker (); - void PageDrawer (); - void AdvanceDemo (); - void StartTitle (); - void QuitNetGame() throws IOException; + void QuitNetGame() throws IOException; -} \ No newline at end of file +} diff --git a/src/doom/IDoomGame.java b/src/doom/IDoomGame.java index f2afd476..70295a27 100644 --- a/src/doom/IDoomGame.java +++ b/src/doom/IDoomGame.java @@ -5,40 +5,38 @@ /** Groups functions formerly in d_game, * in case you want to provide a different implementation */ - public interface IDoomGame { - void ExitLevel (); - void WorldDone (); + void ExitLevel(); + + void WorldDone(); + + boolean CheckDemoStatus(); - boolean CheckDemoStatus(); - - /** Can be called by the startup code or M_Responder. + /** Can be called by the startup code or M_Responder. A normal game starts at map 1, but a warp test can start elsewhere */ - - public void DeferedInitNew (skill_t skill, int episode, int map); - - /** Can be called by the startup code or M_Responder, + public void DeferedInitNew(skill_t skill, int episode, int map); + + /** Can be called by the startup code or M_Responder, calls P_SetupLevel or W_EnterWorld. */ - public void LoadGame (String name); - - /** Called by M_Responder. */ - public void SaveGame (int slot, String description); - - /** Takes a screenshot *NOW* - * - */ - public void ScreenShot() ; - - public void StartTitle(); - - public gameaction_t getGameAction(); - - public void setGameAction(gameaction_t ga); - - // public void PlayerReborn(int player); - - void DeathMatchSpawnPlayer(int playernum); + public void LoadGame(String name); + + /** Called by M_Responder. */ + public void SaveGame(int slot, String description); + + /** Takes a screenshot *NOW* + * + */ + public void ScreenShot(); + + public void StartTitle(); + + public gameaction_t getGameAction(); + + public void setGameAction(gameaction_t ga); + + // public void PlayerReborn(int player); + void DeathMatchSpawnPlayer(int playernum); } diff --git a/src/doom/IDoomGameNetworking.java b/src/doom/IDoomGameNetworking.java index d43b4d99..b16bd281 100644 --- a/src/doom/IDoomGameNetworking.java +++ b/src/doom/IDoomGameNetworking.java @@ -13,26 +13,24 @@ * @author Velktron * */ - public interface IDoomGameNetworking { - - public void TryRunTics() throws IOException; - - /** - * NetUpdate - * Builds ticcmds for console player, - * sends out a packet - * @throws IOException - */ - - public void NetUpdate (); - - public doomcom_t getDoomCom(); - - public void setDoomCom(doomcom_t doomcom); - - public int getTicdup(); - - public void setTicdup(int ticdup); + + public void TryRunTics() throws IOException; + + /** + * NetUpdate + * Builds ticcmds for console player, + * sends out a packet + * @throws IOException + */ + public void NetUpdate(); + + public doomcom_t getDoomCom(); + + public void setDoomCom(doomcom_t doomcom); + + public int getTicdup(); + + public void setTicdup(int ticdup); } diff --git a/src/doom/KeyboardManager.java b/src/doom/KeyboardManager.java index 7cd361ab..eaa00e7a 100644 --- a/src/doom/KeyboardManager.java +++ b/src/doom/KeyboardManager.java @@ -21,5 +21,5 @@ * @author Good Sign */ public class KeyboardManager { - + } diff --git a/src/doom/NetConsts.java b/src/doom/NetConsts.java index 7f264969..91045e6d 100644 --- a/src/doom/NetConsts.java +++ b/src/doom/NetConsts.java @@ -2,21 +2,18 @@ public interface NetConsts { - public static int NCMD_EXIT= 0x80000000; - public static int NCMD_RETRANSMIT =0x40000000; - public static int NCMD_SETUP =0x20000000; - public static int NCMD_KILL = 0x10000000; // kill game - public static int NCMD_CHECKSUM = 0x0fffffff; - - public static int DOOMCOM_ID = 0x12345678; + public static int NCMD_EXIT = 0x80000000; + public static int NCMD_RETRANSMIT = 0x40000000; + public static int NCMD_SETUP = 0x20000000; + public static int NCMD_KILL = 0x10000000; // kill game + public static int NCMD_CHECKSUM = 0x0fffffff; + public static int DOOMCOM_ID = 0x12345678; //Networking and tick handling related. Moved to DEFINES //protected static int BACKUPTICS = 12; - - // command_t - public static short CMD_SEND = 1; - public static short CMD_GET = 2; - + public static short CMD_SEND = 1; + public static short CMD_GET = 2; + } diff --git a/src/doom/SourceCode.java b/src/doom/SourceCode.java index c2e0fd21..379f5557 100644 --- a/src/doom/SourceCode.java +++ b/src/doom/SourceCode.java @@ -16,42 +16,59 @@ */ package doom; -import java.lang.annotation.*; -import static java.lang.annotation.ElementType.*; +import java.lang.annotation.Documented; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.LOCAL_VARIABLE; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.SOURCE; +import java.lang.annotation.Target; @Target({}) @Retention(SOURCE) public @interface SourceCode { - + public enum AM_Map { AM_Responder, AM_Ticker, AM_Drawer, AM_Stop; + @Documented - @Retention(SOURCE) public - @interface C { AM_Map value(); } + @Retention(SOURCE) + public @interface C { + + AM_Map value(); + } } - + public enum D_Main { D_DoomLoop, D_ProcessEvents; + @Documented - @Retention(SOURCE) public - @interface C { D_Main value(); } + @Retention(SOURCE) + public @interface C { + + D_Main value(); + } } - + public enum F_Finale { F_Responder, F_Ticker, F_Drawer, F_StartFinale; + @Documented - @Retention(SOURCE) public - @interface C { F_Finale value(); } + @Retention(SOURCE) + public @interface C { + + F_Finale value(); + } } - + public enum G_Game { G_BuildTiccmd, G_DoCompleted, @@ -81,9 +98,13 @@ public enum G_Game { G_Ticker, G_Responder, G_ScreenShot; + @Documented - @Retention(SOURCE) public - @interface C { G_Game value(); } + @Retention(SOURCE) + public @interface C { + + G_Game value(); + } } public enum HU_Lib { @@ -107,11 +128,15 @@ public enum HU_Lib { HUlib_keyInIText, HUlib_drawIText, HUlib_eraseIText; + @Documented - @Retention(SOURCE) public - @interface C { HU_Lib value(); } - } - + @Retention(SOURCE) + public @interface C { + + HU_Lib value(); + } + } + public enum HU_Stuff { HU_Init, HU_Start, @@ -121,11 +146,15 @@ public enum HU_Stuff { HU_queueChatChar, HU_dequeueChatChar, HU_Erase; + @Documented - @Retention(SOURCE) public - @interface C { HU_Stuff value(); } + @Retention(SOURCE) + public @interface C { + + HU_Stuff value(); + } } - + public enum I_IBM { I_GetTime, I_WaitVBL, @@ -134,38 +163,54 @@ public enum I_IBM { I_StartTic, I_InitNetwork, I_NetCmd; + @Documented - @Retention(SOURCE) public - @interface C { I_IBM value(); } + @Retention(SOURCE) + public @interface C { + + I_IBM value(); + } } public enum M_Argv { M_CheckParm; + @Documented - @Retention(SOURCE) public - @interface C { M_Argv value(); } + @Retention(SOURCE) + public @interface C { + + M_Argv value(); + } } - + public enum M_Menu { M_Responder, M_Ticker, M_Drawer, M_Init, M_StartControlPanel; + @Documented - @Retention(SOURCE) public - @interface C { M_Menu value(); } + @Retention(SOURCE) + public @interface C { + + M_Menu value(); + } } - + public enum M_Random { M_Random, P_Random, M_ClearRandom; + @Documented - @Retention(SOURCE) public - @interface C { M_Random value(); } + @Retention(SOURCE) + public @interface C { + + M_Random value(); + } } - + public enum P_Doors { T_VerticalDoor, EV_VerticalDoor, @@ -177,11 +222,15 @@ public enum P_Doors { P_FindSlidingDoorType, T_SlidingDoor, EV_SlidingDoor; + @Documented - @Retention(SOURCE) public - @interface C { P_Doors value(); } + @Retention(SOURCE) + public @interface C { + + P_Doors value(); + } } - + public enum P_Map { P_CheckPosition, PIT_CheckThing, @@ -193,11 +242,15 @@ public enum P_Map { PTR_AimTraverse, PTR_ShootTraverse, PTR_UseTraverse; + @Documented - @Retention(SOURCE) public - @interface C { P_Map value(); } + @Retention(SOURCE) + public @interface C { + + P_Map value(); + } } - + public enum P_MapUtl { P_BlockThingsIterator, P_BlockLinesIterator, @@ -206,11 +259,15 @@ public enum P_MapUtl { P_SetThingPosition, PIT_AddLineIntercepts, PIT_AddThingIntercepts; + @Documented - @Retention(SOURCE) public - @interface C { P_MapUtl value(); } + @Retention(SOURCE) + public @interface C { + + P_MapUtl value(); + } } - + public enum P_Mobj { G_PlayerReborn, P_SpawnMapThing, @@ -229,18 +286,26 @@ public enum P_Mobj { P_CheckMissileSpawn, P_SpawnMissile, P_SpawnPlayerMissile; + @Documented - @Retention(SOURCE) public - @interface C { P_Mobj value(); } + @Retention(SOURCE) + public @interface C { + + P_Mobj value(); + } } - + public enum P_Enemy { PIT_VileCheck; + @Documented - @Retention(SOURCE) public - @interface C { P_Enemy value(); } + @Retention(SOURCE) + public @interface C { + + P_Enemy value(); + } } - + public enum P_Lights { T_FireFlicker, P_SpawnFireFlicker, @@ -253,11 +318,15 @@ public enum P_Lights { EV_LightTurnOn, T_Glow, P_SpawnGlowingLight; + @Documented - @Retention(SOURCE) public - @interface C { P_Lights value(); } + @Retention(SOURCE) + public @interface C { + + P_Lights value(); + } } - + public enum P_SaveG { P_ArchivePlayers, P_UnArchivePlayers, @@ -267,19 +336,27 @@ public enum P_SaveG { P_UnArchiveThinkers, P_ArchiveSpecials, P_UnArchiveSpecials; + @Documented - @Retention(SOURCE) public - @interface C { P_SaveG value(); } + @Retention(SOURCE) + public @interface C { + + P_SaveG value(); + } } - + public enum P_Setup { P_SetupLevel, P_LoadThings; + @Documented - @Retention(SOURCE) public - @interface C { P_Setup value(); } + @Retention(SOURCE) + public @interface C { + + P_Setup value(); + } } - + public enum P_Spec { P_InitPicAnims, P_SpawnSpecials, @@ -319,18 +396,26 @@ public enum P_Spec { EV_DoFloor, T_MoveFloor, EV_Teleport; + @Documented - @Retention(SOURCE) public - @interface C { P_Spec value(); } + @Retention(SOURCE) + public @interface C { + + P_Spec value(); + } } - + public enum P_Ceiling { EV_DoCeiling; + @Documented - @Retention(SOURCE) public - @interface C { P_Ceiling value(); } + @Retention(SOURCE) + public @interface C { + + P_Ceiling value(); + } } - + public enum P_Tick { P_InitThinkers, P_RemoveThinker, @@ -338,11 +423,15 @@ public enum P_Tick { P_AllocateThinker, P_RunThinkers, P_Ticker; + @Documented - @Retention(SOURCE) public - @interface C { P_Tick value(); } + @Retention(SOURCE) + public @interface C { + + P_Tick value(); + } } - + public enum P_Pspr { P_SetPsprite, P_CalcSwing, @@ -374,11 +463,15 @@ public enum P_Pspr { A_BFGsound, P_SetupPsprites, P_MovePsprites; + @Documented - @Retention(SOURCE) public - @interface C { P_Pspr value(); } + @Retention(SOURCE) + public @interface C { + + P_Pspr value(); + } } - + public enum R_Data { R_GetColumn, R_InitData, @@ -386,18 +479,26 @@ public enum R_Data { R_FlatNumForName, R_TextureNumForName, R_CheckTextureNumForName; + @Documented - @Retention(SOURCE) public - @interface C { R_Data value(); } + @Retention(SOURCE) + public @interface C { + + R_Data value(); + } } - + public enum R_Draw { R_FillBackScreen; + @Documented - @Retention(SOURCE) public - @interface C { R_Draw value(); } + @Retention(SOURCE) + public @interface C { + + R_Draw value(); + } } - + public enum R_Main { R_PointOnSide, R_PointOnSegSide, @@ -410,22 +511,30 @@ public enum R_Main { R_RenderPlayerView, R_Init, R_SetViewSize; + @Documented - @Retention(SOURCE) public - @interface C { R_Main value(); } + @Retention(SOURCE) + public @interface C { + + R_Main value(); + } } - + public enum ST_Stuff { ST_Responder, ST_Ticker, ST_Drawer, ST_Start, ST_Init; + @Documented - @Retention(SOURCE) public - @interface C { ST_Stuff value(); } + @Retention(SOURCE) + public @interface C { + + ST_Stuff value(); + } } - + public enum W_Wad { W_InitMultipleFiles, W_Reload, @@ -435,11 +544,15 @@ public enum W_Wad { W_ReadLump, W_CacheLumpNum, W_CacheLumpName; + @Documented - @Retention(SOURCE) public - @interface C { W_Wad value(); } + @Retention(SOURCE) + public @interface C { + + W_Wad value(); + } } - + public enum WI_Stuff { WI_initVariables, WI_loadData, @@ -450,48 +563,61 @@ public enum WI_Stuff { WI_Ticker, WI_Drawer, WI_Start; + @Documented - @Retention(SOURCE) public - @interface C { WI_Stuff value(); } + @Retention(SOURCE) + public @interface C { + + WI_Stuff value(); + } } - + public interface D_Think { + public enum actionf_t { acp1, acv, acp2 } - + @Documented - @Retention(SOURCE) public - @interface C { actionf_t value(); } + @Retention(SOURCE) + public @interface C { + + actionf_t value(); + } } - + public enum Z_Zone { Z_Malloc; + @Documented - @Retention(SOURCE) public - @interface C { Z_Zone value(); } + @Retention(SOURCE) + public @interface C { + + Z_Zone value(); + } } - + @Documented @Retention(SOURCE) public @interface Exact { - String description() default - "Indicates that the method behaves exactly in vanilla way\n" + - " and can be skipped when traversing for compatibility"; + + String description() default "Indicates that the method behaves exactly in vanilla way\n" + + " and can be skipped when traversing for compatibility"; } @Documented @Retention(SOURCE) public @interface Compatible { + String[] value() default ""; - String description() default - "Indicates that the method can behave differently from vanilla way,\n" + - " but this behavior is reviewed and can be turned back to vanilla as an option." + - "A value might be specivied with the equivalent vanilla code"; + + String description() default "Indicates that the method can behave differently from vanilla way,\n" + + " but this behavior is reviewed and can be turned back to vanilla as an option." + + "A value might be specivied with the equivalent vanilla code"; } - + public enum CauseOfDesyncProbability { LOW, MEDIUM, @@ -500,43 +626,51 @@ public enum CauseOfDesyncProbability { @Documented @Retention(SOURCE) - public @interface Suspicious { + public @interface Suspicious { + CauseOfDesyncProbability value() default CauseOfDesyncProbability.HIGH; - String description() default - "Indicates that the method contains behavior totally different\n" + - "from vanilla, and by so should be considered suspicious\n" + - "in terms of compatibility"; + + String description() default "Indicates that the method contains behavior totally different\n" + + "from vanilla, and by so should be considered suspicious\n" + + "in terms of compatibility"; } @Documented @Retention(SOURCE) @Target({METHOD, FIELD, LOCAL_VARIABLE, PARAMETER}) - public @interface angle_t {} - + public @interface angle_t { + } + @Documented @Retention(SOURCE) @Target({METHOD, FIELD, LOCAL_VARIABLE, PARAMETER}) - public @interface fixed_t {} - + public @interface fixed_t { + } + @Documented @Retention(SOURCE) - public @interface actionf_p1 {} - + public @interface actionf_p1 { + } + @Documented @Retention(SOURCE) - public @interface actionf_v {} - + public @interface actionf_v { + } + @Documented @Retention(SOURCE) - public @interface actionf_p2 {} - + public @interface actionf_p2 { + } + @Documented @Retention(SOURCE) @Target({FIELD, LOCAL_VARIABLE, PARAMETER}) - public @interface thinker_t {} - + public @interface thinker_t { + } + @Documented @Retention(SOURCE) @Target({FIELD, LOCAL_VARIABLE, PARAMETER}) - public @interface think_t {} + public @interface think_t { + } } diff --git a/src/doom/doomcom_t.java b/src/doom/doomcom_t.java index bb504097..8a3449f2 100644 --- a/src/doom/doomcom_t.java +++ b/src/doom/doomcom_t.java @@ -1,57 +1,57 @@ package doom; public class doomcom_t { - - public doomcom_t(){ - this.data=new doomdata_t(); - - } - - // Supposed to be DOOMCOM_ID? - // Maes: was "long", but they intend 32-bit "int" here. Hurray for C's consistency! - public int id; - - // DOOM executes an int to execute commands. - public short intnum; - // Communication between DOOM and the driver. - // Is CMD_SEND or CMD_GET. - public short command; - // Is dest for send, set by get (-1 = no packet). - public short remotenode; - - // Number of bytes in doomdata to be sent - public short datalength; - - // Info common to all nodes. - // Console is allways node 0. - public short numnodes; - // Flag: 1 = no duplication, 2-5 = dup for slow nets. - public short ticdup; - // Flag: 1 = send a backup tic in every packet. - public short extratics; - // Flag: 1 = deathmatch. - public short deathmatch; - // Flag: -1 = new game, 0-5 = load savegame - public short savegame; - public short episode; // 1-3 - public short map; // 1-9 - public short skill; // 1-5 - - // Info specific to this node. - public short consoleplayer; - public short numplayers; - - // These are related to the 3-display mode, - // in which two drones looking left and right - // were used to render two additional views - // on two additional computers. - // Probably not operational anymore. - // 1 = left, 0 = center, -1 = right - public short angleoffset; - // 1 = drone - public short drone; - - // The packet data to be sent. - public doomdata_t data; - + + public doomcom_t() { + this.data = new doomdata_t(); + } + + // Supposed to be DOOMCOM_ID? + // Maes: was "long", but they intend 32-bit "int" here. Hurray for C's consistency! + public int id; + + // DOOM executes an int to execute commands. + public short intnum; + // Communication between DOOM and the driver. + // Is CMD_SEND or CMD_GET. + public short command; + // Is dest for send, set by get (-1 = no packet). + public short remotenode; + + // Number of bytes in doomdata to be sent + public short datalength; + + // Info common to all nodes. + // Console is allways node 0. + public short numnodes; + // Flag: 1 = no duplication, 2-5 = dup for slow nets. + public short ticdup; + // Flag: 1 = send a backup tic in every packet. + public short extratics; + // Flag: 1 = deathmatch. + public short deathmatch; + // Flag: -1 = new game, 0-5 = load savegame + public short savegame; + public short episode; // 1-3 + public short map; // 1-9 + public short skill; // 1-5 + + // Info specific to this node. + public short consoleplayer; + public short numplayers; + + // These are related to the 3-display mode, + // in which two drones looking left and right + // were used to render two additional views + // on two additional computers. + // Probably not operational anymore. + // 1 = left, 0 = center, -1 = right + public short angleoffset; + // 1 = drone + public short drone; + + // The packet data to be sent. + public doomdata_t data; + +} diff --git a/src/doom/doomdata_t.java b/src/doom/doomdata_t.java index a7d88500..aef0faa9 100644 --- a/src/doom/doomdata_t.java +++ b/src/doom/doomdata_t.java @@ -6,124 +6,122 @@ public class doomdata_t implements IDatagramSerializable { - public static final int DOOMDATALEN = 8 + data.Defines.BACKUPTICS * ticcmd_t.TICCMDLEN; - - // High bit is retransmit request. - /** MAES: was "unsigned" */ - public int checksum; + public static final int DOOMDATALEN = 8 + data.Defines.BACKUPTICS * ticcmd_t.TICCMDLEN; - /* + // High bit is retransmit request. + /** MAES: was "unsigned" */ + public int checksum; + + /* * CAREFUL!!! Those "bytes" are actually unsigned - */ - - /** Only valid if NCMD_RETRANSMIT. */ - public byte retransmitfrom; - - public byte starttic; - public byte player; - public byte numtics; - public ticcmd_t[] cmds; - - public doomdata_t() { - cmds = malloc(ticcmd_t::new, ticcmd_t[]::new, data.Defines.BACKUPTICS); - // Enough space for its own header + the ticcmds; - buffer = new byte[DOOMDATALEN]; - // This "pegs" the ByteBuffer to this particular array. - // Separate updates are not necessary. - bbuf = ByteBuffer.wrap(buffer); - } + */ + /** Only valid if NCMD_RETRANSMIT. */ + public byte retransmitfrom; + + public byte starttic; + public byte player; + public byte numtics; + public ticcmd_t[] cmds; + + public doomdata_t() { + cmds = malloc(ticcmd_t::new, ticcmd_t[]::new, data.Defines.BACKUPTICS); + // Enough space for its own header + the ticcmds; + buffer = new byte[DOOMDATALEN]; + // This "pegs" the ByteBuffer to this particular array. + // Separate updates are not necessary. + bbuf = ByteBuffer.wrap(buffer); + } // Used for datagram serialization. private byte[] buffer; private ByteBuffer bbuf; - + @Override - public byte[] pack() { + public byte[] pack() { bbuf.rewind(); - + // Why making it harder? bbuf.putInt(checksum); bbuf.put(retransmitfrom); bbuf.put(starttic); bbuf.put(player); bbuf.put(numtics); - + // FIXME: it's probably more efficient to use System.arraycopy ? // Or are the packets too small anyway? At most we'll be sending "doomdata_t's" - - for (int i = 0; i < cmds.length; i++) { - bbuf.put(cmds[i].pack()); - } - + for (int i = 0; i < cmds.length; i++) { + bbuf.put(cmds[i].pack()); + } + return bbuf.array(); } @Override public void pack(byte[] buf, int offset) { - // No need to make it harder...just pack it and slap it in. - byte[] tmp = this.pack(); - System.arraycopy(tmp, 0, buf, offset, tmp.length); + // No need to make it harder...just pack it and slap it in. + byte[] tmp = this.pack(); + System.arraycopy(tmp, 0, buf, offset, tmp.length); } @Override public void unpack(byte[] buf) { - unpack(buf,0); + unpack(buf, 0); } @Override public void unpack(byte[] buf, int offset) { - checksum = DoomBuffer.getBEInt(buf); - offset = +4; - retransmitfrom = buf[offset++]; - starttic = buf[offset++]; - player = buf[offset++]; - numtics = buf[offset++]; - - for (int i = 0; i < cmds.length; i++) { - cmds[i].unpack(buf, offset); - offset += ticcmd_t.TICCMDLEN; - } + checksum = DoomBuffer.getBEInt(buf); + offset = +4; + retransmitfrom = buf[offset++]; + starttic = buf[offset++]; + player = buf[offset++]; + numtics = buf[offset++]; + + for (int i = 0; i < cmds.length; i++) { + cmds[i].unpack(buf, offset); + offset += ticcmd_t.TICCMDLEN; + } } - - public void selfUnpack(){ + + public void selfUnpack() { unpack(this.buffer); } - - public void copyFrom(doomdata_t source) { - this.checksum = source.checksum; - this.numtics = source.numtics; - this.player = source.player; - this.retransmitfrom = source.retransmitfrom; - this.starttic = source.starttic; - - // MAES: this was buggy as hell, and didn't work at all, which - // in turn prevented other subsystems such as speed throttling and - // networking to work. - // - // This should be enough to alter the ByteBuffer too. - // System.arraycopy(source.cached(), 0, this.buffer, 0, DOOMDATALEN); - // This should set all fields - // selfUnpack(); - } - - @Override - public byte[] cached() { - return this.buffer; - } - - StringBuilder sb = new StringBuilder(); - - public String toString() { - sb.setLength(0); - sb.append("doomdata_t "); - sb.append(retransmitfrom); - sb.append(" starttic "); - sb.append(starttic); - sb.append(" player "); - sb.append(player); - sb.append(" numtics "); - sb.append(numtics); - return sb.toString(); - } - - } + + public void copyFrom(doomdata_t source) { + this.checksum = source.checksum; + this.numtics = source.numtics; + this.player = source.player; + this.retransmitfrom = source.retransmitfrom; + this.starttic = source.starttic; + + // MAES: this was buggy as hell, and didn't work at all, which + // in turn prevented other subsystems such as speed throttling and + // networking to work. + // + // This should be enough to alter the ByteBuffer too. + // System.arraycopy(source.cached(), 0, this.buffer, 0, DOOMDATALEN); + // This should set all fields + // selfUnpack(); + } + + @Override + public byte[] cached() { + return this.buffer; + } + + StringBuilder sb = new StringBuilder(); + + public String toString() { + sb.setLength(0); + sb.append("doomdata_t "); + sb.append(retransmitfrom); + sb.append(" starttic "); + sb.append(starttic); + sb.append(" player "); + sb.append(player); + sb.append(" numtics "); + sb.append(numtics); + return sb.toString(); + } + +} diff --git a/src/doom/englsh.java b/src/doom/englsh.java index ee4b70e7..7ff166b6 100644 --- a/src/doom/englsh.java +++ b/src/doom/englsh.java @@ -22,680 +22,621 @@ // English language support (default). // //----------------------------------------------------------------------------- - // // Printed strings for translation // - // // D_Main.C // +public class englsh { -public class englsh{ -public final static String D_DEVSTR="Development mode ON.\n"; -public final static String D_CDROM="CD-ROM Version: default.cfg from c:\\doomdata\n"; + public final static String D_DEVSTR = "Development mode ON.\n"; + public final static String D_CDROM = "CD-ROM Version: default.cfg from c:\\doomdata\n"; // // M_Misc.C // - -public final static String SCREENSHOT ="screen shot"; + public final static String SCREENSHOT = "screen shot"; // // M_Menu.C // -public final static String PRESSKEY ="press a key."; -public final static String PRESSYN ="press y or n."; -public final static String QUITMSG="are you sure you want to\nquit this great game?"; -public final static String LOADNET ="you can't do load while in a net game!\n\n"+PRESSKEY; -public final static String QLOADNET="you can't quickload during a netgame!\n\n"+PRESSKEY; -public final static String QSAVESPOT="you haven't picked a quicksave slot yet!\n\n"+PRESSKEY; -public final static String SAVEDEAD ="you can't save if you aren't playing!\n\n"+PRESSKEY; -public final static String QSPROMPT ="quicksave over your game named\n\n'%s'?\n\n"+PRESSYN; -public final static String QLPROMPT="do you want to quickload the game named\n\n'%s'?\n\n"+PRESSYN; - -public final static String NEWGAME = "you can't start a new game\nwhile in a network game.\n\n"+PRESSKEY; - -public final static String NIGHTMARE ="are you sure? this skill level\nisn't even remotely fair.\n\n"+PRESSYN; - -public final static String SWSTRING = "this is the shareware version of doom.\n\nyou need to order the entire trilogy.\n\n"+PRESSKEY; - -public final static String MSGOFF="Messages OFF"; -public final static String MSGON ="Messages ON"; -public final static String NETEND="you can't end a netgame!\n\n"+PRESSKEY; -public final static String ENDGAME="are you sure you want to end the game?\n\n"+PRESSYN; - -public final static String DOSY ="(press y to quit)"; - -public final static String DETAILHI="High detail"; -public final static String DETAILLO="Low detail"; -public final static String GAMMALVL0="Gamma correction OFF"; -public final static String GAMMALVL1="Gamma correction level 1"; -public final static String GAMMALVL2="Gamma correction level 2"; -public final static String GAMMALVL3="Gamma correction level 3"; -public final static String GAMMALVL4="Gamma correction level 4"; -public final static String EMPTYSTRING="empty slot"; + public final static String PRESSKEY = "press a key."; + public final static String PRESSYN = "press y or n."; + public final static String QUITMSG = "are you sure you want to\nquit this great game?"; + public final static String LOADNET = "you can't do load while in a net game!\n\n" + PRESSKEY; + public final static String QLOADNET = "you can't quickload during a netgame!\n\n" + PRESSKEY; + public final static String QSAVESPOT = "you haven't picked a quicksave slot yet!\n\n" + PRESSKEY; + public final static String SAVEDEAD = "you can't save if you aren't playing!\n\n" + PRESSKEY; + public final static String QSPROMPT = "quicksave over your game named\n\n'%s'?\n\n" + PRESSYN; + public final static String QLPROMPT = "do you want to quickload the game named\n\n'%s'?\n\n" + PRESSYN; + + public final static String NEWGAME = "you can't start a new game\nwhile in a network game.\n\n" + PRESSKEY; + + public final static String NIGHTMARE = "are you sure? this skill level\nisn't even remotely fair.\n\n" + PRESSYN; + + public final static String SWSTRING = "this is the shareware version of doom.\n\nyou need to order the entire trilogy.\n\n" + PRESSKEY; + + public final static String MSGOFF = "Messages OFF"; + public final static String MSGON = "Messages ON"; + public final static String NETEND = "you can't end a netgame!\n\n" + PRESSKEY; + public final static String ENDGAME = "are you sure you want to end the game?\n\n" + PRESSYN; + + public final static String DOSY = "(press y to quit)"; + + public final static String DETAILHI = "High detail"; + public final static String DETAILLO = "Low detail"; + public final static String GAMMALVL0 = "Gamma correction OFF"; + public final static String GAMMALVL1 = "Gamma correction level 1"; + public final static String GAMMALVL2 = "Gamma correction level 2"; + public final static String GAMMALVL3 = "Gamma correction level 3"; + public final static String GAMMALVL4 = "Gamma correction level 4"; + public final static String EMPTYSTRING = "empty slot"; // // P_inter.C // -public final static String GOTARMOR="Picked up the armor."; -public final static String GOTMEGA="Picked up the MegaArmor!"; -public final static String GOTHTHBONUS="Picked up a health bonus."; -public final static String GOTARMBONUS="Picked up an armor bonus."; -public final static String GOTSTIM="Picked up a stimpack."; -public final static String GOTMEDINEED="Picked up a medikit that you REALLY need!"; -public final static String GOTMEDIKIT="Picked up a medikit."; -public final static String GOTSUPER="Supercharge!"; - -public final static String GOTBLUECARD="Picked up a blue keycard."; -public final static String GOTYELWCARD="Picked up a yellow keycard."; -public final static String GOTREDCARD="Picked up a red keycard."; -public final static String GOTBLUESKUL="Picked up a blue skull key."; -public final static String GOTYELWSKUL="Picked up a yellow skull key."; -public final static String GOTREDSKULL="Picked up a red skull key."; - -public final static String GOTINVUL="Invulnerability!"; -public final static String GOTBERSERK="Berserk!"; -public final static String GOTINVIS="Partial Invisibility"; -public final static String GOTSUIT="Radiation Shielding Suit"; -public final static String GOTMAP="Computer Area Map"; -public final static String GOTVISOR="Light Amplification Visor"; -public final static String GOTMSPHERE="MegaSphere!"; - -public final static String GOTCLIP="Picked up a clip."; -public final static String GOTCLIPBOX="Picked up a box of bullets."; -public final static String GOTROCKET="Picked up a rocket."; -public final static String GOTROCKBOX="Picked up a box of rockets."; -public final static String GOTCELL="Picked up an energy cell."; -public final static String GOTCELLBOX="Picked up an energy cell pack."; -public final static String GOTSHELLS="Picked up 4 shotgun shells."; -public final static String GOTSHELLBOX="Picked up a box of shotgun shells."; -public final static String GOTBACKPACK="Picked up a backpack full of ammo!"; - -public final static String GOTBFG9000="You got the BFG9000! Oh, yes."; -public final static String GOTCHAINGUN="You got the chaingun!"; -public final static String GOTCHAINSAW="A chainsaw! Find some meat!"; -public final static String GOTLAUNCHER="You got the rocket launcher!"; -public final static String GOTPLASMA="You got the plasma gun!"; -public final static String GOTSHOTGUN="You got the shotgun!"; -public final static String GOTSHOTGUN2="You got the super shotgun!"; + public final static String GOTARMOR = "Picked up the armor."; + public final static String GOTMEGA = "Picked up the MegaArmor!"; + public final static String GOTHTHBONUS = "Picked up a health bonus."; + public final static String GOTARMBONUS = "Picked up an armor bonus."; + public final static String GOTSTIM = "Picked up a stimpack."; + public final static String GOTMEDINEED = "Picked up a medikit that you REALLY need!"; + public final static String GOTMEDIKIT = "Picked up a medikit."; + public final static String GOTSUPER = "Supercharge!"; + + public final static String GOTBLUECARD = "Picked up a blue keycard."; + public final static String GOTYELWCARD = "Picked up a yellow keycard."; + public final static String GOTREDCARD = "Picked up a red keycard."; + public final static String GOTBLUESKUL = "Picked up a blue skull key."; + public final static String GOTYELWSKUL = "Picked up a yellow skull key."; + public final static String GOTREDSKULL = "Picked up a red skull key."; + + public final static String GOTINVUL = "Invulnerability!"; + public final static String GOTBERSERK = "Berserk!"; + public final static String GOTINVIS = "Partial Invisibility"; + public final static String GOTSUIT = "Radiation Shielding Suit"; + public final static String GOTMAP = "Computer Area Map"; + public final static String GOTVISOR = "Light Amplification Visor"; + public final static String GOTMSPHERE = "MegaSphere!"; + + public final static String GOTCLIP = "Picked up a clip."; + public final static String GOTCLIPBOX = "Picked up a box of bullets."; + public final static String GOTROCKET = "Picked up a rocket."; + public final static String GOTROCKBOX = "Picked up a box of rockets."; + public final static String GOTCELL = "Picked up an energy cell."; + public final static String GOTCELLBOX = "Picked up an energy cell pack."; + public final static String GOTSHELLS = "Picked up 4 shotgun shells."; + public final static String GOTSHELLBOX = "Picked up a box of shotgun shells."; + public final static String GOTBACKPACK = "Picked up a backpack full of ammo!"; + + public final static String GOTBFG9000 = "You got the BFG9000! Oh, yes."; + public final static String GOTCHAINGUN = "You got the chaingun!"; + public final static String GOTCHAINSAW = "A chainsaw! Find some meat!"; + public final static String GOTLAUNCHER = "You got the rocket launcher!"; + public final static String GOTPLASMA = "You got the plasma gun!"; + public final static String GOTSHOTGUN = "You got the shotgun!"; + public final static String GOTSHOTGUN2 = "You got the super shotgun!"; // // P_Doors.C // -public final static String PD_BLUEO="You need a blue key to activate this object"; -public final static String PD_REDO="You need a red key to activate this object"; -public final static String PD_YELLOWO="You need a yellow key to activate this object"; -public final static String PD_BLUEK="You need a blue key to open this door"; -public final static String PD_REDK="You need a red key to open this door"; -public final static String PD_YELLOWK="You need a yellow key to open this door"; + public final static String PD_BLUEO = "You need a blue key to activate this object"; + public final static String PD_REDO = "You need a red key to activate this object"; + public final static String PD_YELLOWO = "You need a yellow key to activate this object"; + public final static String PD_BLUEK = "You need a blue key to open this door"; + public final static String PD_REDK = "You need a red key to open this door"; + public final static String PD_YELLOWK = "You need a yellow key to open this door"; // // G_game.C // -public final static String GGSAVED="game saved."; + public final static String GGSAVED = "game saved."; // // HU_stuff.C // -public final static String HUSTR_MSGU="[Message unsent]"; - -public final static String HUSTR_E1M1="E1M1: Hangar"; -public final static String HUSTR_E1M2="E1M2: Nuclear Plant"; -public final static String HUSTR_E1M3="E1M3: Toxin Refinery"; -public final static String HUSTR_E1M4="E1M4: Command Control"; -public final static String HUSTR_E1M5="E1M5: Phobos Lab"; -public final static String HUSTR_E1M6="E1M6: Central Processing"; -public final static String HUSTR_E1M7="E1M7: Computer Station"; -public final static String HUSTR_E1M8="E1M8: Phobos Anomaly"; -public final static String HUSTR_E1M9="E1M9: Military Base"; - -public final static String HUSTR_E2M1="E2M1: Deimos Anomaly"; -public final static String HUSTR_E2M2="E2M2: Containment Area"; -public final static String HUSTR_E2M3="E2M3: Refinery"; -public final static String HUSTR_E2M4="E2M4: Deimos Lab"; -public final static String HUSTR_E2M5="E2M5: Command Center"; -public final static String HUSTR_E2M6="E2M6: Halls of the Damned"; -public final static String HUSTR_E2M7="E2M7: Spawning Vats"; -public final static String HUSTR_E2M8="E2M8: Tower of Babel"; -public final static String HUSTR_E2M9="E2M9: Fortress of Mystery"; - -public final static String HUSTR_E3M1="E3M1: Hell Keep"; -public final static String HUSTR_E3M2="E3M2: Slough of Despair"; -public final static String HUSTR_E3M3="E3M3: Pandemonium"; -public final static String HUSTR_E3M4="E3M4: House of Pain"; -public final static String HUSTR_E3M5="E3M5: Unholy Cathedral"; -public final static String HUSTR_E3M6="E3M6: Mt. Erebus"; -public final static String HUSTR_E3M7="E3M7: Limbo"; -public final static String HUSTR_E3M8="E3M8: Dis"; -public final static String HUSTR_E3M9="E3M9: Warrens"; - -public final static String HUSTR_E4M1="E4M1: Hell Beneath"; -public final static String HUSTR_E4M2="E4M2: Perfect Hatred"; -public final static String HUSTR_E4M3="E4M3: Sever The Wicked"; -public final static String HUSTR_E4M4="E4M4: Unruly Evil"; -public final static String HUSTR_E4M5="E4M5: They Will Repent"; -public final static String HUSTR_E4M6="E4M6: Against Thee Wickedly"; -public final static String HUSTR_E4M7="E4M7: And Hell Followed"; -public final static String HUSTR_E4M8="E4M8: Unto The Cruel"; -public final static String HUSTR_E4M9="E4M9: Fear"; - -public final static String HUSTR_1="level 1: entryway"; -public final static String HUSTR_2="level 2: underhalls"; -public final static String HUSTR_3="level 3: the gantlet"; -public final static String HUSTR_4="level 4: the focus"; -public final static String HUSTR_5="level 5: the waste tunnels"; -public final static String HUSTR_6="level 6: the crusher"; -public final static String HUSTR_7="level 7: dead simple"; -public final static String HUSTR_8="level 8: tricks and traps"; -public final static String HUSTR_9="level 9: the pit"; -public final static String HUSTR_10="level 10: refueling base"; -public final static String HUSTR_11="level 11: 'o' of destruction!"; - -public final static String HUSTR_12="level 12: the factory"; -public final static String HUSTR_13="level 13: downtown"; -public final static String HUSTR_14="level 14: the inmost dens"; -public final static String HUSTR_15="level 15: industrial zone"; -public final static String HUSTR_16="level 16: suburbs"; -public final static String HUSTR_17="level 17: tenements"; -public final static String HUSTR_18="level 18: the courtyard"; -public final static String HUSTR_19="level 19: the citadel"; -public final static String HUSTR_20="level 20: gotcha!"; - -public final static String HUSTR_21="level 21: nirvana"; -public final static String HUSTR_22="level 22: the catacombs"; -public final static String HUSTR_23="level 23: barrels o' fun"; -public final static String HUSTR_24="level 24: the chasm"; -public final static String HUSTR_25="level 25: bloodfalls"; -public final static String HUSTR_26="level 26: the abandoned mines"; -public final static String HUSTR_27="level 27: monster condo"; -public final static String HUSTR_28="level 28: the spirit world"; -public final static String HUSTR_29="level 29: the living end"; -public final static String HUSTR_30="level 30: icon of sin"; - -public final static String HUSTR_31="level 31: wolfenstein"; -public final static String HUSTR_32="level 32: grosse"; -public final static String HUSTR_33="level 33: betray"; - -public final static String PHUSTR_1="level 1: congo"; -public final static String PHUSTR_2="level 2: well of souls"; -public final static String PHUSTR_3="level 3: aztec"; -public final static String PHUSTR_4="level 4: caged"; -public final static String PHUSTR_5="level 5: ghost town"; -public final static String PHUSTR_6="level 6: baron's lair"; -public final static String PHUSTR_7="level 7: caughtyard"; -public final static String PHUSTR_8="level 8: realm"; -public final static String PHUSTR_9="level 9: abattoire"; -public final static String PHUSTR_10="level 10: onslaught"; -public final static String PHUSTR_11="level 11: hunted"; - -public final static String PHUSTR_12="level 12: speed"; -public final static String PHUSTR_13="level 13: the crypt"; -public final static String PHUSTR_14="level 14: genesis"; -public final static String PHUSTR_15="level 15: the twilight"; -public final static String PHUSTR_16="level 16: the omen"; -public final static String PHUSTR_17="level 17: compound"; -public final static String PHUSTR_18="level 18: neurosphere"; -public final static String PHUSTR_19="level 19: nme"; -public final static String PHUSTR_20="level 20: the death domain"; - -public final static String PHUSTR_21="level 21: slayer"; -public final static String PHUSTR_22="level 22: impossible mission"; -public final static String PHUSTR_23="level 23: tombstone"; -public final static String PHUSTR_24="level 24: the final frontier"; -public final static String PHUSTR_25="level 25: the temple of darkness"; -public final static String PHUSTR_26="level 26: bunker"; -public final static String PHUSTR_27="level 27: anti-christ"; -public final static String PHUSTR_28="level 28: the sewers"; -public final static String PHUSTR_29="level 29: odyssey of noises"; -public final static String PHUSTR_30="level 30: the gateway of hell"; - -public final static String PHUSTR_31="level 31: cyberden"; -public final static String PHUSTR_32="level 32: go 2 it"; - -public final static String THUSTR_1="level 1: system control"; -public final static String THUSTR_2="level 2: human bbq"; -public final static String THUSTR_3="level 3: power control"; -public final static String THUSTR_4="level 4: wormhole"; -public final static String THUSTR_5="level 5: hanger"; -public final static String THUSTR_6="level 6: open season"; -public final static String THUSTR_7="level 7: prison"; -public final static String THUSTR_8="level 8: metal"; -public final static String THUSTR_9="level 9: stronghold"; -public final static String THUSTR_10="level 10: redemption"; -public final static String THUSTR_11="level 11: storage facility"; - -public final static String THUSTR_12="level 12: crater"; -public final static String THUSTR_13="level 13: nukage processing"; -public final static String THUSTR_14="level 14: steel works"; -public final static String THUSTR_15="level 15: dead zone"; -public final static String THUSTR_16="level 16: deepest reaches"; -public final static String THUSTR_17="level 17: processing area"; -public final static String THUSTR_18="level 18: mill"; -public final static String THUSTR_19="level 19: shipping/respawning"; -public final static String THUSTR_20="level 20: central processing"; - -public final static String THUSTR_21="level 21: administration center"; -public final static String THUSTR_22="level 22: habitat"; -public final static String THUSTR_23="level 23: lunar mining project"; -public final static String THUSTR_24="level 24: quarry"; -public final static String THUSTR_25="level 25: baron's den"; -public final static String THUSTR_26="level 26: ballistyx"; -public final static String THUSTR_27="level 27: mount pain"; -public final static String THUSTR_28="level 28: heck"; -public final static String THUSTR_29="level 29: river styx"; -public final static String THUSTR_30="level 30: last call"; - -public final static String THUSTR_31="level 31: pharaoh"; -public final static String THUSTR_32="level 32: caribbean"; - -public final static String HUSTR_CHATMACRO1="I'm ready to kick butt!"; -public final static String HUSTR_CHATMACRO2="I'm OK."; -public final static String HUSTR_CHATMACRO3="I'm not looking too good!"; -public final static String HUSTR_CHATMACRO4="Help!"; -public final static String HUSTR_CHATMACRO5="You suck!"; -public final static String HUSTR_CHATMACRO6="Next time, scumbag..."; -public final static String HUSTR_CHATMACRO7="Come here!"; -public final static String HUSTR_CHATMACRO8="I'll take care of it."; -public final static String HUSTR_CHATMACRO9="Yes"; -public final static String HUSTR_CHATMACRO0="No"; - -public final static String HUSTR_TALKTOSELF1="You mumble to yourself"; -public final static String HUSTR_TALKTOSELF2="Who's there?"; -public final static String HUSTR_TALKTOSELF3="You scare yourself"; -public final static String HUSTR_TALKTOSELF4="You start to rave"; -public final static String HUSTR_TALKTOSELF5="You've lost it..."; - -public final static String HUSTR_MESSAGESENT="[Message Sent]"; + public final static String HUSTR_MSGU = "[Message unsent]"; + + public final static String HUSTR_E1M1 = "E1M1: Hangar"; + public final static String HUSTR_E1M2 = "E1M2: Nuclear Plant"; + public final static String HUSTR_E1M3 = "E1M3: Toxin Refinery"; + public final static String HUSTR_E1M4 = "E1M4: Command Control"; + public final static String HUSTR_E1M5 = "E1M5: Phobos Lab"; + public final static String HUSTR_E1M6 = "E1M6: Central Processing"; + public final static String HUSTR_E1M7 = "E1M7: Computer Station"; + public final static String HUSTR_E1M8 = "E1M8: Phobos Anomaly"; + public final static String HUSTR_E1M9 = "E1M9: Military Base"; + + public final static String HUSTR_E2M1 = "E2M1: Deimos Anomaly"; + public final static String HUSTR_E2M2 = "E2M2: Containment Area"; + public final static String HUSTR_E2M3 = "E2M3: Refinery"; + public final static String HUSTR_E2M4 = "E2M4: Deimos Lab"; + public final static String HUSTR_E2M5 = "E2M5: Command Center"; + public final static String HUSTR_E2M6 = "E2M6: Halls of the Damned"; + public final static String HUSTR_E2M7 = "E2M7: Spawning Vats"; + public final static String HUSTR_E2M8 = "E2M8: Tower of Babel"; + public final static String HUSTR_E2M9 = "E2M9: Fortress of Mystery"; + + public final static String HUSTR_E3M1 = "E3M1: Hell Keep"; + public final static String HUSTR_E3M2 = "E3M2: Slough of Despair"; + public final static String HUSTR_E3M3 = "E3M3: Pandemonium"; + public final static String HUSTR_E3M4 = "E3M4: House of Pain"; + public final static String HUSTR_E3M5 = "E3M5: Unholy Cathedral"; + public final static String HUSTR_E3M6 = "E3M6: Mt. Erebus"; + public final static String HUSTR_E3M7 = "E3M7: Limbo"; + public final static String HUSTR_E3M8 = "E3M8: Dis"; + public final static String HUSTR_E3M9 = "E3M9: Warrens"; + + public final static String HUSTR_E4M1 = "E4M1: Hell Beneath"; + public final static String HUSTR_E4M2 = "E4M2: Perfect Hatred"; + public final static String HUSTR_E4M3 = "E4M3: Sever The Wicked"; + public final static String HUSTR_E4M4 = "E4M4: Unruly Evil"; + public final static String HUSTR_E4M5 = "E4M5: They Will Repent"; + public final static String HUSTR_E4M6 = "E4M6: Against Thee Wickedly"; + public final static String HUSTR_E4M7 = "E4M7: And Hell Followed"; + public final static String HUSTR_E4M8 = "E4M8: Unto The Cruel"; + public final static String HUSTR_E4M9 = "E4M9: Fear"; + + public final static String HUSTR_1 = "level 1: entryway"; + public final static String HUSTR_2 = "level 2: underhalls"; + public final static String HUSTR_3 = "level 3: the gantlet"; + public final static String HUSTR_4 = "level 4: the focus"; + public final static String HUSTR_5 = "level 5: the waste tunnels"; + public final static String HUSTR_6 = "level 6: the crusher"; + public final static String HUSTR_7 = "level 7: dead simple"; + public final static String HUSTR_8 = "level 8: tricks and traps"; + public final static String HUSTR_9 = "level 9: the pit"; + public final static String HUSTR_10 = "level 10: refueling base"; + public final static String HUSTR_11 = "level 11: 'o' of destruction!"; + + public final static String HUSTR_12 = "level 12: the factory"; + public final static String HUSTR_13 = "level 13: downtown"; + public final static String HUSTR_14 = "level 14: the inmost dens"; + public final static String HUSTR_15 = "level 15: industrial zone"; + public final static String HUSTR_16 = "level 16: suburbs"; + public final static String HUSTR_17 = "level 17: tenements"; + public final static String HUSTR_18 = "level 18: the courtyard"; + public final static String HUSTR_19 = "level 19: the citadel"; + public final static String HUSTR_20 = "level 20: gotcha!"; + + public final static String HUSTR_21 = "level 21: nirvana"; + public final static String HUSTR_22 = "level 22: the catacombs"; + public final static String HUSTR_23 = "level 23: barrels o' fun"; + public final static String HUSTR_24 = "level 24: the chasm"; + public final static String HUSTR_25 = "level 25: bloodfalls"; + public final static String HUSTR_26 = "level 26: the abandoned mines"; + public final static String HUSTR_27 = "level 27: monster condo"; + public final static String HUSTR_28 = "level 28: the spirit world"; + public final static String HUSTR_29 = "level 29: the living end"; + public final static String HUSTR_30 = "level 30: icon of sin"; + + public final static String HUSTR_31 = "level 31: wolfenstein"; + public final static String HUSTR_32 = "level 32: grosse"; + public final static String HUSTR_33 = "level 33: betray"; + + public final static String PHUSTR_1 = "level 1: congo"; + public final static String PHUSTR_2 = "level 2: well of souls"; + public final static String PHUSTR_3 = "level 3: aztec"; + public final static String PHUSTR_4 = "level 4: caged"; + public final static String PHUSTR_5 = "level 5: ghost town"; + public final static String PHUSTR_6 = "level 6: baron's lair"; + public final static String PHUSTR_7 = "level 7: caughtyard"; + public final static String PHUSTR_8 = "level 8: realm"; + public final static String PHUSTR_9 = "level 9: abattoire"; + public final static String PHUSTR_10 = "level 10: onslaught"; + public final static String PHUSTR_11 = "level 11: hunted"; + + public final static String PHUSTR_12 = "level 12: speed"; + public final static String PHUSTR_13 = "level 13: the crypt"; + public final static String PHUSTR_14 = "level 14: genesis"; + public final static String PHUSTR_15 = "level 15: the twilight"; + public final static String PHUSTR_16 = "level 16: the omen"; + public final static String PHUSTR_17 = "level 17: compound"; + public final static String PHUSTR_18 = "level 18: neurosphere"; + public final static String PHUSTR_19 = "level 19: nme"; + public final static String PHUSTR_20 = "level 20: the death domain"; + + public final static String PHUSTR_21 = "level 21: slayer"; + public final static String PHUSTR_22 = "level 22: impossible mission"; + public final static String PHUSTR_23 = "level 23: tombstone"; + public final static String PHUSTR_24 = "level 24: the final frontier"; + public final static String PHUSTR_25 = "level 25: the temple of darkness"; + public final static String PHUSTR_26 = "level 26: bunker"; + public final static String PHUSTR_27 = "level 27: anti-christ"; + public final static String PHUSTR_28 = "level 28: the sewers"; + public final static String PHUSTR_29 = "level 29: odyssey of noises"; + public final static String PHUSTR_30 = "level 30: the gateway of hell"; + + public final static String PHUSTR_31 = "level 31: cyberden"; + public final static String PHUSTR_32 = "level 32: go 2 it"; + + public final static String THUSTR_1 = "level 1: system control"; + public final static String THUSTR_2 = "level 2: human bbq"; + public final static String THUSTR_3 = "level 3: power control"; + public final static String THUSTR_4 = "level 4: wormhole"; + public final static String THUSTR_5 = "level 5: hanger"; + public final static String THUSTR_6 = "level 6: open season"; + public final static String THUSTR_7 = "level 7: prison"; + public final static String THUSTR_8 = "level 8: metal"; + public final static String THUSTR_9 = "level 9: stronghold"; + public final static String THUSTR_10 = "level 10: redemption"; + public final static String THUSTR_11 = "level 11: storage facility"; + + public final static String THUSTR_12 = "level 12: crater"; + public final static String THUSTR_13 = "level 13: nukage processing"; + public final static String THUSTR_14 = "level 14: steel works"; + public final static String THUSTR_15 = "level 15: dead zone"; + public final static String THUSTR_16 = "level 16: deepest reaches"; + public final static String THUSTR_17 = "level 17: processing area"; + public final static String THUSTR_18 = "level 18: mill"; + public final static String THUSTR_19 = "level 19: shipping/respawning"; + public final static String THUSTR_20 = "level 20: central processing"; + + public final static String THUSTR_21 = "level 21: administration center"; + public final static String THUSTR_22 = "level 22: habitat"; + public final static String THUSTR_23 = "level 23: lunar mining project"; + public final static String THUSTR_24 = "level 24: quarry"; + public final static String THUSTR_25 = "level 25: baron's den"; + public final static String THUSTR_26 = "level 26: ballistyx"; + public final static String THUSTR_27 = "level 27: mount pain"; + public final static String THUSTR_28 = "level 28: heck"; + public final static String THUSTR_29 = "level 29: river styx"; + public final static String THUSTR_30 = "level 30: last call"; + + public final static String THUSTR_31 = "level 31: pharaoh"; + public final static String THUSTR_32 = "level 32: caribbean"; + + public final static String HUSTR_CHATMACRO1 = "I'm ready to kick butt!"; + public final static String HUSTR_CHATMACRO2 = "I'm OK."; + public final static String HUSTR_CHATMACRO3 = "I'm not looking too good!"; + public final static String HUSTR_CHATMACRO4 = "Help!"; + public final static String HUSTR_CHATMACRO5 = "You suck!"; + public final static String HUSTR_CHATMACRO6 = "Next time, scumbag..."; + public final static String HUSTR_CHATMACRO7 = "Come here!"; + public final static String HUSTR_CHATMACRO8 = "I'll take care of it."; + public final static String HUSTR_CHATMACRO9 = "Yes"; + public final static String HUSTR_CHATMACRO0 = "No"; + + public final static String HUSTR_TALKTOSELF1 = "You mumble to yourself"; + public final static String HUSTR_TALKTOSELF2 = "Who's there?"; + public final static String HUSTR_TALKTOSELF3 = "You scare yourself"; + public final static String HUSTR_TALKTOSELF4 = "You start to rave"; + public final static String HUSTR_TALKTOSELF5 = "You've lost it..."; + + public final static String HUSTR_MESSAGESENT = "[Message Sent]"; // The following should NOT be changed unless it seems // just AWFULLY necessary + public final static String HUSTR_PLRGREEN = "Green: "; + public final static String HUSTR_PLRINDIGO = "Indigo: "; + public final static String HUSTR_PLRBROWN = "Brown: "; + public final static String HUSTR_PLRRED = "Red: "; -public final static String HUSTR_PLRGREEN="Green: "; -public final static String HUSTR_PLRINDIGO="Indigo: "; -public final static String HUSTR_PLRBROWN="Brown: "; -public final static String HUSTR_PLRRED ="Red: "; - -public final static char HUSTR_KEYGREEN = 'g'; -public final static char HUSTR_KEYINDIGO ='i'; -public final static char HUSTR_KEYBROWN = 'b'; -public final static char HUSTR_KEYRED = 'r'; + public final static char HUSTR_KEYGREEN = 'g'; + public final static char HUSTR_KEYINDIGO = 'i'; + public final static char HUSTR_KEYBROWN = 'b'; + public final static char HUSTR_KEYRED = 'r'; // // AM_map.C // + public final static String AMSTR_FOLLOWON = "Follow Mode ON"; + public final static String AMSTR_FOLLOWOFF = "Follow Mode OFF"; -public final static String AMSTR_FOLLOWON="Follow Mode ON"; -public final static String AMSTR_FOLLOWOFF="Follow Mode OFF"; + public final static String AMSTR_GRIDON = "Grid ON"; + public final static String AMSTR_GRIDOFF = "Grid OFF"; -public final static String AMSTR_GRIDON="Grid ON"; -public final static String AMSTR_GRIDOFF="Grid OFF"; - -public final static String AMSTR_MARKEDSPOT="Marked Spot"; -public final static String AMSTR_MARKSCLEARED="All Marks Cleared"; + public final static String AMSTR_MARKEDSPOT = "Marked Spot"; + public final static String AMSTR_MARKSCLEARED = "All Marks Cleared"; // // ST_stuff.C // + public final static String STSTR_MUS = "Music Change"; + public final static String STSTR_NOMUS = "IMPOSSIBLE SELECTION"; + public final static String STSTR_DQDON = "Degreelessness Mode On"; + public final static String STSTR_DQDOFF = "Degreelessness Mode Off"; -public final static String STSTR_MUS ="Music Change"; -public final static String STSTR_NOMUS ="IMPOSSIBLE SELECTION"; -public final static String STSTR_DQDON ="Degreelessness Mode On"; -public final static String STSTR_DQDOFF="Degreelessness Mode Off"; - -public final static String STSTR_KFAADDED="Very Happy Ammo Added"; -public final static String STSTR_FAADDED="Ammo (no keys) Added"; + public final static String STSTR_KFAADDED = "Very Happy Ammo Added"; + public final static String STSTR_FAADDED = "Ammo (no keys) Added"; -public final static String STSTR_NCON ="No Clipping Mode ON"; -public final static String STSTR_NCOFF ="No Clipping Mode OFF"; + public final static String STSTR_NCON = "No Clipping Mode ON"; + public final static String STSTR_NCOFF = "No Clipping Mode OFF"; -public final static String STSTR_BEHOLD="inVuln, Str, Inviso, Rad, Allmap, or Lite-amp"; -public final static String STSTR_BEHOLDX="Power-up Toggled"; + public final static String STSTR_BEHOLD = "inVuln, Str, Inviso, Rad, Allmap, or Lite-amp"; + public final static String STSTR_BEHOLDX = "Power-up Toggled"; -public final static String STSTR_CHOPPERS="... doesn't suck - GM"; -public final static String STSTR_CLEV ="Changing Level..."; + public final static String STSTR_CHOPPERS = "... doesn't suck - GM"; + public final static String STSTR_CLEV = "Changing Level..."; // // F_Finale.C // -public final static String E1TEXT =( -"Once you beat the big badasses and\n"+ -"clean out the moon base you're supposed\n"+ -"to win, aren't you? Aren't you? Where's\n"+ -"your fat reward and ticket home? What\n"+ -"the hell is this? It's not supposed to\n"+ -"end this way!\n"+ -"\n" + -"It stinks like rotten meat, but looks\n"+ -"like the lost Deimos base. Looks like\n"+ -"you're stuck on The Shores of Hell.\n"+ -"The only way out is through.\n"+ -"\n"+ -"To continue the DOOM experience, play\n"+ -"The Shores of Hell and its amazing\n"+ -"sequel, Inferno!\n"); - - -public final static String E2TEXT =( -"You've done it! The hideous cyber-\n"+ -"demon lord that ruled the lost Deimos\n"+ -"moon base has been slain and you\n"+ -"are triumphant! But ... where are\n"+ -"you? You clamber to the edge of the\n"+ -"moon and look down to see the awful\n"+ -"truth.\n" + -"\n"+ -"Deimos floats above Hell itself!\n"+ -"You've never heard of anyone escaping\n"+ -"from Hell, but you'll make the bastards\n"+ -"sorry they ever heard of you! Quickly,\n"+ -"you rappel down to the surface of\n"+ -"Hell.\n"+ -"\n" + -"Now, it's on to the final chapter of\n"+ -"DOOM! -- Inferno."); - - -public final static String E3TEXT =( -"The loathsome spiderdemon that\n"+ -"masterminded the invasion of the moon\n"+ -"bases and caused so much death has had\n"+ -"its ass kicked for all time.\n"+ -"\n"+ -"A hidden doorway opens and you enter.\n"+ -"You've proven too tough for Hell to\n"+ -"contain, and now Hell at last plays\n"+ -"fair -- for you emerge from the door\n"+ -"to see the green fields of Earth!\n"+ -"Home at last.\n" + -"\n"+ -"You wonder what's been happening on\n"+ -"Earth while you were battling evil\n"+ -"unleashed. It's good that no Hell-\n"+ -"spawn could have come through that\n"+ -"door with you ..."); - - -public final static String E4TEXT =( -"the spider mastermind must have sent forth\n"+ -"its legions of hellspawn before your\n"+ -"final confrontation with that terrible\n"+ -"beast from hell. but you stepped forward\n"+ -"and brought forth eternal damnation and\n"+ -"suffering upon the horde as a true hero\n"+ -"would in the face of something so evil.\n"+ -"\n"+ -"besides, someone was gonna pay for what\n"+ -"happened to daisy, your pet rabbit.\n"+ -"\n"+ -"but now, you see spread before you more\n"+ -"potential pain and gibbitude as a nation\n"+ -"of demons run amok among our cities.\n"+ -"\n"+ -"next stop, hell on earth!"); - + public final static String E1TEXT = ("Once you beat the big badasses and\n" + + "clean out the moon base you're supposed\n" + + "to win, aren't you? Aren't you? Where's\n" + + "your fat reward and ticket home? What\n" + + "the hell is this? It's not supposed to\n" + + "end this way!\n" + + "\n" + + "It stinks like rotten meat, but looks\n" + + "like the lost Deimos base. Looks like\n" + + "you're stuck on The Shores of Hell.\n" + + "The only way out is through.\n" + + "\n" + + "To continue the DOOM experience, play\n" + + "The Shores of Hell and its amazing\n" + + "sequel, Inferno!\n"); + + public final static String E2TEXT = ("You've done it! The hideous cyber-\n" + + "demon lord that ruled the lost Deimos\n" + + "moon base has been slain and you\n" + + "are triumphant! But ... where are\n" + + "you? You clamber to the edge of the\n" + + "moon and look down to see the awful\n" + + "truth.\n" + + "\n" + + "Deimos floats above Hell itself!\n" + + "You've never heard of anyone escaping\n" + + "from Hell, but you'll make the bastards\n" + + "sorry they ever heard of you! Quickly,\n" + + "you rappel down to the surface of\n" + + "Hell.\n" + + "\n" + + "Now, it's on to the final chapter of\n" + + "DOOM! -- Inferno."); + + public final static String E3TEXT = ("The loathsome spiderdemon that\n" + + "masterminded the invasion of the moon\n" + + "bases and caused so much death has had\n" + + "its ass kicked for all time.\n" + + "\n" + + "A hidden doorway opens and you enter.\n" + + "You've proven too tough for Hell to\n" + + "contain, and now Hell at last plays\n" + + "fair -- for you emerge from the door\n" + + "to see the green fields of Earth!\n" + + "Home at last.\n" + + "\n" + + "You wonder what's been happening on\n" + + "Earth while you were battling evil\n" + + "unleashed. It's good that no Hell-\n" + + "spawn could have come through that\n" + + "door with you ..."); + + public final static String E4TEXT = ("the spider mastermind must have sent forth\n" + + "its legions of hellspawn before your\n" + + "final confrontation with that terrible\n" + + "beast from hell. but you stepped forward\n" + + "and brought forth eternal damnation and\n" + + "suffering upon the horde as a true hero\n" + + "would in the face of something so evil.\n" + + "\n" + + "besides, someone was gonna pay for what\n" + + "happened to daisy, your pet rabbit.\n" + + "\n" + + "but now, you see spread before you more\n" + + "potential pain and gibbitude as a nation\n" + + "of demons run amok among our cities.\n" + + "\n" + + "next stop, hell on earth!"); // after level 6, put this: - -public final static String C1TEXT =( -"YOU HAVE ENTERED DEEPLY INTO THE INFESTED\n" + -"STARPORT. BUT SOMETHING IS WRONG. THE\n" + -"MONSTERS HAVE BROUGHT THEIR OWN REALITY\n" + -"WITH THEM, AND THE STARPORT'S TECHNOLOGY\n" + -"IS BEING SUBVERTED BY THEIR PRESENCE.\n" + -"\n"+ -"AHEAD, YOU SEE AN OUTPOST OF HELL, A\n" + -"FORTIFIED ZONE. IF YOU CAN GET PAST IT,\n" + -"YOU CAN PENETRATE INTO THE HAUNTED HEART\n" + -"OF THE STARBASE AND FIND THE CONTROLLING\n" + -"SWITCH WHICH HOLDS EARTH'S POPULATION\n" + -"HOSTAGE."); + public final static String C1TEXT = ("YOU HAVE ENTERED DEEPLY INTO THE INFESTED\n" + + "STARPORT. BUT SOMETHING IS WRONG. THE\n" + + "MONSTERS HAVE BROUGHT THEIR OWN REALITY\n" + + "WITH THEM, AND THE STARPORT'S TECHNOLOGY\n" + + "IS BEING SUBVERTED BY THEIR PRESENCE.\n" + + "\n" + + "AHEAD, YOU SEE AN OUTPOST OF HELL, A\n" + + "FORTIFIED ZONE. IF YOU CAN GET PAST IT,\n" + + "YOU CAN PENETRATE INTO THE HAUNTED HEART\n" + + "OF THE STARBASE AND FIND THE CONTROLLING\n" + + "SWITCH WHICH HOLDS EARTH'S POPULATION\n" + + "HOSTAGE."); // After level 11, put this: - -public final static String C2TEXT =( -"YOU HAVE WON! YOUR VICTORY HAS ENABLED\n" + -"HUMANKIND TO EVACUATE EARTH AND ESCAPE\n"+ -"THE NIGHTMARE. NOW YOU ARE THE ONLY\n"+ -"HUMAN LEFT ON THE FACE OF THE PLANET.\n"+ -"CANNIBAL MUTATIONS, CARNIVOROUS ALIENS,\n"+ -"AND EVIL SPIRITS ARE YOUR ONLY NEIGHBORS.\n"+ -"YOU SIT BACK AND WAIT FOR DEATH, CONTENT\n"+ -"THAT YOU HAVE SAVED YOUR SPECIES.\n"+ -"\n"+ -"BUT THEN, EARTH CONTROL BEAMS DOWN A\n"+ -"MESSAGE FROM SPACE: \"SENSORS HAVE LOCATED\n"+ -"THE SOURCE OF THE ALIEN INVASION. IF YOU\n"+ -"GO THERE, YOU MAY BE ABLE TO BLOCK THEIR\n"+ -"ENTRY. THE ALIEN BASE IS IN THE HEART OF\n"+ -"YOUR OWN HOME CITY, NOT FAR FROM THE\n"+ -"STARPORT.\" SLOWLY AND PAINFULLY YOU GET\n"+ -"UP AND RETURN TO THE FRAY."); - + public final static String C2TEXT = ("YOU HAVE WON! YOUR VICTORY HAS ENABLED\n" + + "HUMANKIND TO EVACUATE EARTH AND ESCAPE\n" + + "THE NIGHTMARE. NOW YOU ARE THE ONLY\n" + + "HUMAN LEFT ON THE FACE OF THE PLANET.\n" + + "CANNIBAL MUTATIONS, CARNIVOROUS ALIENS,\n" + + "AND EVIL SPIRITS ARE YOUR ONLY NEIGHBORS.\n" + + "YOU SIT BACK AND WAIT FOR DEATH, CONTENT\n" + + "THAT YOU HAVE SAVED YOUR SPECIES.\n" + + "\n" + + "BUT THEN, EARTH CONTROL BEAMS DOWN A\n" + + "MESSAGE FROM SPACE: \"SENSORS HAVE LOCATED\n" + + "THE SOURCE OF THE ALIEN INVASION. IF YOU\n" + + "GO THERE, YOU MAY BE ABLE TO BLOCK THEIR\n" + + "ENTRY. THE ALIEN BASE IS IN THE HEART OF\n" + + "YOUR OWN HOME CITY, NOT FAR FROM THE\n" + + "STARPORT.\" SLOWLY AND PAINFULLY YOU GET\n" + + "UP AND RETURN TO THE FRAY."); // After level 20, put this: - -public final static String C3TEXT =( -"YOU ARE AT THE CORRUPT HEART OF THE CITY,\n"+ -"SURROUNDED BY THE CORPSES OF YOUR ENEMIES.\n"+ -"YOU SEE NO WAY TO DESTROY THE CREATURES'\n"+ -"ENTRYWAY ON THIS SIDE, SO YOU CLENCH YOUR\n"+ -"TEETH AND PLUNGE THROUGH IT.\n"+ -"\n"+ -"THERE MUST BE A WAY TO CLOSE IT ON THE\n"+ -"OTHER SIDE. WHAT DO YOU CARE IF YOU'VE\n"+ -"GOT TO GO THROUGH HELL TO GET TO IT?"); - + public final static String C3TEXT = ("YOU ARE AT THE CORRUPT HEART OF THE CITY,\n" + + "SURROUNDED BY THE CORPSES OF YOUR ENEMIES.\n" + + "YOU SEE NO WAY TO DESTROY THE CREATURES'\n" + + "ENTRYWAY ON THIS SIDE, SO YOU CLENCH YOUR\n" + + "TEETH AND PLUNGE THROUGH IT.\n" + + "\n" + + "THERE MUST BE A WAY TO CLOSE IT ON THE\n" + + "OTHER SIDE. WHAT DO YOU CARE IF YOU'VE\n" + + "GOT TO GO THROUGH HELL TO GET TO IT?"); // After level 30, put this: - -public final static String C4TEXT =( -"THE HORRENDOUS VISAGE OF THE BIGGEST\n"+ -"DEMON YOU'VE EVER SEEN CRUMBLES BEFORE\n"+ -"YOU, AFTER YOU PUMP YOUR ROCKETS INTO\n"+ -"HIS EXPOSED BRAIN. THE MONSTER SHRIVELS\n"+ -"UP AND DIES, ITS THRASHING LIMBS\n"+ -"DEVASTATING UNTOLD MILES OF HELL'S\n"+ -"SURFACE.\n"+ -"\n"+ -"YOU'VE DONE IT. THE INVASION IS OVER.\n"+ -"EARTH IS SAVED. HELL IS A WRECK. YOU\n"+ -"WONDER WHERE BAD FOLKS WILL GO WHEN THEY\n"+ -"DIE, NOW. WIPING THE SWEAT FROM YOUR\n"+ -"FOREHEAD YOU BEGIN THE LONG TREK BACK\n"+ -"HOME. REBUILDING EARTH OUGHT TO BE A\n"+ -"LOT MORE FUN THAN RUINING IT WAS.\n"); - - + public final static String C4TEXT = ("THE HORRENDOUS VISAGE OF THE BIGGEST\n" + + "DEMON YOU'VE EVER SEEN CRUMBLES BEFORE\n" + + "YOU, AFTER YOU PUMP YOUR ROCKETS INTO\n" + + "HIS EXPOSED BRAIN. THE MONSTER SHRIVELS\n" + + "UP AND DIES, ITS THRASHING LIMBS\n" + + "DEVASTATING UNTOLD MILES OF HELL'S\n" + + "SURFACE.\n" + + "\n" + + "YOU'VE DONE IT. THE INVASION IS OVER.\n" + + "EARTH IS SAVED. HELL IS A WRECK. YOU\n" + + "WONDER WHERE BAD FOLKS WILL GO WHEN THEY\n" + + "DIE, NOW. WIPING THE SWEAT FROM YOUR\n" + + "FOREHEAD YOU BEGIN THE LONG TREK BACK\n" + + "HOME. REBUILDING EARTH OUGHT TO BE A\n" + + "LOT MORE FUN THAN RUINING IT WAS.\n"); // Before level 31, put this: - -public final static String C5TEXT =( -"CONGRATULATIONS, YOU'VE FOUND THE SECRET\n"+ -"LEVEL! LOOKS LIKE IT'S BEEN BUILT BY\n"+ -"HUMANS, RATHER THAN DEMONS. YOU WONDER\n"+ -"WHO THE INMATES OF THIS CORNER OF HELL\n"+ -"WILL BE."); - + public final static String C5TEXT = ("CONGRATULATIONS, YOU'VE FOUND THE SECRET\n" + + "LEVEL! LOOKS LIKE IT'S BEEN BUILT BY\n" + + "HUMANS, RATHER THAN DEMONS. YOU WONDER\n" + + "WHO THE INMATES OF THIS CORNER OF HELL\n" + + "WILL BE."); // Before level 32, put this: - -public final static String C6TEXT =( -"CONGRATULATIONS, YOU'VE FOUND THE\n"+ -"SUPER SECRET LEVEL! YOU'D BETTER\n"+ -"BLAZE THROUGH THIS ONE!\n"); - + public final static String C6TEXT = ("CONGRATULATIONS, YOU'VE FOUND THE\n" + + "SUPER SECRET LEVEL! YOU'D BETTER\n" + + "BLAZE THROUGH THIS ONE!\n"); // after map 06 - -public final static String P1TEXT =( -"You gloat over the steaming carcass of the\n"+ -"Guardian. With its death, you've wrested\n"+ -"the Accelerator from the stinking claws\n"+ -"of Hell. You relax and glance around the\n"+ -"room. Damn! There was supposed to be at\n"+ -"least one working prototype, but you can't\n"+ -"see it. The demons must have taken it.\n"+ -"\n"+ -"You must find the prototype, or all your\n"+ -"struggles will have been wasted. Keep\n"+ -"moving, keep fighting, keep killing.\n"+ -"Oh yes, keep living, too."); - + public final static String P1TEXT = ("You gloat over the steaming carcass of the\n" + + "Guardian. With its death, you've wrested\n" + + "the Accelerator from the stinking claws\n" + + "of Hell. You relax and glance around the\n" + + "room. Damn! There was supposed to be at\n" + + "least one working prototype, but you can't\n" + + "see it. The demons must have taken it.\n" + + "\n" + + "You must find the prototype, or all your\n" + + "struggles will have been wasted. Keep\n" + + "moving, keep fighting, keep killing.\n" + + "Oh yes, keep living, too."); // after map 11 - -public final static String P2TEXT =( -"Even the deadly Arch-Vile labyrinth could\n"+ -"not stop you, and you've gotten to the\n"+ -"prototype Accelerator which is soon\n"+ -"efficiently and permanently deactivated.\n"+ -"\n"+ -"You're good at that kind of thing."); - + public final static String P2TEXT = ("Even the deadly Arch-Vile labyrinth could\n" + + "not stop you, and you've gotten to the\n" + + "prototype Accelerator which is soon\n" + + "efficiently and permanently deactivated.\n" + + "\n" + + "You're good at that kind of thing."); // after map 20 - -public final static String P3TEXT =( -"You've bashed and battered your way into\n"+ -"the heart of the devil-hive. Time for a\n"+ -"Search-and-Destroy mission, aimed at the\n"+ -"Gatekeeper, whose foul offspring is\n"+ -"cascading to Earth. Yeah, he's bad. But\n"+ -"you know who's worse!\n"+ -"\n"+ -"Grinning evilly, you check your gear, and\n"+ -"get ready to give the bastard a little Hell\n"+ -"of your own making!"); + public final static String P3TEXT = ("You've bashed and battered your way into\n" + + "the heart of the devil-hive. Time for a\n" + + "Search-and-Destroy mission, aimed at the\n" + + "Gatekeeper, whose foul offspring is\n" + + "cascading to Earth. Yeah, he's bad. But\n" + + "you know who's worse!\n" + + "\n" + + "Grinning evilly, you check your gear, and\n" + + "get ready to give the bastard a little Hell\n" + + "of your own making!"); // after map 30 - -public final static String P4TEXT =( -"The Gatekeeper's evil face is splattered\n"+ -"all over the place. As its tattered corpse\n"+ -"collapses, an inverted Gate forms and\n"+ -"sucks down the shards of the last\n"+ -"prototype Accelerator, not to mention the\n"+ -"few remaining demons. You're done. Hell\n"+ -"has gone back to pounding bad dead folks \n"+ -"instead of good live ones. Remember to\n"+ -"tell your grandkids to put a rocket\n"+ -"launcher in your coffin. If you go to Hell\n"+ -"when you die, you'll need it for some\n"+ -"final cleaning-up ..."); + public final static String P4TEXT = ("The Gatekeeper's evil face is splattered\n" + + "all over the place. As its tattered corpse\n" + + "collapses, an inverted Gate forms and\n" + + "sucks down the shards of the last\n" + + "prototype Accelerator, not to mention the\n" + + "few remaining demons. You're done. Hell\n" + + "has gone back to pounding bad dead folks \n" + + "instead of good live ones. Remember to\n" + + "tell your grandkids to put a rocket\n" + + "launcher in your coffin. If you go to Hell\n" + + "when you die, you'll need it for some\n" + + "final cleaning-up ..."); // before map 31 - -public final static String P5TEXT =( -"You've found the second-hardest level we\n"+ -"got. Hope you have a saved game a level or\n"+ -"two previous. If not, be prepared to die\n"+ -"aplenty. For master marines only."); + public final static String P5TEXT = ("You've found the second-hardest level we\n" + + "got. Hope you have a saved game a level or\n" + + "two previous. If not, be prepared to die\n" + + "aplenty. For master marines only."); // before map 32 - -public final static String P6TEXT =( -"Betcha wondered just what WAS the hardest\n"+ -"level we had ready for ya? Now you know.\n"+ -"No one gets out alive."); - - -public final static String T1TEXT =( -"You've fought your way out of the infested\n"+ -"experimental labs. It seems that UAC has\n"+ -"once again gulped it down. With their\n"+ -"high turnover, it must be hard for poor\n"+ -"old UAC to buy corporate health insurance\n"+ -"nowadays..\n"+ -"\n"+ -"Ahead lies the military complex, now\n"+ -"swarming with diseased horrors hot to get\n"+ -"their teeth into you. With luck, the\n"+ -"complex still has some warlike ordnance\n"+ -"laying around."); - - -public final static String T2TEXT =( -"You hear the grinding of heavy machinery\n"+ -"ahead. You sure hope they're not stamping\n"+ -"out new hellspawn, but you're ready to\n"+ -"ream out a whole herd if you have to.\n"+ -"They might be planning a blood feast, but\n"+ -"you feel about as mean as two thousand\n"+ -"maniacs packed into one mad killer.\n"+ -"\n"+ -"You don't plan to go down easy."); - - -public final static String T3TEXT =( -"The vista opening ahead looks real damn\n"+ -"familiar. Smells familiar, too -- like\n"+ -"fried excrement. You didn't like this\n"+ -"place before, and you sure as hell ain't\n"+ -"planning to like it now. The more you\n"+ -"brood on it, the madder you get.\n"+ -"Hefting your gun, an evil grin trickles\n"+ -"onto your face. Time to take some names."); - -public final static String T4TEXT =( -"Suddenly, all is silent, from one horizon\n"+ -"to the other. The agonizing echo of Hell\n"+ -"fades away, the nightmare sky turns to\n"+ -"blue, the heaps of monster corpses start \n"+ -"to evaporate along with the evil stench \n"+ -"that filled the air. Jeeze, maybe you've\n"+ -"done it. Have you really won?\n"+ -"\n"+ -"Something rumbles in the distance.\n"+ -"A blue light begins to glow inside the\n"+ -"ruined skull of the demon-spitter."); - - -public final static String T5TEXT =( -"What now? Looks totally different. Kind\n"+ -"of like King Tut's condo. Well,\n"+ -"whatever's here can't be any worse\n"+ -"than usual. Can it? Or maybe it's best\n"+ -"to let sleeping gods lie.."); - - -public final static String T6TEXT =( -"Time for a vacation. You've burst the\n"+ -"bowels of hell and by golly you're ready\n"+ -"for a break. You mutter to yourself,\n"+ -"Maybe someone else can kick Hell's ass\n"+ -"next time around. Ahead lies a quiet town,\n"+ -"with peaceful flowing water, quaint\n"+ -"buildings, and presumably no Hellspawn.\n"+ -"\n"+ -"As you step off the transport, you hear\n"+ -"the stomp of a cyberdemon's iron shoe."); - - + public final static String P6TEXT = ("Betcha wondered just what WAS the hardest\n" + + "level we had ready for ya? Now you know.\n" + + "No one gets out alive."); + + public final static String T1TEXT = ("You've fought your way out of the infested\n" + + "experimental labs. It seems that UAC has\n" + + "once again gulped it down. With their\n" + + "high turnover, it must be hard for poor\n" + + "old UAC to buy corporate health insurance\n" + + "nowadays..\n" + + "\n" + + "Ahead lies the military complex, now\n" + + "swarming with diseased horrors hot to get\n" + + "their teeth into you. With luck, the\n" + + "complex still has some warlike ordnance\n" + + "laying around."); + + public final static String T2TEXT = ("You hear the grinding of heavy machinery\n" + + "ahead. You sure hope they're not stamping\n" + + "out new hellspawn, but you're ready to\n" + + "ream out a whole herd if you have to.\n" + + "They might be planning a blood feast, but\n" + + "you feel about as mean as two thousand\n" + + "maniacs packed into one mad killer.\n" + + "\n" + + "You don't plan to go down easy."); + + public final static String T3TEXT = ("The vista opening ahead looks real damn\n" + + "familiar. Smells familiar, too -- like\n" + + "fried excrement. You didn't like this\n" + + "place before, and you sure as hell ain't\n" + + "planning to like it now. The more you\n" + + "brood on it, the madder you get.\n" + + "Hefting your gun, an evil grin trickles\n" + + "onto your face. Time to take some names."); + + public final static String T4TEXT = ("Suddenly, all is silent, from one horizon\n" + + "to the other. The agonizing echo of Hell\n" + + "fades away, the nightmare sky turns to\n" + + "blue, the heaps of monster corpses start \n" + + "to evaporate along with the evil stench \n" + + "that filled the air. Jeeze, maybe you've\n" + + "done it. Have you really won?\n" + + "\n" + + "Something rumbles in the distance.\n" + + "A blue light begins to glow inside the\n" + + "ruined skull of the demon-spitter."); + + public final static String T5TEXT = ("What now? Looks totally different. Kind\n" + + "of like King Tut's condo. Well,\n" + + "whatever's here can't be any worse\n" + + "than usual. Can it? Or maybe it's best\n" + + "to let sleeping gods lie.."); + + public final static String T6TEXT = ("Time for a vacation. You've burst the\n" + + "bowels of hell and by golly you're ready\n" + + "for a break. You mutter to yourself,\n" + + "Maybe someone else can kick Hell's ass\n" + + "next time around. Ahead lies a quiet town,\n" + + "with peaceful flowing water, quaint\n" + + "buildings, and presumably no Hellspawn.\n" + + "\n" + + "As you step off the transport, you hear\n" + + "the stomp of a cyberdemon's iron shoe."); // // Character cast strings F_FINALE.C // -public final static String CC_ZOMBIE="ZOMBIEMAN"; -public final static String CC_SHOTGUN="SHOTGUN GUY"; -public final static String CC_HEAVY="HEAVY WEAPON DUDE"; -public final static String CC_IMP="IMP"; -public final static String CC_DEMON="DEMON"; -public final static String CC_LOST="LOST SOUL"; -public final static String CC_CACO="CACODEMON"; -public final static String CC_HELL="HELL KNIGHT"; -public final static String CC_BARON="BARON OF HELL"; -public final static String CC_ARACH="ARACHNOTRON"; -public final static String CC_PAIN="PAIN ELEMENTAL"; -public final static String CC_REVEN="REVENANT"; -public final static String CC_MANCU="MANCUBUS"; -public final static String CC_ARCH="ARCH-VILE"; -public final static String CC_SPIDER="THE SPIDER MASTERMIND"; -public final static String CC_CYBER="THE CYBERDEMON"; -public final static String CC_NAZI="WAFFEN SS. SIEG HEIL!"; -public final static String CC_KEEN="COMMANDER KEEN"; -public final static String CC_BARREL="EXPLODING BARREL"; -public final static String CC_HERO="OUR HERO"; - -} \ No newline at end of file + public final static String CC_ZOMBIE = "ZOMBIEMAN"; + public final static String CC_SHOTGUN = "SHOTGUN GUY"; + public final static String CC_HEAVY = "HEAVY WEAPON DUDE"; + public final static String CC_IMP = "IMP"; + public final static String CC_DEMON = "DEMON"; + public final static String CC_LOST = "LOST SOUL"; + public final static String CC_CACO = "CACODEMON"; + public final static String CC_HELL = "HELL KNIGHT"; + public final static String CC_BARON = "BARON OF HELL"; + public final static String CC_ARACH = "ARACHNOTRON"; + public final static String CC_PAIN = "PAIN ELEMENTAL"; + public final static String CC_REVEN = "REVENANT"; + public final static String CC_MANCU = "MANCUBUS"; + public final static String CC_ARCH = "ARCH-VILE"; + public final static String CC_SPIDER = "THE SPIDER MASTERMIND"; + public final static String CC_CYBER = "THE CYBERDEMON"; + public final static String CC_NAZI = "WAFFEN SS. SIEG HEIL!"; + public final static String CC_KEEN = "COMMANDER KEEN"; + public final static String CC_BARREL = "EXPLODING BARREL"; + public final static String CC_HERO = "OUR HERO"; + +} diff --git a/src/doom/event_t.java b/src/doom/event_t.java index 6d6cee75..37571c28 100644 --- a/src/doom/event_t.java +++ b/src/doom/event_t.java @@ -14,11 +14,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package doom; // Event structure. - import g.Signals.ScanCode; import java.awt.Point; import java.awt.Robot; @@ -32,178 +30,261 @@ @FunctionalInterface public interface event_t { + int MOUSE_LEFT = 1; int MOUSE_RIGHT = 2; int MOUSE_MID = 4; - + int JOY_1 = 1; int JOY_2 = 2; int JOY_3 = 4; int JOY_4 = 8; - + // Special FORCED and PAINFUL key and mouse cancel event. event_t EMPTY_EVENT = () -> evtype_t.ev_null; event_t CANCEL_KEYS = () -> evtype_t.ev_clear; event_t CANCEL_MOUSE = new event_t.mouseevent_t(evtype_t.ev_mouse, 0, 0, 0); - default boolean hasData() { return false; } - default boolean isKey() { return false; } - default boolean isKey(ScanCode sc) { return false; } - default T mapByKey(Function scMapper) { return scMapper.apply(null); } - default boolean withKey(Consumer scConsumer) { return false; } - default boolean ifKey(Predicate scCondition) { return false; } - default boolean withKeyChar(IntConsumer scCharConsumer) { return false; } - default boolean ifKeyChar(IntPredicate scCharCondition) { return false; } - default boolean withKeyAsciiChar(IntConsumer scAsciiCharConsumer) { return false; } - default boolean ifKeyAsciiChar(IntPredicate scCharCondition) { return false; } - default boolean withKey(Consumer scConsumer, Function extractor) { return false; } - default boolean ifKey(Predicate scCondition, Function extractor) { return false; } - default ScanCode getSC() { return ScanCode.SC_NULL; } - default boolean isMouse() { return false; } - default boolean isMouse(int button) { return false; } - default T mapByMouse(Function mouseMapper) { return mouseMapper.apply(null); } - default boolean withMouse(Consumer mouseConsumer) { return false; } - default boolean ifMouse(Predicate mouseCondition) { return false; } - default boolean withMouse(Consumer mouseConsumer, Function extractor) { return false; } - default boolean ifMouse(Predicate mouseCondition, Function extractor) { return false; } - default boolean isJoy() { return false; } - default boolean isJoy(int button) { return false; } - default T mapByJoy(Function joyMapper) { return joyMapper.apply(null); } - default boolean withJoy(Consumer joyConsumer) { return false; } - default boolean ifJoy(Predicate joyCondition) { return false; } - default boolean withJoy(Consumer joyConsumer, Function extractor) { return false; } - default boolean ifJoy(Predicate joyCondition, Function extractor) { return false; } + default boolean hasData() { + return false; + } + + default boolean isKey() { + return false; + } + + default boolean isKey(ScanCode sc) { + return false; + } + + default T mapByKey(Function scMapper) { + return scMapper.apply(null); + } + + default boolean withKey(Consumer scConsumer) { + return false; + } + + default boolean ifKey(Predicate scCondition) { + return false; + } + + default boolean withKeyChar(IntConsumer scCharConsumer) { + return false; + } + + default boolean ifKeyChar(IntPredicate scCharCondition) { + return false; + } + + default boolean withKeyAsciiChar(IntConsumer scAsciiCharConsumer) { + return false; + } + + default boolean ifKeyAsciiChar(IntPredicate scCharCondition) { + return false; + } + + default boolean withKey(Consumer scConsumer, Function extractor) { + return false; + } + + default boolean ifKey(Predicate scCondition, Function extractor) { + return false; + } + + default ScanCode getSC() { + return ScanCode.SC_NULL; + } + + default boolean isMouse() { + return false; + } + + default boolean isMouse(int button) { + return false; + } + + default T mapByMouse(Function mouseMapper) { + return mouseMapper.apply(null); + } + + default boolean withMouse(Consumer mouseConsumer) { + return false; + } + + default boolean ifMouse(Predicate mouseCondition) { + return false; + } + + default boolean withMouse(Consumer mouseConsumer, Function extractor) { + return false; + } + + default boolean ifMouse(Predicate mouseCondition, Function extractor) { + return false; + } + + default boolean isJoy() { + return false; + } + + default boolean isJoy(int button) { + return false; + } + + default T mapByJoy(Function joyMapper) { + return joyMapper.apply(null); + } + + default boolean withJoy(Consumer joyConsumer) { + return false; + } + + default boolean ifJoy(Predicate joyCondition) { + return false; + } + + default boolean withJoy(Consumer joyConsumer, Function extractor) { + return false; + } + + default boolean ifJoy(Predicate joyCondition, Function extractor) { + return false; + } + evtype_t type(); - + default boolean isType(evtype_t type) { return type() == type; } - + default boolean isKey(ScanCode sc, evtype_t type) { return type() == type && isKey(sc); } - + default boolean ifKey(evtype_t type, Predicate scCondition) { if (type() == type) { return ifKey(scCondition); } - + return false; } - + default boolean withKey(evtype_t type, Consumer scConsumer) { if (type() == type) { return event_t.this.withKey(scConsumer); } - + return false; } - + default boolean withKey(ScanCode sc, evtype_t type, Runnable runnable) { if (type() == type) { return withKey(sc, runnable); } - + return false; } - + default boolean withKey(ScanCode sc, Runnable runnable) { if (isKey(sc)) { runnable.run(); return true; } - + return false; } - + default boolean isMouse(int button, evtype_t type) { return type() == type && isMouse(button); } - + default boolean ifMouse(evtype_t type, Predicate mouseCondition) { if (type() == type) { return ifMouse(mouseCondition); } - + return false; } - + default boolean withMouse(evtype_t type, Consumer mouseConsumer) { if (type() == type) { return event_t.this.withMouse(mouseConsumer); } - + return false; } - + default boolean withMouse(int button, evtype_t type, Runnable runnable) { if (type() == type) { return withMouse(button, runnable); } - + return false; } - + default boolean withMouse(int button, Runnable runnable) { if (isMouse(button)) { runnable.run(); return true; } - + return false; } - + default boolean isJoy(int button, evtype_t type) { return type() == type && isJoy(button); } - + default boolean ifJoy(evtype_t type, Predicate joyCondition) { if (type() == type) { return ifJoy(joyCondition); } - + return false; } - + default boolean withJoy(evtype_t type, Consumer joyConsumer) { if (type() == type) { return event_t.this.withJoy(joyConsumer); } - + return false; } - + default boolean withJoy(int button, evtype_t type, Runnable runnable) { if (type() == type) { return withJoy(button, runnable); } - + return false; } - + default boolean withJoy(int button, Runnable runnable) { if (isJoy(button)) { runnable.run(); return true; } - + return false; } - + static int mouseBits(int button) { - switch(button) { + switch (button) { case MouseEvent.BUTTON1: return MOUSE_LEFT; case MouseEvent.BUTTON2: - return MOUSE_RIGHT; - case MouseEvent.BUTTON3: return MOUSE_MID; + case MouseEvent.BUTTON3: + return MOUSE_RIGHT; } - + return 0; } - + final class keyevent_t implements event_t { + public evtype_t type; public ScanCode sc; @@ -263,7 +344,7 @@ public boolean ifKeyAsciiChar(IntPredicate scAsciiCharCondition) { public boolean withKeyAsciiChar(IntConsumer scAsciiCharConsumer) { return sc.c > 255 ? false : withKeyChar(scAsciiCharConsumer); } - + @Override public boolean ifKey(Predicate scCondition, Function extractor) { return scCondition.test(extractor.apply(sc)); @@ -285,8 +366,9 @@ public ScanCode getSC() { return sc; } } - + final class mouseevent_t implements event_t { + public volatile evtype_t type; public volatile boolean robotMove; public volatile boolean processed = true; @@ -304,7 +386,7 @@ public mouseevent_t(evtype_t type, int buttons, int x, int y) { public boolean hasData() { return buttons != 0; } - + public void buttonOn(MouseEvent ev) { buttons |= mouseBits(ev.getButton()); } @@ -312,23 +394,23 @@ public void buttonOn(MouseEvent ev) { public void buttonOff(MouseEvent ev) { buttons ^= mouseBits(ev.getButton()); } - + public void processedNotify() { this.processed = true; } - + public void resetNotify() { this.processed = false; } - + public void moveIn(MouseEvent ev, int centreX, int centreY, boolean drag) { final int mouseX = ev.getX(), mouseY = ev.getY(); - + // Mouse haven't left centre of the window if (mouseX == centreX && mouseY == centreY) { return; } - + // A pure move has no buttons. if (!drag) { buttons = 0; @@ -360,7 +442,7 @@ public void moveIn(MouseEvent ev, int centreX, int centreY, boolean drag) { this.y += (centreY - mouseY) << 2; } } - + public void moveIn(MouseEvent ev, Robot robot, Point windowOffset, int centreX, int centreY, boolean drag) { moveIn(ev, centreX, centreY, drag); resetIn(robot, windowOffset, centreX, centreY); @@ -373,7 +455,7 @@ public void resetIn(Robot robot, Point windowOffset, int centreX, int centreY) { // Move the mouse to the window center robot.mouseMove(windowOffset.x + centreX, windowOffset.y + centreY); } - + @Override public evtype_t type() { return type; @@ -416,8 +498,9 @@ public T mapByMouse(Function mouseMapper) return mouseMapper.apply(this); } } - + final class joyevent_t implements event_t { + public evtype_t type; public int buttons; public int x, y; @@ -432,7 +515,7 @@ public joyevent_t(evtype_t type, int buttons, int x, int y) { @Override public boolean hasData() { return buttons != 0; - } + } @Override public evtype_t type() { diff --git a/src/doom/evtype_t.java b/src/doom/evtype_t.java index 29bc5591..f316c847 100644 --- a/src/doom/evtype_t.java +++ b/src/doom/evtype_t.java @@ -1,13 +1,12 @@ package doom; /** The possible events according to Doom */ - public enum evtype_t { - ev_null, - ev_keydown, - ev_keyup, - ev_mouse, - ev_joystick, - ev_mousewheel, // extension - ev_clear // Forcibly clear all button input (e.g. when losing focus) - }; + ev_null, + ev_keydown, + ev_keyup, + ev_mouse, + ev_joystick, + ev_mousewheel, // extension + ev_clear // Forcibly clear all button input (e.g. when losing focus) +}; diff --git a/src/doom/gameaction_t.java b/src/doom/gameaction_t.java index 75f36a46..d7416e5c 100644 --- a/src/doom/gameaction_t.java +++ b/src/doom/gameaction_t.java @@ -1,15 +1,15 @@ package doom; public enum gameaction_t { - ga_nothing, - ga_loadlevel, - ga_newgame, - ga_loadgame, - ga_savegame, - ga_playdemo, - ga_completed, - ga_victory, - ga_worlddone, - ga_screenshot, - ga_failure // HACK: communicate failures silently - } + ga_nothing, + ga_loadlevel, + ga_newgame, + ga_loadgame, + ga_savegame, + ga_playdemo, + ga_completed, + ga_victory, + ga_worlddone, + ga_screenshot, + ga_failure // HACK: communicate failures silently +} diff --git a/src/doom/items.java b/src/doom/items.java index bf8a9fbf..a890d160 100644 --- a/src/doom/items.java +++ b/src/doom/items.java @@ -41,99 +41,92 @@ // //----------------------------------------------------------------------------- -import defines.*; +import defines.ammotype_t; +import defines.statenum_t; -public class items{ +public class items { -public static weaponinfo_t[] weaponinfo= -{ - new weaponinfo_t( - // fist - ammotype_t.am_noammo, - statenum_t.S_PUNCHUP, - statenum_t.S_PUNCHDOWN, - statenum_t.S_PUNCH, - statenum_t.S_PUNCH1, - statenum_t.S_NULL - ), - new weaponinfo_t( - // pistol - ammotype_t.am_clip, - statenum_t.S_PISTOLUP, - statenum_t.S_PISTOLDOWN, - statenum_t.S_PISTOL, - statenum_t.S_PISTOL1, - statenum_t.S_PISTOLFLASH - ), new weaponinfo_t( - // shotgun - ammotype_t.am_shell, - statenum_t.S_SGUNUP, - statenum_t.S_SGUNDOWN, - statenum_t.S_SGUN, - statenum_t.S_SGUN1, - statenum_t.S_SGUNFLASH1 - ), - new weaponinfo_t( - // chaingun - ammotype_t.am_clip, - statenum_t.S_CHAINUP, - statenum_t.S_CHAINDOWN, - statenum_t.S_CHAIN, - statenum_t.S_CHAIN1, - statenum_t.S_CHAINFLASH1 - ), - new weaponinfo_t( - // missile launcher - ammotype_t.am_misl, - statenum_t.S_MISSILEUP, - statenum_t.S_MISSILEDOWN, - statenum_t.S_MISSILE, - statenum_t.S_MISSILE1, - statenum_t.S_MISSILEFLASH1 - ), - new weaponinfo_t( - // plasma rifle - ammotype_t.am_cell, - statenum_t.S_PLASMAUP, - statenum_t.S_PLASMADOWN, - statenum_t.S_PLASMA, - statenum_t.S_PLASMA1, - statenum_t.S_PLASMAFLASH1 - ), - new weaponinfo_t( - // bfg 9000 - ammotype_t.am_cell, - statenum_t.S_BFGUP, - statenum_t.S_BFGDOWN, - statenum_t.S_BFG, - statenum_t.S_BFG1, - statenum_t.S_BFGFLASH1 - ), - new weaponinfo_t( - // chainsaw - ammotype_t.am_noammo, - statenum_t.S_SAWUP, - statenum_t.S_SAWDOWN, - statenum_t.S_SAW, - statenum_t.S_SAW1, - statenum_t.S_NULL - ), - new weaponinfo_t( - // super shotgun - ammotype_t.am_shell, - statenum_t.S_DSGUNUP, - statenum_t.S_DSGUNDOWN, - statenum_t.S_DSGUN, - statenum_t.S_DSGUN1, - statenum_t.S_DSGUNFLASH1 - ) - }; + public static weaponinfo_t[] weaponinfo + = { + new weaponinfo_t( + // fist + ammotype_t.am_noammo, + statenum_t.S_PUNCHUP, + statenum_t.S_PUNCHDOWN, + statenum_t.S_PUNCH, + statenum_t.S_PUNCH1, + statenum_t.S_NULL + ), + new weaponinfo_t( + // pistol + ammotype_t.am_clip, + statenum_t.S_PISTOLUP, + statenum_t.S_PISTOLDOWN, + statenum_t.S_PISTOL, + statenum_t.S_PISTOL1, + statenum_t.S_PISTOLFLASH + ), new weaponinfo_t( + // shotgun + ammotype_t.am_shell, + statenum_t.S_SGUNUP, + statenum_t.S_SGUNDOWN, + statenum_t.S_SGUN, + statenum_t.S_SGUN1, + statenum_t.S_SGUNFLASH1 + ), + new weaponinfo_t( + // chaingun + ammotype_t.am_clip, + statenum_t.S_CHAINUP, + statenum_t.S_CHAINDOWN, + statenum_t.S_CHAIN, + statenum_t.S_CHAIN1, + statenum_t.S_CHAINFLASH1 + ), + new weaponinfo_t( + // missile launcher + ammotype_t.am_misl, + statenum_t.S_MISSILEUP, + statenum_t.S_MISSILEDOWN, + statenum_t.S_MISSILE, + statenum_t.S_MISSILE1, + statenum_t.S_MISSILEFLASH1 + ), + new weaponinfo_t( + // plasma rifle + ammotype_t.am_cell, + statenum_t.S_PLASMAUP, + statenum_t.S_PLASMADOWN, + statenum_t.S_PLASMA, + statenum_t.S_PLASMA1, + statenum_t.S_PLASMAFLASH1 + ), + new weaponinfo_t( + // bfg 9000 + ammotype_t.am_cell, + statenum_t.S_BFGUP, + statenum_t.S_BFGDOWN, + statenum_t.S_BFG, + statenum_t.S_BFG1, + statenum_t.S_BFGFLASH1 + ), + new weaponinfo_t( + // chainsaw + ammotype_t.am_noammo, + statenum_t.S_SAWUP, + statenum_t.S_SAWDOWN, + statenum_t.S_SAW, + statenum_t.S_SAW1, + statenum_t.S_NULL + ), + new weaponinfo_t( + // super shotgun + ammotype_t.am_shell, + statenum_t.S_DSGUNUP, + statenum_t.S_DSGUNDOWN, + statenum_t.S_DSGUN, + statenum_t.S_DSGUN1, + statenum_t.S_DSGUNFLASH1 + ) + }; } - - - - - - - - diff --git a/src/doom/net.java b/src/doom/net.java index 94880406..b28b6537 100644 --- a/src/doom/net.java +++ b/src/doom/net.java @@ -40,16 +40,12 @@ // //----------------------------------------------------------------------------- - //static const char rcsid[] = "$Id: net.java,v 1.5 2011/02/11 00:11:13 velktron Exp $"; - - //#include "m_menu.h" //#include "i_system.h" //#include "i_video.h" //#include "i_net.h" //#include "g_game.h" - // //Network play related stuff. //There is a data struct that stores network @@ -57,33 +53,28 @@ //one that defines the actual packets to //be transmitted. // +public class net { + protected static int NCMD_EXIT = 0x80000000; + protected static int NCMD_RETRANSMIT = 0x40000000; + protected static int NCMD_SETUP = 0x20000000; + protected static int NCMD_KILL = 0x10000000; // kill game + protected static int NCMD_CHECKSUM = 0x0fffffff; -public class net{ - -protected static int NCMD_EXIT= 0x80000000; -protected static int NCMD_RETRANSMIT =0x40000000; -protected static int NCMD_SETUP =0x20000000; -protected static int NCMD_KILL = 0x10000000; // kill game -protected static int NCMD_CHECKSUM = 0x0fffffff; - -protected static int DOOMCOM_ID = 0x12345678; + protected static int DOOMCOM_ID = 0x12345678; //Max computers/players in a game. -protected static int MAXNETNODES = 8; - + protected static int MAXNETNODES = 8; //Networking and tick handling related. -protected static int BACKUPTICS = 12; - + protected static int BACKUPTICS = 12; // commant_t -protected static int CMD_SEND = 1; -protected static int CMD_GET = 2; - -doomcom_t doomcom; -doomdata_t netbuffer; // points inside doomcom + protected static int CMD_SEND = 1; + protected static int CMD_GET = 2; + doomcom_t doomcom; + doomdata_t netbuffer; // points inside doomcom // // NETWORKING @@ -94,51 +85,44 @@ public class net{ // // a gametic cannot be run until nettics[] > gametic for all players // -public static int RESENDCOUNT =10; -public static int PL_DRONE =0x80; // bit flag in doomdata->player + public static int RESENDCOUNT = 10; + public static int PL_DRONE = 0x80; // bit flag in doomdata->player -ticcmd_t[] localcmds= new ticcmd_t[BACKUPTICS]; + ticcmd_t[] localcmds = new ticcmd_t[BACKUPTICS]; -final int MAXPLAYERS = 4; + final int MAXPLAYERS = 4; -ticcmd_t [][] netcmds=new ticcmd_t [MAXPLAYERS][BACKUPTICS]; -int[] nettics=new int[MAXNETNODES]; -boolean[] nodeingame=new boolean[MAXNETNODES]; // set false as nodes leave game -boolean[] remoteresend=new boolean[MAXNETNODES]; // set when local needs tics -int[] resendto=new int[MAXNETNODES]; // set when remote needs tics -int[] resendcount=new int[MAXNETNODES]; + ticcmd_t[][] netcmds = new ticcmd_t[MAXPLAYERS][BACKUPTICS]; + int[] nettics = new int[MAXNETNODES]; + boolean[] nodeingame = new boolean[MAXNETNODES]; // set false as nodes leave game + boolean[] remoteresend = new boolean[MAXNETNODES]; // set when local needs tics + int[] resendto = new int[MAXNETNODES]; // set when remote needs tics + int[] resendcount = new int[MAXNETNODES]; -int[] nodeforplayer=new int[MAXPLAYERS]; - -int maketic; -int lastnettic; -int skiptics; -int ticdup; -int maxsend; // BACKUPTICS/(2*ticdup)-1 + int[] nodeforplayer = new int[MAXPLAYERS]; + int maketic; + int lastnettic; + int skiptics; + int ticdup; + int maxsend; // BACKUPTICS/(2*ticdup)-1 //void D_ProcessEvents (void); //void G_BuildTiccmd (ticcmd_t *cmd); //void D_DoAdvanceDemo (void); - -boolean reboundpacket; -doomdata_t reboundstore; - - + boolean reboundpacket; + doomdata_t reboundstore; // // //123 - -/** MAES: interesting. After testing it was found to return the following size: - * - */ - -int NetbufferSize () -{ + /** MAES: interesting. After testing it was found to return the following size: + * + */ + int NetbufferSize() { // return (int)(((doomdata_t)0).cmds[netbuffer.numtics]); - return (8*(netbuffer.numtics+1)); -} + return (8 * (netbuffer.numtics + 1)); + } } /* diff --git a/src/doom/pic_t.java b/src/doom/pic_t.java index 6181101b..5a46c3da 100644 --- a/src/doom/pic_t.java +++ b/src/doom/pic_t.java @@ -1,16 +1,15 @@ package doom; public class pic_t { - + public pic_t(byte width, byte height, byte data) { super(); this.width = width; this.height = height; this.data = data; } - - public byte width; - public byte height; - public byte data; -} + public byte width; + public byte height; + public byte data; +} diff --git a/src/doom/player_t.java b/src/doom/player_t.java index 976041a6..bd6a9880 100644 --- a/src/doom/player_t.java +++ b/src/doom/player_t.java @@ -1,15 +1,48 @@ package doom; -import static data.Defines.*; -import static data.Limits.*; +import static data.Defines.BT_CHANGE; +import static data.Defines.BT_SPECIAL; +import static data.Defines.BT_USE; +import static data.Defines.BT_WEAPONMASK; +import static data.Defines.BT_WEAPONSHIFT; +import static data.Defines.INFRATICS; +import static data.Defines.INVISTICS; +import static data.Defines.INVULNTICS; +import static data.Defines.IRONTICS; +import static data.Defines.NUMAMMO; +import static data.Defines.NUMPOWERS; +import static data.Defines.NUMWEAPONS; +import static data.Defines.PST_DEAD; +import static data.Defines.PST_LIVE; +import static data.Defines.PST_REBORN; +import static data.Defines.TIC_MUL; +import static data.Defines.TOCENTER; +import static data.Defines.VIEWHEIGHT; +import static data.Defines.pw_infrared; +import static data.Defines.pw_invisibility; +import static data.Defines.pw_invulnerability; +import static data.Defines.pw_ironfeet; +import static data.Defines.pw_strength; +import static data.Limits.MAXHEALTH; +import static data.Limits.MAXPLAYERS; import data.Tables; -import static data.Tables.*; -import static data.info.*; +import static data.Tables.ANG180; +import static data.Tables.ANG90; +import static data.Tables.BITS32; +import static data.Tables.FINEANGLES; +import static data.Tables.FINEMASK; +import static data.Tables.finecosine; +import static data.Tables.finesine; +import static data.info.states; import data.sounds.sfxenum_t; import data.state_t; -import defines.*; +import defines.ammotype_t; +import defines.card_t; +import defines.skill_t; +import defines.statenum_t; import doom.SourceCode.G_Game; -import static doom.SourceCode.G_Game.*; +import static doom.SourceCode.G_Game.G_PlayerFinishLevel; +import static doom.SourceCode.G_Game.G_PlayerReborn; import doom.SourceCode.P_Pspr; import static doom.SourceCode.P_Pspr.P_BringUpWeapon; import static doom.SourceCode.P_Pspr.P_SetPsprite; @@ -20,14 +53,22 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; -import static m.fixed_t.*; +import static m.fixed_t.FRACBITS; +import static m.fixed_t.FRACUNIT; +import static m.fixed_t.FixedMul; +import static m.fixed_t.MAPFRACUNIT; import p.ActiveStates.PlayerSpriteConsumer; import p.mobj_t; -import static p.mobj_t.*; +import static p.mobj_t.MF_JUSTATTACKED; +import static p.mobj_t.MF_NOCLIP; +import static p.mobj_t.MF_SHADOW; import p.pspdef_t; import rr.sector_t; import utils.C2JUtils; -import static utils.C2JUtils.*; +import static utils.C2JUtils.eval; +import static utils.C2JUtils.flags; +import static utils.C2JUtils.memset; +import static utils.C2JUtils.pointer; import static utils.GenericCopy.malloc; import v.graphics.Palettes; import w.DoomBuffer; @@ -254,7 +295,7 @@ public void reset() { @Override public player_t clone() - throws CloneNotSupportedException { + throws CloneNotSupportedException { return (player_t) super.clone(); } @@ -300,7 +341,7 @@ public void MovePlayer() { } if ((cmd.forwardmove != 0 || cmd.sidemove != 0) - && mo.mobj_state == states[statenum_t.S_PLAY.ordinal()]) { + && mo.mobj_state == states[statenum_t.S_PLAY.ordinal()]) { this.mo.SetMobjState(statenum_t.S_PLAY_RUN1); } @@ -408,7 +449,7 @@ public boolean GiveAmmo(ammotype_t amm, int num) { } if (DOOM.gameskill == skill_t.sk_baby - || DOOM.gameskill == skill_t.sk_nightmare) { + || DOOM.gameskill == skill_t.sk_nightmare) { // give double ammo in trainer mode, // you'll need in nightmare num <<= 1; @@ -444,7 +485,7 @@ public boolean GiveAmmo(ammotype_t amm, int num) { case am_shell: if (readyweapon == weapontype_t.wp_fist - || readyweapon == weapontype_t.wp_pistol) { + || readyweapon == weapontype_t.wp_pistol) { if (weaponowned[weapontype_t.wp_shotgun.ordinal()]) { pendingweapon = weapontype_t.wp_shotgun; } @@ -453,7 +494,7 @@ public boolean GiveAmmo(ammotype_t amm, int num) { case am_cell: if (readyweapon == weapontype_t.wp_fist - || readyweapon == weapontype_t.wp_pistol) { + || readyweapon == weapontype_t.wp_pistol) { if (weaponowned[weapontype_t.wp_plasma.ordinal()]) { pendingweapon = weapontype_t.wp_plasma; } @@ -485,7 +526,7 @@ public boolean GiveWeapon(weapontype_t weapn, boolean dropped) { int weapon = weapn.ordinal(); if (DOOM.netgame && (DOOM.deathmatch != true) // ???? was "2" - && !dropped) { + && !dropped) { // leave placed weapons forever on net games if (weaponowned[weapon]) { return false; @@ -676,7 +717,7 @@ protected void PlayerInSpecialSector() { case 4: // STROBE HURT if (!eval(powers[pw_ironfeet]) - || (DOOM.random.P_Random() < 5)) { + || (DOOM.random.P_Random() < 5)) { if (!flags(DOOM.leveltime, 0x1f)) { DOOM.actions.DamageMobj(mo, null, null, 20); } @@ -705,7 +746,7 @@ protected void PlayerInSpecialSector() { default: DOOM.doomSystem.Error("P_PlayerInSpecialSector: unknown special %d", sector.special); break; - }; + } } // @@ -723,8 +764,8 @@ public void CalcHeight() { // Note: a LUT allows for effects // like a ramp with low health. this.bob - = FixedMul(mo.momx, mo.momx) - + FixedMul(mo.momy, mo.momy); + = FixedMul(mo.momx, mo.momx) + + FixedMul(mo.momy, mo.momy); this.bob >>= 2; @@ -807,9 +848,9 @@ public void DeathThink() { if (attacker != null && attacker != mo) { angle = DOOM.sceneRenderer.PointToAngle2(mo.x, - mo.y, - attacker.x, - attacker.y); + mo.y, + attacker.x, + attacker.y); delta = Tables.addAngles(angle, -mo.angle); @@ -939,8 +980,8 @@ public int identify() { /* psprnum_t enum */ public static int ps_weapon = 0, - ps_flash = 1, - NUMPSPRITES = 2; + ps_flash = 1, + NUMPSPRITES = 2; public static int LOWERSPEED = MAPFRACUNIT * 6; public static int RAISESPEED = MAPFRACUNIT * 6; @@ -1044,7 +1085,8 @@ public void BringUpWeapon() { } if (pendingweapon == weapontype_t.wp_chainsaw) { - S_StartSound: { + S_StartSound: + { DOOM.doomSound.StartSound(mo, sfxenum_t.sfx_sawup); } } @@ -1054,7 +1096,8 @@ public void BringUpWeapon() { pendingweapon = weapontype_t.wp_nochange; psprites[ps_weapon].sy = WEAPONBOTTOM; - P_SetPsprite: { + P_SetPsprite: + { this.SetPsprite(ps_weapon, newstate); } } @@ -1088,29 +1131,29 @@ public boolean CheckAmmo() { // Preferences are set here. do { if (weaponowned[weapontype_t.wp_plasma.ordinal()] - && (this.ammo[ammotype_t.am_cell.ordinal()] != 0) - && !DOOM.isShareware()) { + && (this.ammo[ammotype_t.am_cell.ordinal()] != 0) + && !DOOM.isShareware()) { pendingweapon = weapontype_t.wp_plasma; } else if (weaponowned[weapontype_t.wp_supershotgun.ordinal()] - && this.ammo[ammotype_t.am_shell.ordinal()] > 2 - && DOOM.isCommercial()) { + && this.ammo[ammotype_t.am_shell.ordinal()] > 2 + && DOOM.isCommercial()) { pendingweapon = weapontype_t.wp_supershotgun; } else if (weaponowned[weapontype_t.wp_chaingun.ordinal()] - && this.ammo[ammotype_t.am_clip.ordinal()] != 0) { + && this.ammo[ammotype_t.am_clip.ordinal()] != 0) { pendingweapon = weapontype_t.wp_chaingun; } else if (weaponowned[weapontype_t.wp_shotgun.ordinal()] - && this.ammo[ammotype_t.am_shell.ordinal()] != 0) { + && this.ammo[ammotype_t.am_shell.ordinal()] != 0) { pendingweapon = weapontype_t.wp_shotgun; } else if (this.ammo[ammotype_t.am_clip.ordinal()] != 0) { pendingweapon = weapontype_t.wp_pistol; } else if (weaponowned[weapontype_t.wp_chainsaw.ordinal()]) { pendingweapon = weapontype_t.wp_chainsaw; } else if (weaponowned[weapontype_t.wp_missile.ordinal()] - && this.ammo[ammotype_t.am_misl.ordinal()] != 0) { + && this.ammo[ammotype_t.am_misl.ordinal()] != 0) { pendingweapon = weapontype_t.wp_missile; } else if (weaponowned[weapontype_t.wp_bfg.ordinal()] - && this.ammo[ammotype_t.am_cell.ordinal()] > 40 - && !DOOM.isShareware()) { + && this.ammo[ammotype_t.am_cell.ordinal()] > 40 + && !DOOM.isShareware()) { pendingweapon = weapontype_t.wp_bfg; } else { // If everything fails. @@ -1121,8 +1164,8 @@ public boolean CheckAmmo() { // Now set appropriate weapon overlay. this.SetPsprite( - ps_weapon, - weaponinfo[readyweapon.ordinal()].downstate); + ps_weapon, + weaponinfo[readyweapon.ordinal()].downstate); return false; } @@ -1133,8 +1176,8 @@ public boolean CheckAmmo() { */ public void DropWeapon() { this.SetPsprite( - ps_weapon, - weaponinfo[readyweapon.ordinal()].downstate); + ps_weapon, + weaponinfo[readyweapon.ordinal()].downstate); } /** @@ -1214,27 +1257,27 @@ public void PlayerThink(player_t player) { // If chainsaw is available, it won't change back to the fist // unless player also has berserk. if (newweapon == weapontype_t.wp_fist - && player.weaponowned[weapontype_t.wp_chainsaw.ordinal()] - && !(player.readyweapon == weapontype_t.wp_chainsaw - && eval(player.powers[pw_strength]))) { + && player.weaponowned[weapontype_t.wp_chainsaw.ordinal()] + && !(player.readyweapon == weapontype_t.wp_chainsaw + && eval(player.powers[pw_strength]))) { newweapon = weapontype_t.wp_chainsaw; } // Will switch between SG and SSG in Doom 2. if (DOOM.isCommercial() - && newweapon == weapontype_t.wp_shotgun - && player.weaponowned[weapontype_t.wp_supershotgun.ordinal()] - && player.readyweapon != weapontype_t.wp_supershotgun) { + && newweapon == weapontype_t.wp_shotgun + && player.weaponowned[weapontype_t.wp_supershotgun.ordinal()] + && player.readyweapon != weapontype_t.wp_supershotgun) { newweapon = weapontype_t.wp_supershotgun; } if (player.weaponowned[newweapon.ordinal()] - && newweapon != player.readyweapon) { + && newweapon != player.readyweapon) { // Do not go to plasma or BFG in shareware, // even if cheated. if ((newweapon != weapontype_t.wp_plasma - && newweapon != weapontype_t.wp_bfg) - || !DOOM.isShareware()) { + && newweapon != weapontype_t.wp_bfg) + || !DOOM.isShareware()) { player.pendingweapon = newweapon; } } @@ -1294,7 +1337,7 @@ && eval(player.powers[pw_strength]))) { } } else if (eval(player.powers[pw_infrared])) { if (player.powers[pw_infrared] > 4 * 32 - || flags(player.powers[pw_infrared], 8)) { + || flags(player.powers[pw_infrared], 8)) { // almost full bright player.fixedcolormap = Palettes.COLORMAP_BULLBRIGHT; } else { @@ -1452,7 +1495,7 @@ public void write(DataOutputStream f) throws IOException { @Override public void pack(ByteBuffer buf) - throws IOException { + throws IOException { ByteOrder bo = ByteOrder.LITTLE_ENDIAN; buf.order(bo); diff --git a/src/doom/playerstate_t.java b/src/doom/playerstate_t.java index 784529b3..4bb2fc72 100644 --- a/src/doom/playerstate_t.java +++ b/src/doom/playerstate_t.java @@ -1,14 +1,13 @@ package doom; - // Player states. - // - public enum playerstate_t - { - // Playing or camping. - PST_LIVE, - // Dead on the ground, view follows killer. - PST_DEAD, - // Ready to restart/respawn??? - PST_REBORN +// Player states. +// +public enum playerstate_t { + // Playing or camping. + PST_LIVE, + // Dead on the ground, view follows killer. + PST_DEAD, + // Ready to restart/respawn??? + PST_REBORN - }; \ No newline at end of file +}; diff --git a/src/doom/th_class.java b/src/doom/th_class.java index a96ce708..177a8868 100644 --- a/src/doom/th_class.java +++ b/src/doom/th_class.java @@ -4,14 +4,12 @@ * cph 2002/01/13: for consistency with the main thinker list, keep objects * pending deletion on a class list too */ - - public enum th_class { - th_delete, - th_misc, - th_friends, - th_enemies, - th_all; - - public static final int NUMTHCLASS=th_class.values().length; + th_delete, + th_misc, + th_friends, + th_enemies, + th_all; + + public static final int NUMTHCLASS = th_class.values().length; } diff --git a/src/doom/thinker_t.java b/src/doom/thinker_t.java index c4f119fa..ba669f79 100644 --- a/src/doom/thinker_t.java +++ b/src/doom/thinker_t.java @@ -5,9 +5,8 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import p.ActiveStates; -import static utils.C2JUtils.pointer; - import p.ThinkerStates; +import static utils.C2JUtils.pointer; import w.CacheableDoomObject; import w.IPackableDoomObject; import w.IReadableDoomObject; @@ -31,7 +30,6 @@ public class thinker_t implements CacheableDoomObject, IReadableDoomObject, IPac * Next, previous thinkers in same class */ //public thinker_t cnext, cprev; - /** * extra fields, to use when archiving/unarchiving for * identification. Also in blocklinks, etc. @@ -40,7 +38,7 @@ public class thinker_t implements CacheableDoomObject, IReadableDoomObject, IPac @Override public void read(DataInputStream f) - throws IOException { + throws IOException { readbuffer.position(0); readbuffer.order(ByteOrder.LITTLE_ENDIAN); f.read(readbuffer.array()); @@ -52,7 +50,7 @@ public void read(DataInputStream f) */ @Override public void pack(ByteBuffer b) - throws IOException { + throws IOException { // It's possible to reconstruct even by hashcodes. // As for the function, that should be implied by the mobj_t type. b.order(ByteOrder.LITTLE_ENDIAN); @@ -64,7 +62,7 @@ public void pack(ByteBuffer b) @Override public void unpack(ByteBuffer b) - throws IOException { + throws IOException { // We are supposed to archive pointers to other thinkers, // but they are rather useless once on disk. b.order(ByteOrder.LITTLE_ENDIAN); diff --git a/src/doom/ticcmd_t.java b/src/doom/ticcmd_t.java index e8e16f32..347f45d6 100644 --- a/src/doom/ticcmd_t.java +++ b/src/doom/ticcmd_t.java @@ -4,22 +4,19 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; - import w.CacheableDoomObject; import w.IReadableDoomObject; -public class ticcmd_t implements IDatagramSerializable, IReadableDoomObject,CacheableDoomObject{ - +public class ticcmd_t implements IDatagramSerializable, IReadableDoomObject, CacheableDoomObject { + // The length datagrams are supposed to have, for full compatibility. - - public static final int TICCMDLEN=8; - + public static final int TICCMDLEN = 8; + // Initializes ticcmd buffer, too. - - public ticcmd_t(){ - this.buffer=new byte[TICCMDLEN]; + public ticcmd_t() { + this.buffer = new byte[TICCMDLEN]; } - + /** *2048 for move */ public byte forwardmove; @@ -31,27 +28,23 @@ public ticcmd_t(){ /** checks for net game */ public short consistancy; - + /** MAES: these are unsigned bytes :-( * However over networks, if we wish for vanilla compatibility, * these must be reduced to 8-bit "chars" * */ + public char chatchar, buttons; + + /** HERETIC look/fly up/down/centering */ + public char lookfly; - public char chatchar, buttons; - - /** HERETIC look/fly up/down/centering */ - public char lookfly; - // TODO: will be ignored during vanilla demos. Consider using specialized // per-demotype readers instead of Cacheable/Unpackage. - /** replaces G_CmdChecksum (ticcmd_t cmd) */ - ///////////////////////////////////////////// - // For datagram serialization private byte[] buffer; - + public int getChecksum(ticcmd_t cmd) { int sum = 0; sum += forwardmove; @@ -61,85 +54,84 @@ public int getChecksum(ticcmd_t cmd) { sum += chatchar; sum += buttons; return sum; - } + } /** because Cloneable is bullshit */ - - public void copyTo(ticcmd_t dest){ - dest.forwardmove = forwardmove; - dest.sidemove = sidemove; - dest.angleturn= angleturn; - dest.consistancy= consistancy; - dest.chatchar= chatchar; - dest.buttons= buttons; - dest.lookfly=lookfly; - } - - private static StringBuilder sb=new StringBuilder(); - - public String toString(){ - sb.setLength(0); - sb.append(" forwardmove "); - sb.append(Integer.toHexString(this.forwardmove)); - sb.append(" sidemove "); - sb.append(Integer.toHexString(this.sidemove)); - sb.append(" angleturn "); - sb.append(Integer.toHexString(this.angleturn)); - sb.append(" consistancy "); - sb.append(Integer.toHexString(this.consistancy)); - sb.append(" chatchar "); - sb.append(chatchar); + public void copyTo(ticcmd_t dest) { + dest.forwardmove = forwardmove; + dest.sidemove = sidemove; + dest.angleturn = angleturn; + dest.consistancy = consistancy; + dest.chatchar = chatchar; + dest.buttons = buttons; + dest.lookfly = lookfly; + } + + private static StringBuilder sb = new StringBuilder(); + + public String toString() { + sb.setLength(0); + sb.append(" forwardmove "); + sb.append(Integer.toHexString(this.forwardmove)); + sb.append(" sidemove "); + sb.append(Integer.toHexString(this.sidemove)); + sb.append(" angleturn "); + sb.append(Integer.toHexString(this.angleturn)); + sb.append(" consistancy "); + sb.append(Integer.toHexString(this.consistancy)); + sb.append(" chatchar "); + sb.append(chatchar); sb.append(" buttons "); - sb.append(Integer.toHexString(this.buttons)); - return sb.toString(); - } + sb.append(Integer.toHexString(this.buttons)); + return sb.toString(); + } @Override public byte[] pack() { - buffer[0]=forwardmove; - buffer[1]=sidemove; - buffer[2]=(byte) (angleturn>>>8); - buffer[3]=(byte) (angleturn&0x00FF); - buffer[4]=(byte) (consistancy>>>8); - buffer[5]=(byte) (consistancy&0x00FF); + buffer[0] = forwardmove; + buffer[1] = sidemove; + buffer[2] = (byte) (angleturn >>> 8); + buffer[3] = (byte) (angleturn & 0x00FF); + buffer[4] = (byte) (consistancy >>> 8); + buffer[5] = (byte) (consistancy & 0x00FF); // We only send 8 bytes because the original length was 8 bytes. - buffer[6]=(byte) (chatchar&0x00FF); - buffer[7]=(byte) (buttons&0x00FF); - + buffer[6] = (byte) (chatchar & 0x00FF); + buffer[7] = (byte) (buttons & 0x00FF); + return buffer; } @Override public void pack(byte[] buf, int offset) { - buf[0+offset]=forwardmove; - buf[1+offset]=sidemove; - buf[2+offset]=(byte) (angleturn>>>8); - buf[3+offset]=(byte) (angleturn&0x00FF); - buf[4+offset]=(byte) (consistancy>>>8); - buf[5+offset]=(byte) (consistancy&0x00FF); + buf[0 + offset] = forwardmove; + buf[1 + offset] = sidemove; + buf[2 + offset] = (byte) (angleturn >>> 8); + buf[3 + offset] = (byte) (angleturn & 0x00FF); + buf[4 + offset] = (byte) (consistancy >>> 8); + buf[5 + offset] = (byte) (consistancy & 0x00FF); // We only send 8 bytes because the original length was 8 bytes. - buf[6+offset]=(byte) (chatchar&0x00FF); - buf[7+offset]=(byte) (buttons&0x00FF); - + buf[6 + offset] = (byte) (chatchar & 0x00FF); + buf[7 + offset] = (byte) (buttons & 0x00FF); + } @Override public void unpack(byte[] buf) { - unpack(buf,0); - } + unpack(buf, 0); + } @Override public void unpack(byte[] buf, int offset) { - forwardmove=buf[0+offset]; - sidemove= buf[1+offset]; - angleturn=(short)(buf[2+offset]<<8|buf[3+offset]); - consistancy=(short)(buf[4+offset]<<8|buf[5+offset]); + forwardmove = buf[0 + offset]; + sidemove = buf[1 + offset]; + angleturn = (short) (buf[2 + offset] << 8 | buf[3 + offset]); + consistancy = (short) (buf[4 + offset] << 8 | buf[5 + offset]); // We blow these up to full chars. - chatchar=(char)(0x00FF& buf[6+offset]); - buttons=(char) (0x00FF& buf[7+offset]); - + chatchar = (char) (0x00FF & buf[6 + offset]); + buttons = (char) (0x00FF & buf[7 + offset]); + } @Override @@ -150,32 +142,31 @@ public byte[] cached() { @Override public void read(DataInputStream f) throws IOException { - iobuffer.position(0); - iobuffer.order(ByteOrder.LITTLE_ENDIAN); - f.read(iobuffer.array()); - unpack(iobuffer); + iobuffer.position(0); + iobuffer.order(ByteOrder.LITTLE_ENDIAN); + f.read(iobuffer.array()); + unpack(iobuffer); } - + /** This is useful only when loading/saving players from savegames. * It's NOT interchangeable with datagram methods, because it * does not use the network byte order. */ - @Override public void unpack(ByteBuffer f) throws IOException { f.order(ByteOrder.LITTLE_ENDIAN); - forwardmove=f.get(); - sidemove= f.get(); + forwardmove = f.get(); + sidemove = f.get(); // Even if they use the "unsigned char" syntax, angleturn is signed. - angleturn=f.getShort(); - consistancy=f.getShort(); + angleturn = f.getShort(); + consistancy = f.getShort(); // We blow these up to full chars. - chatchar=(char) f.get(); - buttons=(char) f.get(); - + chatchar = (char) f.get(); + buttons = (char) f.get(); + } - + /** Ditto, we only pack some of the fields. * * @param f @@ -185,15 +176,15 @@ public void pack(ByteBuffer f) throws IOException { f.order(ByteOrder.LITTLE_ENDIAN); f.put(forwardmove); - f.put(sidemove); + f.put(sidemove); // LE order on disk for vanilla compatibility. f.putShort(angleturn); f.putShort(consistancy); // We crimp these to bytes :-( f.put((byte) chatchar); - f.put((byte) buttons); + f.put((byte) buttons); } - - private static ByteBuffer iobuffer=ByteBuffer.allocate(8); - + + private static ByteBuffer iobuffer = ByteBuffer.allocate(8); + }; diff --git a/src/doom/wbplayerstruct_t.java b/src/doom/wbplayerstruct_t.java index e132e310..0df29d24 100644 --- a/src/doom/wbplayerstruct_t.java +++ b/src/doom/wbplayerstruct_t.java @@ -1,45 +1,48 @@ package doom; - // +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; + // INTERMISSION // Structure passed e.g. to WI_Start(wb) // +public class wbplayerstruct_t implements Cloneable { + + private static final Logger LOGGER = Loggers.getLogger(wbplayerstruct_t.class.getName()); -public class wbplayerstruct_t implements Cloneable{ - - public wbplayerstruct_t(){ - frags=new int[4]; + public wbplayerstruct_t() { + frags = new int[4]; } - public boolean in; // whether the player is in game - - /** Player stats, kills, collected items etc. */ - public int skills; - public int sitems; - public int ssecret; - public int stime; - public int[] frags; - /** current score on entry, modified on return */ - public int score; - - public wbplayerstruct_t clone(){ - wbplayerstruct_t r=null; + public boolean in; // whether the player is in game + + /** Player stats, kills, collected items etc. */ + public int skills; + public int sitems; + public int ssecret; + public int stime; + public int[] frags; + /** current score on entry, modified on return */ + public int score; + + public wbplayerstruct_t clone() { + wbplayerstruct_t r = null; try { - r = (wbplayerstruct_t)super.clone(); + r = (wbplayerstruct_t) super.clone(); } catch (CloneNotSupportedException e) { - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "wbplayerstruct_t: clone failure", e); } - /*r.in=this.in; + /*r.in=this.in; r.skills=this.skills; r.sitems=this.sitems; r.ssecret=this.ssecret; r.stime=this.stime; */ - System.arraycopy(this.frags, 0, r.frags,0,r.frags.length); - // r.score=this.score; - - + System.arraycopy(this.frags, 0, r.frags, 0, r.frags.length); + // r.score=this.score; + return r; - - } - - } + + } + +} diff --git a/src/doom/wbstartstruct_t.java b/src/doom/wbstartstruct_t.java index be317e7a..70ac771a 100644 --- a/src/doom/wbstartstruct_t.java +++ b/src/doom/wbstartstruct_t.java @@ -1,45 +1,49 @@ package doom; import static data.Limits.MAXPLAYERS; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import static utils.GenericCopy.malloc; -public class wbstartstruct_t implements Cloneable{ +public class wbstartstruct_t implements Cloneable { - public wbstartstruct_t(){ - plyr = malloc(wbplayerstruct_t::new, wbplayerstruct_t[]::new, MAXPLAYERS); + private static final Logger LOGGER = Loggers.getLogger(wbstartstruct_t.class.getName()); + + public wbstartstruct_t() { + plyr = malloc(wbplayerstruct_t::new, wbplayerstruct_t[]::new, MAXPLAYERS); + } + + public int epsd; // episode # (0-2) + + // if true, splash the secret level + public boolean didsecret; + + // previous and next levels, origin 0 + public int last; + public int next; + + public int maxkills; + public int maxitems; + public int maxsecret; + public int maxfrags; + + /** the par time */ + public int partime; + + /** index of this player in game */ + public int pnum; + /** meant to be treated as a "struct", therefore assignments should be deep copies */ + public wbplayerstruct_t[] plyr; + + public wbstartstruct_t clone() { + wbstartstruct_t cl = null; + try { + cl = (wbstartstruct_t) super.clone(); + } catch (CloneNotSupportedException e) { + LOGGER.log(Level.SEVERE, "wbstartstruct_t: clone failure", e); } - - public int epsd; // episode # (0-2) - - // if true, splash the secret level - public boolean didsecret; - - // previous and next levels, origin 0 - public int last; - public int next; - - public int maxkills; - public int maxitems; - public int maxsecret; - public int maxfrags; - - /** the par time */ - public int partime; - - /** index of this player in game */ - public int pnum; - /** meant to be treated as a "struct", therefore assignments should be deep copies */ - public wbplayerstruct_t[] plyr; - - public wbstartstruct_t clone(){ - wbstartstruct_t cl=null; - try { - cl=(wbstartstruct_t)super.clone(); - } catch (CloneNotSupportedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - /*cl.epsd=this.epsd; + /*cl.epsd=this.epsd; cl.didsecret=this.didsecret; cl.last=this.last; cl.next=this.next; @@ -49,13 +53,13 @@ public wbstartstruct_t clone(){ cl.maxkills=this.maxkills; cl.partime=this.partime; cl.pnum=this.pnum;*/ - for (int i=0;i extends AbstractEndLevel { + private static final Logger LOGGER = Loggers.getLogger(EndLevel.class.getName()); + ////////////////// STATUS /////////////////// private final DoomMain DOOM; @@ -432,7 +444,7 @@ protected void drawEL() { DOOM.graphicSystem.DrawPatchScaled(FG, c[i], DOOM.vs, lnodes[wbs.epsd][n].x, lnodes[wbs.epsd][n].y); } else { // DEBUG - System.out.println("Could not place patch on level " + n + 1); + LOGGER.log(Level.FINE, String.format("Could not place patch on level %d", n + 1)); } } @@ -456,18 +468,20 @@ protected void initAnimatedBack() { a.ctr = -1; if (null != a.type) // specify the next time to draw it - switch (a.type) { - case ANIM_ALWAYS: - a.nexttic = bcnt + 1 + (DOOM.random.M_Random() % a.period); - break; - case ANIM_RANDOM: - a.nexttic = bcnt + 1 + a.data2 + (DOOM.random.M_Random() % a.data1); - break; - case ANIM_LEVEL: - a.nexttic = bcnt + 1; - break; - default: - break; + { + switch (a.type) { + case ANIM_ALWAYS: + a.nexttic = bcnt + 1 + (DOOM.random.M_Random() % a.period); + break; + case ANIM_RANDOM: + a.nexttic = bcnt + 1 + a.data2 + (DOOM.random.M_Random() % a.data1); + break; + case ANIM_LEVEL: + a.nexttic = bcnt + 1; + break; + default: + break; + } } } @@ -859,7 +873,8 @@ protected void initDeathmatchStats() { } } - WI_initAnimatedBack: { + WI_initAnimatedBack: + { initAnimatedBack(); } } @@ -1040,14 +1055,15 @@ protected void initNetgameStats() { } cnt_kills[i] = cnt_items[i] = cnt_secret[i] = cnt_frags[i] = 0; - + dofrags += fragSum(i); } //Suspicious - Good Sign 2017/05/08 dofrags = ~ ~dofrags; - WI_initAnimatedBack: { + WI_initAnimatedBack: + { initAnimatedBack(); } } @@ -1262,7 +1278,8 @@ protected void initStats() { cnt_time = cnt_par = -1; cnt_pause = TICRATE; - WI_initAnimatedBack: { + WI_initAnimatedBack: + { initAnimatedBack(); } } @@ -1717,9 +1734,9 @@ public void Drawer() { case NoState: drawNoState(); break; - + default: - break; + break; } } @@ -1772,23 +1789,28 @@ protected void initVariables(wbstartstruct_t wbstartstruct) { @SourceCode.Exact @WI_Stuff.C(WI_Start) public void Start(wbstartstruct_t wbstartstruct) { - WI_initVariables: { + WI_initVariables: + { initVariables(wbstartstruct); } - WI_loadData: { + WI_loadData: + { loadData(); } if (DOOM.deathmatch) { - WI_initDeathmatchStats: { + WI_initDeathmatchStats: + { initDeathmatchStats(); } } else if (DOOM.netgame) { - WI_initNetgameStats: { + WI_initNetgameStats: + { initNetgameStats(); } } else { - WI_initStats: { + WI_initStats: + { initStats(); } } diff --git a/src/f/Finale.java b/src/f/Finale.java index ef4540d4..53872b94 100644 --- a/src/f/Finale.java +++ b/src/f/Finale.java @@ -12,7 +12,8 @@ import data.sounds.musicenum_t; import data.sounds.sfxenum_t; import data.state_t; -import defines.*; +import defines.gamestate_t; +import defines.statenum_t; import doom.DoomMain; import doom.SourceCode.F_Finale; import static doom.SourceCode.F_Finale.F_Responder; @@ -28,11 +29,11 @@ import rr.patch_t; import rr.spritedef_t; import rr.spriteframe_t; -import static utils.C2JUtils.*; -import static v.DoomGraphicSystem.*; +import static utils.C2JUtils.eval; +import static v.DoomGraphicSystem.V_FLIPPEDPATCH; import v.graphics.Blocks; import v.renderers.DoomScreen; -import static v.renderers.DoomScreen.*; +import static v.renderers.DoomScreen.FG; // Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- @@ -55,630 +56,627 @@ // Game completion, final screen animation. // //----------------------------------------------------------------------------- - public class Finale { - final DoomMain DOOM; - int finalestage; - int finalecount; - - private static final int TEXTSPEED = 3; - private static final int TEXTWAIT = 250; - - final static String[] doom_text = { E1TEXT, E2TEXT, E3TEXT, E4TEXT }; - final static String[] doom2_text = { C1TEXT, C2TEXT, C3TEXT, C4TEXT, C5TEXT, C6TEXT }; - final static String[] plut_text = { P1TEXT, P2TEXT, P3TEXT, P4TEXT, P5TEXT, P6TEXT }; - final static String[] tnt_text = { T1TEXT, T2TEXT, T3TEXT, T4TEXT, T5TEXT, T6TEXT }; - String finaletext; - String finaleflat; - - /** - * F_StartFinale - */ - public void StartFinale() { - DOOM.setGameAction(gameaction_t.ga_nothing); - DOOM.gamestate = gamestate_t.GS_FINALE; - DOOM.viewactive = false; - DOOM.automapactive = false; - String[] texts = null; - - // Pick proper text. - switch (DOOM.getGameMode()) { - case commercial: - case pack_xbla: - case freedoom2: - case freedm: - texts = doom2_text; - break; - case pack_tnt: - texts = tnt_text; - break; - case pack_plut: - texts = plut_text; - break; - case shareware: - case registered: - case retail: - case freedoom1: - texts = doom_text; - break; - default: - break; - } - - // Okay - IWAD dependend stuff. - // This has been changed severly, and - // some stuff might have changed in the process. - switch (DOOM.getGameMode()) { - - // DOOM 1 - E1, E3 or E4, but each nine missions - case freedoom1: - case shareware: - case registered: - case retail: { - DOOM.doomSound.ChangeMusic(musicenum_t.mus_victor, true); - - switch (DOOM.gameepisode) { - case 1: - finaleflat = "FLOOR4_8"; - finaletext = texts[0]; - break; - case 2: - finaleflat = "SFLR6_1"; - finaletext = texts[1]; - break; - case 3: - finaleflat = "MFLR8_4"; - finaletext = texts[2]; - break; - case 4: - finaleflat = "MFLR8_3"; - finaletext = texts[3]; - break; - default: - // Ouch. - break; - } - break; - } - - // DOOM II and missions packs with E1, M34 - case freedm: - case freedoom2: - case commercial: - case pack_xbla: - case pack_tnt: - case pack_plut: { - DOOM.doomSound.ChangeMusic(musicenum_t.mus_read_m, true); - - switch (DOOM.gamemap) { - case 6: - finaleflat = "SLIME16"; - finaletext = texts[0]; - break; - case 11: - finaleflat = "RROCK14"; - finaletext = texts[1]; - break; - case 20: - finaleflat = "RROCK07"; - finaletext = texts[2]; - break; - case 30: - finaleflat = "RROCK17"; - finaletext = texts[3]; - break; - case 15: - finaleflat = "RROCK13"; - finaletext = texts[4]; - break; - case 31: - finaleflat = "RROCK19"; - finaletext = texts[5]; - break; - default: - // Ouch. - break; - } - break; - } - - // Indeterminate. - default: - DOOM.doomSound.ChangeMusic(musicenum_t.mus_read_m, true); - finaleflat = "F_SKY1"; // Not used anywhere else. - finaletext = doom2_text[1]; - break; - } - - finalestage = 0; - finalecount = 0; - - } + final DoomMain DOOM; + int finalestage; + int finalecount; + + private static final int TEXTSPEED = 3; + private static final int TEXTWAIT = 250; + + final static String[] doom_text = {E1TEXT, E2TEXT, E3TEXT, E4TEXT}; + final static String[] doom2_text = {C1TEXT, C2TEXT, C3TEXT, C4TEXT, C5TEXT, C6TEXT}; + final static String[] plut_text = {P1TEXT, P2TEXT, P3TEXT, P4TEXT, P5TEXT, P6TEXT}; + final static String[] tnt_text = {T1TEXT, T2TEXT, T3TEXT, T4TEXT, T5TEXT, T6TEXT}; + String finaletext; + String finaleflat; + + /** + * F_StartFinale + */ + public void StartFinale() { + DOOM.setGameAction(gameaction_t.ga_nothing); + DOOM.gamestate = gamestate_t.GS_FINALE; + DOOM.viewactive = false; + DOOM.automapactive = false; + String[] texts = null; + + // Pick proper text. + switch (DOOM.getGameMode()) { + case commercial: + case pack_xbla: + case freedoom2: + case freedm: + texts = doom2_text; + break; + case pack_tnt: + texts = tnt_text; + break; + case pack_plut: + texts = plut_text; + break; + case shareware: + case registered: + case retail: + case freedoom1: + texts = doom_text; + break; + default: + break; + } + + // Okay - IWAD dependend stuff. + // This has been changed severly, and + // some stuff might have changed in the process. + switch (DOOM.getGameMode()) { + + // DOOM 1 - E1, E3 or E4, but each nine missions + case freedoom1: + case shareware: + case registered: + case retail: { + DOOM.doomSound.ChangeMusic(musicenum_t.mus_victor, true); + + switch (DOOM.gameepisode) { + case 1: + finaleflat = "FLOOR4_8"; + finaletext = texts[0]; + break; + case 2: + finaleflat = "SFLR6_1"; + finaletext = texts[1]; + break; + case 3: + finaleflat = "MFLR8_4"; + finaletext = texts[2]; + break; + case 4: + finaleflat = "MFLR8_3"; + finaletext = texts[3]; + break; + default: + // Ouch. + break; + } + break; + } + + // DOOM II and missions packs with E1, M34 + case freedm: + case freedoom2: + case commercial: + case pack_xbla: + case pack_tnt: + case pack_plut: { + DOOM.doomSound.ChangeMusic(musicenum_t.mus_read_m, true); + + switch (DOOM.gamemap) { + case 6: + finaleflat = "SLIME16"; + finaletext = texts[0]; + break; + case 11: + finaleflat = "RROCK14"; + finaletext = texts[1]; + break; + case 20: + finaleflat = "RROCK07"; + finaletext = texts[2]; + break; + case 30: + finaleflat = "RROCK17"; + finaletext = texts[3]; + break; + case 15: + finaleflat = "RROCK13"; + finaletext = texts[4]; + break; + case 31: + finaleflat = "RROCK19"; + finaletext = texts[5]; + break; + default: + // Ouch. + break; + } + break; + } + + // Indeterminate. + default: + DOOM.doomSound.ChangeMusic(musicenum_t.mus_read_m, true); + finaleflat = "F_SKY1"; // Not used anywhere else. + finaletext = doom2_text[1]; + break; + } + + finalestage = 0; + finalecount = 0; + + } @F_Finale.C(F_Responder) - public boolean Responder(event_t event) { - if (finalestage == 2) - return CastResponder(event); - - return false; - } - - /** - * F_Ticker - */ - - public void Ticker() { - - // check for skipping - if ((DOOM.isCommercial()) && (finalecount > 50)) { - int i; - // go on to the next level - for (i = 0; i < MAXPLAYERS; i++) { - if (DOOM.players[i].cmd.buttons != 0) { - break; + public boolean Responder(event_t event) { + if (finalestage == 2) { + return CastResponder(event); + } + + return false; + } + + /** + * F_Ticker + */ + public void Ticker() { + + // check for skipping + if ((DOOM.isCommercial()) && (finalecount > 50)) { + int i; + // go on to the next level + for (i = 0; i < MAXPLAYERS; i++) { + if (DOOM.players[i].cmd.buttons != 0) { + break; } } - if (i < MAXPLAYERS) { - if (DOOM.gamemap == 30) { - StartCast(); + if (i < MAXPLAYERS) { + if (DOOM.gamemap == 30) { + StartCast(); } else { - DOOM.setGameAction(gameaction_t.ga_worlddone); + DOOM.setGameAction(gameaction_t.ga_worlddone); } - } - } + } + } - // advance animation - finalecount++; + // advance animation + finalecount++; - if (finalestage == 2) { - CastTicker(); - return; - } + if (finalestage == 2) { + CastTicker(); + return; + } - if (DOOM.isCommercial()) { - return; + if (DOOM.isCommercial()) { + return; } - - // MAES: this is when we can transition to bunny. - if ((finalestage == 0) && finalecount > finaletext.length() * TEXTSPEED + TEXTWAIT) { - finalecount = 0; - finalestage = 1; - DOOM.wipegamestate = gamestate_t.GS_MINUS_ONE; // force a wipe - - if (DOOM.gameepisode == 3) { - DOOM.doomSound.StartMusic(musicenum_t.mus_bunny); - } - } - } - // - // F_TextWrite - // + // MAES: this is when we can transition to bunny. + if ((finalestage == 0) && finalecount > finaletext.length() * TEXTSPEED + TEXTWAIT) { + finalecount = 0; + finalestage = 1; + DOOM.wipegamestate = gamestate_t.GS_MINUS_ONE; // force a wipe - // #include "hu_stuff.h" - patch_t[] hu_font; + if (DOOM.gameepisode == 3) { + DOOM.doomSound.StartMusic(musicenum_t.mus_bunny); + } + } + } + + // + // F_TextWrite + // + // #include "hu_stuff.h" + patch_t[] hu_font; - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public void TextWrite() { - // erase the entire screen to a tiled background - byte[] src = DOOM.wadLoader.CacheLumpName(finaleflat, PU_CACHE, flat_t.class).data; + // erase the entire screen to a tiled background + byte[] src = DOOM.wadLoader.CacheLumpName(finaleflat, PU_CACHE, flat_t.class).data; if (Engine.getConfig().equals(Settings.scale_screen_tiles, Boolean.TRUE)) { final Object scaled = ((Blocks) DOOM.graphicSystem) - .ScaleBlock(DOOM.graphicSystem.convertPalettedBlock(src), 64, 64, - DOOM.graphicSystem.getScalingX(), DOOM.graphicSystem.getScalingY() - ); - + .ScaleBlock(DOOM.graphicSystem.convertPalettedBlock(src), 64, 64, + DOOM.graphicSystem.getScalingX(), DOOM.graphicSystem.getScalingY() + ); + ((Blocks) DOOM.graphicSystem) - .TileScreen(FG, scaled, new Rectangle(0, 0, - 64 * DOOM.graphicSystem.getScalingX(), 64 * DOOM.graphicSystem.getScalingY()) - ); + .TileScreen(FG, scaled, new Rectangle(0, 0, + 64 * DOOM.graphicSystem.getScalingX(), 64 * DOOM.graphicSystem.getScalingY()) + ); } else { ((Blocks) DOOM.graphicSystem) - .TileScreen(FG, DOOM.graphicSystem.convertPalettedBlock(src), - new Rectangle(0, 0, 64, 64) - ); + .TileScreen(FG, DOOM.graphicSystem.convertPalettedBlock(src), + new Rectangle(0, 0, 64, 64) + ); } - // draw some of the text onto the screen - int cx = 10, cy = 10; - final char[] ch = finaletext.toCharArray(); + // draw some of the text onto the screen + int cx = 10, cy = 10; + final char[] ch = finaletext.toCharArray(); + + int count = (finalecount - 10) / TEXTSPEED; + if (count < 0) { + count = 0; + } + + // _D_: added min between count and ch.length, so that the text is not + // written all at once + for (int i = 0; i < Math.min(ch.length, count); i++) { + int c = ch[i]; + if (c == 0) { + break; + } + if (c == '\n') { + cx = 10; + cy += 11; + continue; + } + + c = Character.toUpperCase(c) - HU_FONTSTART; + if (c < 0 || c > HU_FONTSIZE) { + cx += 4; + continue; + } - int count = (finalecount - 10) / TEXTSPEED; - if (count < 0) { - count = 0; + if (cx + hu_font[c].width > DOOM.vs.getScreenWidth()) { + break; + } + DOOM.graphicSystem.DrawPatchScaled(FG, hu_font[c], DOOM.vs, cx, cy); + cx += hu_font[c].width; } - // _D_: added min between count and ch.length, so that the text is not - // written all at once - for (int i = 0; i < Math.min(ch.length, count); i++) { - int c = ch[i]; - if (c == 0) - break; - if (c == '\n') { - cx = 10; - cy += 11; - continue; - } - - c = Character.toUpperCase(c) - HU_FONTSTART; - if (c < 0 || c > HU_FONTSIZE) { - cx += 4; - continue; - } - - if (cx + hu_font[c].width > DOOM.vs.getScreenWidth()) { - break; + } + + private final castinfo_t[] castorder; + + int castnum; + int casttics; + state_t caststate; + boolean castdeath; + int castframes; + int castonmelee; + boolean castattacking; + + // + // F_StartCast + // + // extern gamestate_t wipegamestate; + public void StartCast() { + DOOM.wipegamestate = gamestate_t.GS_MINUS_ONE; // force a screen wipe + castnum = 0; + caststate = states[mobjinfo[castorder[castnum].type.ordinal()].seestate.ordinal()]; + casttics = caststate.tics; + castdeath = false; + finalestage = 2; + castframes = 0; + castonmelee = 0; + castattacking = false; + DOOM.doomSound.ChangeMusic(musicenum_t.mus_evil, true); + } + + // + // F_CastTicker + // + public void CastTicker() { + if (--casttics > 0) { + return; // not time to change state yet + } + if (caststate.tics == -1 || caststate.nextstate == statenum_t.S_NULL || caststate.nextstate == null) { + // switch from deathstate to next monster + castnum++; + castdeath = false; + if (castorder[castnum].name == null) { + castnum = 0; } - DOOM.graphicSystem.DrawPatchScaled(FG, hu_font[c], DOOM.vs, cx, cy); - cx += hu_font[c].width; - } - - } - - private final castinfo_t[] castorder; - - int castnum; - int casttics; - state_t caststate; - boolean castdeath; - int castframes; - int castonmelee; - boolean castattacking; - - // - // F_StartCast - // - // extern gamestate_t wipegamestate; - - public void StartCast() { - DOOM.wipegamestate = gamestate_t.GS_MINUS_ONE; // force a screen wipe - castnum = 0; - caststate = states[mobjinfo[castorder[castnum].type.ordinal()].seestate.ordinal()]; - casttics = caststate.tics; - castdeath = false; - finalestage = 2; - castframes = 0; - castonmelee = 0; - castattacking = false; - DOOM.doomSound.ChangeMusic(musicenum_t.mus_evil, true); - } - - // - // F_CastTicker - // - public void CastTicker() { - if (--casttics > 0) - return; // not time to change state yet - - if (caststate.tics == -1 || caststate.nextstate == statenum_t.S_NULL || caststate.nextstate == null) { - // switch from deathstate to next monster - castnum++; - castdeath = false; - if (castorder[castnum].name == null) { - castnum = 0; + + if (mobjinfo[castorder[castnum].type.ordinal()].seesound.ordinal() != 0) { + DOOM.doomSound.StartSound(null, mobjinfo[castorder[castnum].type.ordinal()].seesound); + } + + caststate = states[mobjinfo[castorder[castnum].type.ordinal()].seestate.ordinal()]; + castframes = 0; + } else { + final sfxenum_t sfx; + + // just advance to next state in animation + if (caststate == states[statenum_t.S_PLAY_ATK1.ordinal()]) { + stopattack(); // Oh, gross hack! + afterstopattack(); + return; // bye ... } - - if (mobjinfo[castorder[castnum].type.ordinal()].seesound.ordinal() != 0) { - DOOM.doomSound.StartSound(null, mobjinfo[castorder[castnum].type.ordinal()].seesound); + + final statenum_t st = caststate.nextstate; + caststate = states[st.ordinal()]; + castframes++; + + // sound hacks.... + switch (st) { + case S_PLAY_ATK1: + sfx = sfxenum_t.sfx_dshtgn; + break; + case S_POSS_ATK2: + sfx = sfxenum_t.sfx_pistol; + break; + case S_SPOS_ATK2: + sfx = sfxenum_t.sfx_shotgn; + break; + case S_VILE_ATK2: + sfx = sfxenum_t.sfx_vilatk; + break; + case S_SKEL_FIST2: + sfx = sfxenum_t.sfx_skeswg; + break; + case S_SKEL_FIST4: + sfx = sfxenum_t.sfx_skepch; + break; + case S_SKEL_MISS2: + sfx = sfxenum_t.sfx_skeatk; + break; + case S_FATT_ATK8: + case S_FATT_ATK5: + case S_FATT_ATK2: + sfx = sfxenum_t.sfx_firsht; + break; + case S_CPOS_ATK2: + case S_CPOS_ATK3: + case S_CPOS_ATK4: + sfx = sfxenum_t.sfx_shotgn; + break; + case S_TROO_ATK3: + sfx = sfxenum_t.sfx_claw; + break; + case S_SARG_ATK2: + sfx = sfxenum_t.sfx_sgtatk; + break; + case S_BOSS_ATK2: + case S_BOS2_ATK2: + case S_HEAD_ATK2: + sfx = sfxenum_t.sfx_firsht; + break; + case S_SKULL_ATK2: + sfx = sfxenum_t.sfx_sklatk; + break; + case S_SPID_ATK2: + case S_SPID_ATK3: + sfx = sfxenum_t.sfx_shotgn; + break; + case S_BSPI_ATK2: + sfx = sfxenum_t.sfx_plasma; + break; + case S_CYBER_ATK2: + case S_CYBER_ATK4: + case S_CYBER_ATK6: + sfx = sfxenum_t.sfx_rlaunc; + break; + case S_PAIN_ATK3: + sfx = sfxenum_t.sfx_sklatk; + break; + default: + sfx = null; + break; } - - caststate = states[mobjinfo[castorder[castnum].type.ordinal()].seestate.ordinal()]; - castframes = 0; - } else { - final sfxenum_t sfx; - - // just advance to next state in animation - if (caststate == states[statenum_t.S_PLAY_ATK1.ordinal()]) { - stopattack(); // Oh, gross hack! - afterstopattack(); - return; // bye ... - } - - final statenum_t st = caststate.nextstate; - caststate = states[st.ordinal()]; - castframes++; - - // sound hacks.... - switch (st) { - case S_PLAY_ATK1: - sfx = sfxenum_t.sfx_dshtgn; - break; - case S_POSS_ATK2: - sfx = sfxenum_t.sfx_pistol; - break; - case S_SPOS_ATK2: - sfx = sfxenum_t.sfx_shotgn; - break; - case S_VILE_ATK2: - sfx = sfxenum_t.sfx_vilatk; - break; - case S_SKEL_FIST2: - sfx = sfxenum_t.sfx_skeswg; - break; - case S_SKEL_FIST4: - sfx = sfxenum_t.sfx_skepch; - break; - case S_SKEL_MISS2: - sfx = sfxenum_t.sfx_skeatk; - break; - case S_FATT_ATK8: - case S_FATT_ATK5: - case S_FATT_ATK2: - sfx = sfxenum_t.sfx_firsht; - break; - case S_CPOS_ATK2: - case S_CPOS_ATK3: - case S_CPOS_ATK4: - sfx = sfxenum_t.sfx_shotgn; - break; - case S_TROO_ATK3: - sfx = sfxenum_t.sfx_claw; - break; - case S_SARG_ATK2: - sfx = sfxenum_t.sfx_sgtatk; - break; - case S_BOSS_ATK2: - case S_BOS2_ATK2: - case S_HEAD_ATK2: - sfx = sfxenum_t.sfx_firsht; - break; - case S_SKULL_ATK2: - sfx = sfxenum_t.sfx_sklatk; - break; - case S_SPID_ATK2: - case S_SPID_ATK3: - sfx = sfxenum_t.sfx_shotgn; - break; - case S_BSPI_ATK2: - sfx = sfxenum_t.sfx_plasma; - break; - case S_CYBER_ATK2: - case S_CYBER_ATK4: - case S_CYBER_ATK6: - sfx = sfxenum_t.sfx_rlaunc; - break; - case S_PAIN_ATK3: - sfx = sfxenum_t.sfx_sklatk; - break; - default: - sfx = null; - break; - } - - if (sfx != null) {// Fixed mute thanks to _D_ 8/6/2011 - DOOM.doomSound.StartSound(null, sfx); + + if (sfx != null) {// Fixed mute thanks to _D_ 8/6/2011 + DOOM.doomSound.StartSound(null, sfx); } - } + } - if (castframes == 12) { - // go into attack frame - castattacking = true; - if (castonmelee != 0) { - caststate = states[mobjinfo[castorder[castnum].type.ordinal()].meleestate.ordinal()]; + if (castframes == 12) { + // go into attack frame + castattacking = true; + if (castonmelee != 0) { + caststate = states[mobjinfo[castorder[castnum].type.ordinal()].meleestate.ordinal()]; } else { - caststate = states[mobjinfo[castorder[castnum].type.ordinal()].missilestate.ordinal()]; + caststate = states[mobjinfo[castorder[castnum].type.ordinal()].missilestate.ordinal()]; } - castonmelee ^= 1; - if (caststate == states[statenum_t.S_NULL.ordinal()]) { - if (castonmelee != 0) { - caststate = states[mobjinfo[castorder[castnum].type.ordinal()].meleestate.ordinal()]; + castonmelee ^= 1; + if (caststate == states[statenum_t.S_NULL.ordinal()]) { + if (castonmelee != 0) { + caststate = states[mobjinfo[castorder[castnum].type.ordinal()].meleestate.ordinal()]; } else { - caststate = states[mobjinfo[castorder[castnum].type .ordinal()].missilestate.ordinal()]; + caststate = states[mobjinfo[castorder[castnum].type.ordinal()].missilestate.ordinal()]; } - } - } + } + } - if (castattacking) { - if (castframes == 24 || caststate == states[mobjinfo[castorder[castnum].type.ordinal()].seestate.ordinal()]) { - stopattack(); + if (castattacking) { + if (castframes == 24 || caststate == states[mobjinfo[castorder[castnum].type.ordinal()].seestate.ordinal()]) { + stopattack(); } - } - - afterstopattack(); - } - - protected void stopattack() { - castattacking = false; - castframes = 0; - caststate = states[mobjinfo[castorder[castnum].type.ordinal()].seestate.ordinal()]; - } - - protected void afterstopattack() { - casttics = caststate.tics; - - if (casttics == -1) { - casttics = 15; } - } - /** - * CastResponder - */ + afterstopattack(); + } + + protected void stopattack() { + castattacking = false; + castframes = 0; + caststate = states[mobjinfo[castorder[castnum].type.ordinal()].seestate.ordinal()]; + } + + protected void afterstopattack() { + casttics = caststate.tics; + + if (casttics == -1) { + casttics = 15; + } + } + + /** + * CastResponder + */ + public boolean CastResponder(event_t ev) { + if (!ev.isType(evtype_t.ev_keydown)) { + return false; + } - public boolean CastResponder(event_t ev) { - if (!ev.isType(evtype_t.ev_keydown)) { - return false; + if (castdeath) { + return true; // already in dying frames } - if (castdeath) { - return true; // already in dying frames + // go into death frame + castdeath = true; + caststate = states[mobjinfo[castorder[castnum].type.ordinal()].deathstate.ordinal()]; + casttics = caststate.tics; + castframes = 0; + castattacking = false; + + if (mobjinfo[castorder[castnum].type.ordinal()].deathsound != null) { + DOOM.doomSound.StartSound(null, mobjinfo[castorder[castnum].type.ordinal()].deathsound); } - // go into death frame - castdeath = true; - caststate = states[mobjinfo[castorder[castnum].type.ordinal()].deathstate.ordinal()]; - casttics = caststate.tics; - castframes = 0; - castattacking = false; - - if (mobjinfo[castorder[castnum].type.ordinal()].deathsound != null) { - DOOM.doomSound.StartSound(null, mobjinfo[castorder[castnum].type.ordinal()].deathsound); + return true; + } + + public void CastPrint(String text) { + int c, width = 0; + + // find width + final char[] ch = text.toCharArray(); + + for (int i = 0; i < ch.length; i++) { + c = ch[i]; + if (c == 0) { + break; + } + c = Character.toUpperCase(c) - HU_FONTSTART; + if (c < 0 || c > HU_FONTSIZE) { + width += 4; + continue; + } + + width += hu_font[c].width; } - return true; - } - - public void CastPrint(String text) { - int c, width = 0; - - // find width - final char[] ch = text.toCharArray(); - - for (int i = 0; i < ch.length; i++) { - c = ch[i]; - if (c == 0) - break; - c = Character.toUpperCase(c) - HU_FONTSTART; - if (c < 0 || c > HU_FONTSIZE) { - width += 4; - continue; - } - - width += hu_font[c].width; - } - - // draw it - int cx = 160 - width / 2; - // ch = text; - for (int i = 0; i < ch.length; i++) { - c = ch[i]; - if (c == 0) - break; - c = Character.toUpperCase(c) - HU_FONTSTART; - if (c < 0 || c > HU_FONTSIZE) { - cx += 4; - continue; - } - - DOOM.graphicSystem.DrawPatchScaled(FG, hu_font[c], DOOM.vs, cx, 180); - cx += hu_font[c].width; - } - } - - /** - * F_CastDrawer - * - * @throws IOException - */ - - // public void V_DrawPatchFlipped (int x, int y, int scrn, patch_t patch); - - public void CastDrawer() { - // erase the entire screen to a background - DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("BOSSBACK", PU_CACHE), DOOM.vs, 0, 0); - this.CastPrint(castorder[castnum].name); - - // draw the current frame in the middle of the screen - final spritedef_t sprdef = DOOM.spriteManager.getSprite(caststate.sprite.ordinal()); - final spriteframe_t sprframe = sprdef.spriteframes[caststate.frame & FF_FRAMEMASK]; - final int lump = sprframe.lump[0]; - final boolean flip = eval(sprframe.flip[0]); - // flip=false; - // lump=0; - - final patch_t patch = DOOM.wadLoader.CachePatchNum(lump + DOOM.spriteManager.getFirstSpriteLump()); - - if (flip) { - DOOM.graphicSystem.DrawPatchScaled(FG, patch, DOOM.vs, 160, 170, V_FLIPPEDPATCH); + // draw it + int cx = 160 - width / 2; + // ch = text; + for (int i = 0; i < ch.length; i++) { + c = ch[i]; + if (c == 0) { + break; + } + c = Character.toUpperCase(c) - HU_FONTSTART; + if (c < 0 || c > HU_FONTSIZE) { + cx += 4; + continue; + } + + DOOM.graphicSystem.DrawPatchScaled(FG, hu_font[c], DOOM.vs, cx, 180); + cx += hu_font[c].width; + } + } + + /** + * F_CastDrawer + * + * @throws IOException + */ + // public void V_DrawPatchFlipped (int x, int y, int scrn, patch_t patch); + public void CastDrawer() { + // erase the entire screen to a background + DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("BOSSBACK", PU_CACHE), DOOM.vs, 0, 0); + this.CastPrint(castorder[castnum].name); + + // draw the current frame in the middle of the screen + final spritedef_t sprdef = DOOM.spriteManager.getSprite(caststate.sprite.ordinal()); + final spriteframe_t sprframe = sprdef.spriteframes[caststate.frame & FF_FRAMEMASK]; + final int lump = sprframe.lump[0]; + final boolean flip = eval(sprframe.flip[0]); + // flip=false; + // lump=0; + + final patch_t patch = DOOM.wadLoader.CachePatchNum(lump + DOOM.spriteManager.getFirstSpriteLump()); + + if (flip) { + DOOM.graphicSystem.DrawPatchScaled(FG, patch, DOOM.vs, 160, 170, V_FLIPPEDPATCH); } else { - DOOM.graphicSystem.DrawPatchScaled(FG, patch, DOOM.vs, 160, 170); + DOOM.graphicSystem.DrawPatchScaled(FG, patch, DOOM.vs, 160, 170); } - } + } - protected int laststage; + protected int laststage; - /** - * F_BunnyScroll - */ - public void BunnyScroll() { - final patch_t p1 = DOOM.wadLoader.CachePatchName("PFUB2", PU_LEVEL); - final patch_t p2 = DOOM.wadLoader.CachePatchName("PFUB1", PU_LEVEL); + /** + * F_BunnyScroll + */ + public void BunnyScroll() { + final patch_t p1 = DOOM.wadLoader.CachePatchName("PFUB2", PU_LEVEL); + final patch_t p2 = DOOM.wadLoader.CachePatchName("PFUB1", PU_LEVEL); - //V.MarkRect(0, 0, DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight()); + //V.MarkRect(0, 0, DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight()); + int scrolled = 320 - (finalecount - 230) / 2; - int scrolled = 320 - (finalecount - 230) / 2; - - if (scrolled > 320) { - scrolled = 320; + if (scrolled > 320) { + scrolled = 320; } - + if (scrolled < 0) { - scrolled = 0; + scrolled = 0; } - for (int x = 0; x < 320; x++) { - if (x + scrolled < 320) { + for (int x = 0; x < 320; x++) { + if (x + scrolled < 320) { DOOM.graphicSystem.DrawPatchColScaled(FG, p1, DOOM.vs, x, x + scrolled); } else { DOOM.graphicSystem.DrawPatchColScaled(FG, p2, DOOM.vs, x, x + scrolled - 320); } - } + } - if (finalecount < 1130) { - return; + if (finalecount < 1130) { + return; } else if (finalecount < 1180) { - DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("END0", PU_CACHE), DOOM.vs, (320 - 13 * 8) / 2, ((200 - 8 * 8) / 2)); - laststage = 0; - return; - } - - int stage = (finalecount - 1180) / 5; - - if (stage > 6) { - stage = 6; + DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("END0", PU_CACHE), DOOM.vs, (320 - 13 * 8) / 2, ((200 - 8 * 8) / 2)); + laststage = 0; + return; + } + + int stage = (finalecount - 1180) / 5; + + if (stage > 6) { + stage = 6; + } + + if (stage > laststage) { + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_pistol); + laststage = stage; + } + + final String name = ("END" + stage); + DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName(name, PU_CACHE), DOOM.vs, (320 - 13 * 8) / 2, ((200 - 8 * 8) / 2)); + } + + // + // F_Drawer + // + public void Drawer() { + if (finalestage == 2) { + CastDrawer(); + return; } - - if (stage > laststage) { - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_pistol); - laststage = stage; - } - - final String name = ("END" + stage); - DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName(name, PU_CACHE), DOOM.vs, (320 - 13 * 8) / 2, ((200 - 8 * 8) / 2)); - } - - // - // F_Drawer - // - public void Drawer() { - if (finalestage == 2) { - CastDrawer(); - return; - } - - if (finalestage == 0) { - TextWrite(); + + if (finalestage == 0) { + TextWrite(); } else { - switch (DOOM.gameepisode) { - case 1: - if (DOOM.isCommercial() || DOOM.isRegistered()) - DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("CREDIT", PU_CACHE), this.DOOM.vs, 0, 0); - else - // Fun fact: Registered/Ultimate Doom has no "HELP2" lump. - DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("HELP2", PU_CACHE), this.DOOM.vs, 0, 0); - break; - case 2: - DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("VICTORY2", PU_CACHE), this.DOOM.vs, 0, 0); - break; - case 3: - BunnyScroll(); - break; - case 4: - DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("ENDPIC", PU_CACHE), this.DOOM.vs, 0, 0); - break; - } - } - - } - - public Finale(DoomMain DOOM) { - this.DOOM = DOOM; - hu_font = DOOM.headsUp.getHUFonts(); - - //castinfo_t shit = new castinfo_t(CC_ZOMBIE, mobjtype_t.MT_POSSESSED); - castorder = new castinfo_t[]{ + switch (DOOM.gameepisode) { + case 1: + if (DOOM.isCommercial() || DOOM.isRegistered()) { + DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("CREDIT", PU_CACHE), this.DOOM.vs, 0, 0); + } else // Fun fact: Registered/Ultimate Doom has no "HELP2" lump. + { + DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("HELP2", PU_CACHE), this.DOOM.vs, 0, 0); + } + break; + case 2: + DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("VICTORY2", PU_CACHE), this.DOOM.vs, 0, 0); + break; + case 3: + BunnyScroll(); + break; + case 4: + DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("ENDPIC", PU_CACHE), this.DOOM.vs, 0, 0); + break; + } + } + + } + + public Finale(DoomMain DOOM) { + this.DOOM = DOOM; + hu_font = DOOM.headsUp.getHUFonts(); + + //castinfo_t shit = new castinfo_t(CC_ZOMBIE, mobjtype_t.MT_POSSESSED); + castorder = new castinfo_t[]{ new castinfo_t(CC_ZOMBIE, mobjtype_t.MT_POSSESSED), new castinfo_t(CC_SHOTGUN, mobjtype_t.MT_SHOTGUY), new castinfo_t(CC_HEAVY, mobjtype_t.MT_CHAINGUY), @@ -698,7 +696,7 @@ public Finale(DoomMain DOOM) { new castinfo_t(CC_HERO, mobjtype_t.MT_PLAYER), new castinfo_t(null, null) }; - } + } } -// /$Log \ No newline at end of file +// /$Log diff --git a/src/f/Wiper.java b/src/f/Wiper.java index 2a1a2eb1..f44f18e2 100644 --- a/src/f/Wiper.java +++ b/src/f/Wiper.java @@ -3,31 +3,32 @@ import v.graphics.Wipers; public interface Wiper { + boolean ScreenWipe(Wipers.WipeType type, int x, int y, int width, int height, int ticks); boolean EndScreen(int x, int y, int width, int height); boolean StartScreen(int x, int y, int width, int height); - + public enum Wipe implements Wipers.WipeType { // simple gradual pixel change for 8-bit only // MAES: this transition isn't guaranteed to always terminate // see Chocolate Strife develpment. Unused in Doom anyway. ColorXForm( - Wipers.WipeFunc.initColorXForm, - Wipers.WipeFunc.doColorXForm, - Wipers.WipeFunc.exitColorXForm + Wipers.WipeFunc.initColorXForm, + Wipers.WipeFunc.doColorXForm, + Wipers.WipeFunc.exitColorXForm ), // weird screen melt Melt( - Wipers.WipeFunc.initMelt, - Wipers.WipeFunc.doMelt, - Wipers.WipeFunc.exitMelt + Wipers.WipeFunc.initMelt, + Wipers.WipeFunc.doMelt, + Wipers.WipeFunc.exitMelt ), ScaledMelt( - Wipers.WipeFunc.initScaledMelt, - Wipers.WipeFunc.doScaledMelt, - Wipers.WipeFunc.exitMelt + Wipers.WipeFunc.initScaledMelt, + Wipers.WipeFunc.doScaledMelt, + Wipers.WipeFunc.exitMelt ); private final Wipers.WipeFunc initFunc; @@ -54,5 +55,5 @@ private Wipe(Wipers.WipeFunc initFunc, Wipers.WipeFunc doFunc, Wipers.WipeFunc e this.doFunc = doFunc; this.exitFunc = exitFunc; } - } + } } diff --git a/src/f/anim_t.java b/src/f/anim_t.java index 3e03ff97..e3247536 100644 --- a/src/f/anim_t.java +++ b/src/f/anim_t.java @@ -1,16 +1,15 @@ package f; -import w.animenum_t; import rr.patch_t; +import w.animenum_t; // //Animation. //There is another anim_t used in p_spec. // - public class anim_t { - public anim_t(animenum_t type, int period, int nanims, point_t loc, + public anim_t(animenum_t type, int period, int nanims, point_t loc, int data1, int data2, patch_t[] p, int nexttic, int lastdrawn, int ctr, int state) { this.type = type; @@ -25,62 +24,62 @@ public anim_t(animenum_t type, int period, int nanims, point_t loc, this.ctr = ctr; this.state = state; } - // Partial constructor, only 4 first fields. - public anim_t(animenum_t animAlways, int period, int nanims, point_t loc - ) { - this.type = animAlways; - this.period = period; - this.nanims = nanims; - this.loc = loc; - } - - // Partial constructor, only 5 first fields. - public anim_t(animenum_t type, int period, int nanims, point_t loc, int data1 - ) { - this.type = type; - this.period = period; - this.nanims = nanims; - this.loc = loc; - this.data1=data1; - } - - public animenum_t type; - - // period in tics between animations - public int period; - - // number of animation frames - public int nanims; - - // location of animation - point_t loc; - - // ALWAYS: n/a, - // RANDOM: period deviation (<256), - // LEVEL: level - public int data1; - - // ALWAYS: n/a, - // RANDOM: random base period, - // LEVEL: n/a - public int data2; - - // actual graphics for frames of animations - //Maes: was pointer to array - public patch_t[] p= new patch_t[3]; - - // following must be initialized to zero before use! - - // next value of bcnt (used in conjunction with period) - public int nexttic; - - // last drawn animation frame - public int lastdrawn; - - // next frame number to animate - public int ctr; - - // used by RANDOM and LEVEL when animating - public int state; - - } + // Partial constructor, only 4 first fields. + + public anim_t(animenum_t animAlways, int period, int nanims, point_t loc + ) { + this.type = animAlways; + this.period = period; + this.nanims = nanims; + this.loc = loc; + } + + // Partial constructor, only 5 first fields. + public anim_t(animenum_t type, int period, int nanims, point_t loc, int data1 + ) { + this.type = type; + this.period = period; + this.nanims = nanims; + this.loc = loc; + this.data1 = data1; + } + + public animenum_t type; + + // period in tics between animations + public int period; + + // number of animation frames + public int nanims; + + // location of animation + point_t loc; + + // ALWAYS: n/a, + // RANDOM: period deviation (<256), + // LEVEL: level + public int data1; + + // ALWAYS: n/a, + // RANDOM: random base period, + // LEVEL: n/a + public int data2; + + // actual graphics for frames of animations + //Maes: was pointer to array + public patch_t[] p = new patch_t[3]; + + // following must be initialized to zero before use! + // next value of bcnt (used in conjunction with period) + public int nexttic; + + // last drawn animation frame + public int lastdrawn; + + // next frame number to animate + public int ctr; + + // used by RANDOM and LEVEL when animating + public int state; + +} diff --git a/src/f/castinfo_t.java b/src/f/castinfo_t.java index e28494e7..a7c0d581 100644 --- a/src/f/castinfo_t.java +++ b/src/f/castinfo_t.java @@ -5,18 +5,18 @@ /** * Final DOOM 2 animation Casting by id Software. in order of appearance */ - public class castinfo_t { - String name; - mobjtype_t type; - public castinfo_t() { + String name; + mobjtype_t type; + + public castinfo_t() { - } + } - public castinfo_t(String name, mobjtype_t type) { - this.name = name; - this.type = type; - } + public castinfo_t(String name, mobjtype_t type) { + this.name = name; + this.type = type; + } } diff --git a/src/f/point_t.java b/src/f/point_t.java index 43a95562..53b98eab 100644 --- a/src/f/point_t.java +++ b/src/f/point_t.java @@ -1,11 +1,12 @@ package f; public class point_t { - public point_t(int x, int y) { - this.x=x; - this.y=y; - } - public int x; - public int y; - + + public point_t(int x, int y) { + this.x = x; + this.y = y; } + public int x; + public int y; + +} diff --git a/src/g/DoomGameInterface.java b/src/g/DoomGameInterface.java index bcf92221..783bd5df 100644 --- a/src/g/DoomGameInterface.java +++ b/src/g/DoomGameInterface.java @@ -1,7 +1,6 @@ - package g; -import defines.*; +import defines.skill_t; import doom.event_t; import doom.gameaction_t; @@ -26,58 +25,60 @@ // Duh. // //----------------------------------------------------------------------------- - public interface DoomGameInterface { - // // GAME // -public void DeathMatchSpawnPlayer (int playernum); + public void DeathMatchSpawnPlayer(int playernum); -public void InitNew (skill_t skill, int episode, int map); + public void InitNew(skill_t skill, int episode, int map); -/** Can be called by the startup code or M_Responder. + /** Can be called by the startup code or M_Responder. A normal game starts at map 1, but a warp test can start elsewhere */ -public void DeferedInitNew (skill_t skill, int episode, int map); + public void DeferedInitNew(skill_t skill, int episode, int map); -public void DeferedPlayDemo (String demo); + public void DeferedPlayDemo(String demo); -/** Can be called by the startup code or M_Responder, + /** Can be called by the startup code or M_Responder, calls P_SetupLevel or W_EnterWorld. */ -public void LoadGame (String name); + public void LoadGame(String name); + + public void DoLoadGame(); + + /** Called by M_Responder. */ + public void SaveGame(int slot, String description); + + /** Only called by startup code. */ + public void RecordDemo(String name); + + public void BeginRecording(); + + public void PlayDemo(String name); -public void DoLoadGame (); + public void TimeDemo(String name); -/** Called by M_Responder. */ -public void SaveGame (int slot, String description); + public boolean CheckDemoStatus(); -/** Only called by startup code. */ -public void RecordDemo (String name); + public void ExitLevel(); -public void BeginRecording (); + public void SecretExitLevel(); -public void PlayDemo (String name); -public void TimeDemo (String name); -public boolean CheckDemoStatus (); + public void WorldDone(); -public void ExitLevel (); -public void SecretExitLevel() ; + public void Ticker(); -public void WorldDone() ; + public boolean Responder(event_t ev); -public void Ticker() ; -public boolean Responder (event_t ev); + public void ScreenShot(); -public void ScreenShot() ; + public gameaction_t getGameAction(); -public gameaction_t getGameAction(); + public void setGameAction(gameaction_t ga); -public void setGameAction(gameaction_t ga); + public boolean getPaused(); -public boolean getPaused(); + public void setPaused(boolean on); -public void setPaused(boolean on); - } diff --git a/src/g/DoomSaveGame.java b/src/g/DoomSaveGame.java index 71878d01..0d03eced 100644 --- a/src/g/DoomSaveGame.java +++ b/src/g/DoomSaveGame.java @@ -1,8 +1,10 @@ package g; import static data.Defines.VERSION; -import static data.Limits.*; -import defines.*; +import static data.Limits.MAXPLAYERS; +import static data.Limits.SAVESTRINGSIZE; +import static data.Limits.VERSIONSIZE; +import defines.skill_t; import doom.DoomStatus; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -15,21 +17,18 @@ import w.IReadableDoomObject; import w.IWritableDoomObject; - /** represents the header of Doom savegame, so that basic info can be checked quickly. * * To load the whole game and check if there are final mistakes, you must go through it all. * Savegames need to be aware of ALL status and context, so maybe they should be inner classes? * */ +public class DoomSaveGame implements CacheableDoomObject, IReadableDoomObject, IWritableDoomObject { - -public class DoomSaveGame implements CacheableDoomObject, IReadableDoomObject, IWritableDoomObject{ - - public DoomSaveGame(){ - playeringame=new boolean[MAXPLAYERS]; + public DoomSaveGame() { + playeringame = new boolean[MAXPLAYERS]; } - + public String name; // max size SAVEGAMENAME public String vcheck; // These are for DS @@ -42,97 +41,97 @@ public DoomSaveGame(){ // These help checking shit. public boolean wrongversion; public boolean properend; - @Override public void unpack(ByteBuffer buf) throws IOException { - name=DoomBuffer.getNullTerminatedString(buf, SAVESTRINGSIZE); - vcheck=DoomBuffer.getNullTerminatedString(buf, VERSIONSIZE); - String vcheckb= ("version "+VERSION); + name = DoomBuffer.getNullTerminatedString(buf, SAVESTRINGSIZE); + vcheck = DoomBuffer.getNullTerminatedString(buf, VERSIONSIZE); + String vcheckb = ("version " + VERSION); // no more unpacking, and report it. - if (wrongversion = !(vcheckb.equalsIgnoreCase(vcheck))) return; - gameskill = buf.get(); + if (wrongversion = !(vcheckb.equalsIgnoreCase(vcheck))) { + return; + } + gameskill = buf.get(); gameepisode = buf.get(); gamemap = buf.get(); - - for (int i=0 ; i>>16)); - byte b = (byte) (0x00FF&(leveltime>>>8)); - byte c = (byte) (0x00FF&(leveltime)); + byte a = (byte) (0x0000FF & (leveltime >>> 16)); + byte b = (byte) (0x00FF & (leveltime >>> 8)); + byte c = (byte) (0x00FF & (leveltime)); // Quite anomalous, leveltime is stored as a BIG ENDIAN, 24-bit unsigned integer :-S f.writeByte(a); f.writeByte(b); f.writeByte(c); - + // TODO: after this point, we should probably save some packed buffers representing raw state... // needs further study. - // The end. f.writeByte(0x1d); - - } - + + } + @Override public void read(DataInputStream f) throws IOException { - name=DoomIO.readNullTerminatedString(f,SAVESTRINGSIZE); - vcheck=DoomIO.readNullTerminatedString(f,VERSIONSIZE); - String vcheckb= ("version "+VERSION); + name = DoomIO.readNullTerminatedString(f, SAVESTRINGSIZE); + vcheck = DoomIO.readNullTerminatedString(f, VERSIONSIZE); + String vcheckb = ("version " + VERSION); // no more unpacking, and report it. - if (wrongversion = !(vcheckb.equalsIgnoreCase(vcheck))) return; - gameskill = f.readByte(); + if (wrongversion = !(vcheckb.equalsIgnoreCase(vcheck))) { + return; + } + gameskill = f.readByte(); gameepisode = f.readByte(); gamemap = f.readByte(); - playeringame=new boolean[MAXPLAYERS]; - for (int i=0 ; i DS){ - System.arraycopy(this.playeringame, 0, DS.playeringame, 0, this.playeringame.length); - DS.gameskill=skill_t.values()[this.gameskill]; - DS.gameepisode=this.gameepisode; - DS.gamemap=this.gamemap; - DS.leveltime=this.leveltime; - - } - - public void fromStat(DoomStatus DS){ - System.arraycopy(DS.playeringame, 0, this.playeringame, 0, DS.playeringame.length); - this.gameskill=DS.gameskill.ordinal(); - this.gameepisode=DS.gameepisode; - this.gamemap=DS.gamemap; - this.leveltime=DS.leveltime; - - } + } + + public void toStat(DoomStatus DS) { + System.arraycopy(this.playeringame, 0, DS.playeringame, 0, this.playeringame.length); + DS.gameskill = skill_t.values()[this.gameskill]; + DS.gameepisode = this.gameepisode; + DS.gamemap = this.gamemap; + DS.leveltime = this.leveltime; + + } + + public void fromStat(DoomStatus DS) { + System.arraycopy(DS.playeringame, 0, this.playeringame, 0, DS.playeringame.length); + this.gameskill = DS.gameskill.ordinal(); + this.gameepisode = DS.gameepisode; + this.gamemap = DS.gamemap; + this.leveltime = DS.leveltime; + + } } diff --git a/src/g/Overflow.java b/src/g/Overflow.java index d078f568..160ff87a 100644 --- a/src/g/Overflow.java +++ b/src/g/Overflow.java @@ -36,60 +36,57 @@ * *--------------------------------------------------------------------- */ - public class Overflow { - String[] overflow_cfgname = - { - "overrun_spechit_emulate", - "overrun_reject_emulate", - "overrun_intercept_emulate", - "overrun_playeringame_emulate", - "overrun_donut_emulate", - "overrun_missedbackside_emulate" - }; - - class overrun_param_t{ - boolean warn; - boolean emulate; - boolean tmp_emulate; - int promted; - int shit_happens; + String[] overflow_cfgname + = { + "overrun_spechit_emulate", + "overrun_reject_emulate", + "overrun_intercept_emulate", + "overrun_playeringame_emulate", + "overrun_donut_emulate", + "overrun_missedbackside_emulate" + }; + + class overrun_param_t { + + boolean warn; + boolean emulate; + boolean tmp_emulate; + int promted; + int shit_happens; } - - class intercepts_overrun_t - { + + class intercepts_overrun_t { + int len; long addr; boolean int16_array; - } + } + public static final int OVERFLOW_SPECHIT = 0; + public static final int OVERFLOW_REJECT = 1; + public static final int OVERFLOW_INTERCEPT = 2; + public static final int OVERFLOW_PLYERINGAME = 3; + public static final int OVERFLOW_DONUT = 4; + public static final int OVERFLOW_MISSEDBACKSIDE = 5; + public static final int OVERFLOW_MAX = 6; - public static final int OVERFLOW_SPECHIT=0; - public static final int OVERFLOW_REJECT=1; - public static final int OVERFLOW_INTERCEPT=2; - public static final int OVERFLOW_PLYERINGAME=3; - public static final int OVERFLOW_DONUT=4; - public static final int OVERFLOW_MISSEDBACKSIDE=5; - public static final int OVERFLOW_MAX=6; - - public static final int MAXINTERCEPTS_ORIGINAL=128; + public static final int MAXINTERCEPTS_ORIGINAL = 128; - - public static final boolean EMULATE(int overflow) { return (overflows[overflow].emulate || overflows[overflow].tmp_emulate); } - + public static final boolean PROCESS(int overflow) { return (overflows[overflow].warn || EMULATE(overflow)); } - static overrun_param_t[] overflows=new overrun_param_t[OVERFLOW_MAX]; - + static overrun_param_t[] overflows = new overrun_param_t[OVERFLOW_MAX]; + public static intercepts_overrun_t[] intercepts_overrun; -/* + /* static void ShowOverflowWarning(int overflow, int fatal, String ... params) { overflows[overflow].shit_happens = true; @@ -129,7 +126,6 @@ static void ShowOverflowWarning(int overflow, int fatal, String ... params) va_end(argptr); } } */ - // e6y // // Intercepts Overrun emulation @@ -139,9 +135,7 @@ static void ShowOverflowWarning(int overflow, int fatal, String ... params) // Thanks to Simon Howard (fraggle) for refactor the intercepts // overrun code so that it should work properly on big endian machines // as well as little endian machines. - // Overwrite a specific memory location with a value. - /* static void InterceptsMemoryOverrun(int location, int value) { @@ -185,9 +179,9 @@ static void InterceptsMemoryOverrun(int location, int value) ++i; } } -*/ + */ - /* + /* void InterceptsOverrun(int num_intercepts, intercept_t intercept) { if (num_intercepts > MAXINTERCEPTS_ORIGINAL && demo_compatibility && PROCESS(OVERFLOW_INTERCEPT)) @@ -211,7 +205,7 @@ void InterceptsOverrun(int num_intercepts, intercept_t intercept) } } } -*/ + */ // e6y // playeringame overrun emulation // it detects and emulates overflows on vex6d.wad\bug_wald(toke).lmp, etc. @@ -230,28 +224,26 @@ void InterceptsOverrun(int num_intercepts, intercept_t intercept) } return false; }*/ + // + // spechit overrun emulation + // + // Spechit overrun magic value. + public static final int DEFAULT_SPECHIT_MAGIC = 0x01C09C98; - // - // spechit overrun emulation - // - - // Spechit overrun magic value. - public static final int DEFAULT_SPECHIT_MAGIC =0x01C09C98; + class spechit_overrun_param_t { - class spechit_overrun_param_t - { - line_t line; + line_t line; - line_t[] spechit; - int numspechit; + line_t[] spechit; + int numspechit; - int[] tmbbox; - int[] tmfloorz; - int[] tmceilingz; + int[] tmbbox; + int[] tmfloorz; + int[] tmceilingz; - boolean crushchange; - boolean nofit; - } + boolean crushchange; + boolean nofit; + } long spechit_baseaddr = 0; @@ -262,7 +254,6 @@ class spechit_overrun_param_t // http://www.doomworld.com/vb/showthread.php?s=&threadid=35214 // See more information on: // doomworld.com/vb/doom-speed-demos/35214-spechits-reject-and-intercepts-overflow-lists - /* static void SpechitOverrun(spechit_overrun_param_t params) { @@ -365,12 +356,10 @@ static void SpechitOverrun(spechit_overrun_param_t params) } } } - */ - + */ // // reject overrun emulation // - // padding the reject table if it is too short // totallines must be the number returned by P_GroupLines() // an underflow will be padded with zeroes, or a doom.exe z_zone header @@ -444,11 +433,9 @@ static void SpechitOverrun(spechit_overrun_param_t params) lprintf(LO_WARN, "P_LoadReject: REJECT too short (%u<%u) - padded\n", length, required); } }*/ - // // Read Access Violation emulation. // - // C:\>debug // -d 0:0 // @@ -585,5 +572,4 @@ int MissedBackSideOverrun(sector_t *sector, seg_t *seg) return false; }*/ - } diff --git a/src/g/Signals.java b/src/g/Signals.java index 62b315c4..f5a8fb1f 100644 --- a/src/g/Signals.java +++ b/src/g/Signals.java @@ -14,26 +14,21 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package g; // - import doom.event_t; import doom.evtype_t; -import static java.awt.event.InputEvent.ALT_DOWN_MASK; -import static java.awt.event.InputEvent.CTRL_DOWN_MASK; -import static java.awt.event.InputEvent.META_DOWN_MASK; -import static java.awt.event.InputEvent.SHIFT_DOWN_MASK; import java.awt.event.KeyEvent; import static java.awt.event.KeyEvent.*; public class Signals { + // 65535 + 4 bytes in memory, acceptable for speed purpose private final static byte[] map = new byte[Character.MAX_VALUE]; // plus 260 bytes in this private final static byte[] siblings = new byte[Byte.MAX_VALUE << 1]; - + public static ScanCode getScanCode(KeyEvent e) { final ScanCode ret = ScanCode.v[map[e.getKeyCode()] & 0xFF]; @@ -46,17 +41,19 @@ public static ScanCode getScanCode(KeyEvent e) { if (sib.location == e.getKeyLocation()) { return sib; } - + return ScanCode.SC_NULL; } - private Signals() {} - + private Signals() { + } + @FunctionalInterface public interface SignalListener { + void sendEvent(ScanCode sc, int eventType); } - + /** * Maps scan codes for whatever crap we use. They should be system dependent, but * it seems I've invented a "keyboard" instead of passing it to real one. @@ -204,15 +201,15 @@ public enum ScanCode { /** Custom ScanCodes - no keyboard or platform standard **/ /* 140 */ SC_LMETA(VK_META, KEY_LOCATION_LEFT, META_DOWN_MASK), /* 141 */ SC_RMETA(VK_META, KEY_LOCATION_RIGHT, META_DOWN_MASK); - + public final char c; public final event_t doomEventUp; public final event_t doomEventDown; - + private final int location; private final char virtualKey; private final static ScanCode[] v = values(); - + ScanCode() { this.doomEventUp = this.doomEventDown = event_t.EMPTY_EVENT; this.location = this.c = this.virtualKey = 0; @@ -230,4 +227,4 @@ public enum ScanCode { map[virtualKey] = (byte) ordinal(); } } -} \ No newline at end of file +} diff --git a/src/hu/HU.java b/src/hu/HU.java index df834716..fc09e5b3 100644 --- a/src/hu/HU.java +++ b/src/hu/HU.java @@ -20,16 +20,31 @@ // DESCRIPTION: Heads-up displays // // ----------------------------------------------------------------------------- - -import static data.Defines.*; -import static data.Limits.*; +import static data.Defines.HU_BROADCAST; +import static data.Defines.HU_FONTSIZE; +import static data.Defines.HU_FONTSTART; +import static data.Defines.HU_MAXLINELENGTH; +import static data.Defines.HU_MAXLINES; +import static data.Defines.HU_MSGHEIGHT; +import static data.Defines.HU_MSGREFRESH; +import static data.Defines.HU_MSGTIMEOUT; +import static data.Defines.HU_MSGX; +import static data.Defines.HU_MSGY; +import static data.Defines.PU_STATIC; +import static data.Limits.MAXPLAYERS; import data.sounds.sfxenum_t; -import defines.*; +import defines.GameMode; +import defines.Language_t; import doom.DoomMain; import doom.SourceCode; import doom.SourceCode.CauseOfDesyncProbability; import doom.SourceCode.HU_Lib; -import static doom.SourceCode.HU_Lib.*; +import static doom.SourceCode.HU_Lib.HUlib_addCharToTextLine; +import static doom.SourceCode.HU_Lib.HUlib_clearTextLine; +import static doom.SourceCode.HU_Lib.HUlib_delCharFromIText; +import static doom.SourceCode.HU_Lib.HUlib_delCharFromTextLine; +import static doom.SourceCode.HU_Lib.HUlib_keyInIText; +import static doom.SourceCode.HU_Lib.HUlib_resetIText; import doom.SourceCode.HU_Stuff; import static doom.SourceCode.HU_Stuff.HU_Responder; import static doom.SourceCode.HU_Stuff.HU_queueChatChar; @@ -43,17 +58,17 @@ import rr.ViewVars; import rr.patch_t; import utils.C2JUtils; -import static v.renderers.DoomScreen.*; - +import static v.renderers.DoomScreen.BG; +import static v.renderers.DoomScreen.FG; + +public class HU implements IHeadsUp { -public class HU implements IHeadsUp{ // MAES: Status and wad data. final DoomMain DOOM; // // Locally used constants, shortcuts. // MAES: Some depend on STATE, so moved into constructor. - String HU_TITLE, HU_TITLE2, HU_TITLEP, HU_TITLET; protected final static int HU_TITLEHEIGHT = 1; @@ -69,25 +84,24 @@ public class HU implements IHeadsUp{ protected int HU_INPUTY;// = (HU_MSGY + // HU_MSGHEIGHT*(Swap.SHORT(hu_font[0].height) +1)); - protected final static int HU_INPUTWIDTH = 64; protected final static int HU_INPUTHEIGHT = 1; - public String[] chat_macros = - { HUSTR_CHATMACRO0, HUSTR_CHATMACRO1, HUSTR_CHATMACRO2, + public String[] chat_macros + = {HUSTR_CHATMACRO0, HUSTR_CHATMACRO1, HUSTR_CHATMACRO2, HUSTR_CHATMACRO3, HUSTR_CHATMACRO4, HUSTR_CHATMACRO5, HUSTR_CHATMACRO6, HUSTR_CHATMACRO7, HUSTR_CHATMACRO8, - HUSTR_CHATMACRO9 }; - + HUSTR_CHATMACRO9}; + @Override - public void setChatMacro(int i, String s){ - this.chat_macros[i]=s; + public void setChatMacro(int i, String s) { + this.chat_macros[i] = s; } /** Needs to be seen by DoomGame */ - public final static String[] player_names = - { HUSTR_PLRGREEN, HUSTR_PLRINDIGO, HUSTR_PLRBROWN, HUSTR_PLRRED }; + public final static String[] player_names + = {HUSTR_PLRGREEN, HUSTR_PLRINDIGO, HUSTR_PLRBROWN, HUSTR_PLRRED}; char chat_char; // remove later. @@ -100,14 +114,13 @@ public void setChatMacro(int i, String s){ char[] chat_dest = new char[MAXPLAYERS]; // MAES: these used to be defined in hu_lib. We're going 100% OO here... - hu_itext_t[] w_inputbuffer; - hu_textline_t w_title ; + hu_textline_t w_title; hu_itext_t w_chat; - boolean[] always_off = { false }; + boolean[] always_off = {false}; // Needs to be referenced by one of the widgets. public boolean[] chat_on = new boolean[1]; @@ -127,70 +140,61 @@ public void setChatMacro(int i, String s){ // need to share Menu context. // int showMessages; // MAES: I think this is supposed to be visible by the various hu_ crap... - // boolean automapactive; - + // boolean automapactive; boolean headsupactive = false; // // Builtin map names. // The actual names can be found in DStrings.h. // - - protected String[] mapnames = // DOOM shareware/registered/retail (Ultimate) - // names. - { - - HUSTR_E1M1, HUSTR_E1M2, HUSTR_E1M3, HUSTR_E1M4, HUSTR_E1M5, HUSTR_E1M6, + protected String[] mapnames + = // DOOM shareware/registered/retail (Ultimate) + // names. + { + HUSTR_E1M1, HUSTR_E1M2, HUSTR_E1M3, HUSTR_E1M4, HUSTR_E1M5, HUSTR_E1M6, HUSTR_E1M7, HUSTR_E1M8, HUSTR_E1M9, - HUSTR_E2M1, HUSTR_E2M2, HUSTR_E2M3, HUSTR_E2M4, HUSTR_E2M5, HUSTR_E2M6, HUSTR_E2M7, HUSTR_E2M8, HUSTR_E2M9, - HUSTR_E3M1, HUSTR_E3M2, HUSTR_E3M3, HUSTR_E3M4, HUSTR_E3M5, HUSTR_E3M6, HUSTR_E3M7, HUSTR_E3M8, HUSTR_E3M9, - HUSTR_E4M1, HUSTR_E4M2, HUSTR_E4M3, HUSTR_E4M4, HUSTR_E4M5, HUSTR_E4M6, HUSTR_E4M7, HUSTR_E4M8, HUSTR_E4M9, - "NEWLEVEL", "NEWLEVEL", "NEWLEVEL", "NEWLEVEL", "NEWLEVEL", - "NEWLEVEL", "NEWLEVEL", "NEWLEVEL", "NEWLEVEL" }; + "NEWLEVEL", "NEWLEVEL", "NEWLEVEL", "NEWLEVEL"}; - protected String[] mapnames2 = // DOOM 2 map names. - { HUSTR_1, HUSTR_2, HUSTR_3, HUSTR_4, HUSTR_5, HUSTR_6, HUSTR_7, + protected String[] mapnames2 + = // DOOM 2 map names. + {HUSTR_1, HUSTR_2, HUSTR_3, HUSTR_4, HUSTR_5, HUSTR_6, HUSTR_7, HUSTR_8, HUSTR_9, HUSTR_10, HUSTR_11, - HUSTR_12, HUSTR_13, HUSTR_14, HUSTR_15, HUSTR_16, HUSTR_17, HUSTR_18, HUSTR_19, HUSTR_20, - HUSTR_21, HUSTR_22, HUSTR_23, HUSTR_24, HUSTR_25, HUSTR_26, - HUSTR_27, HUSTR_28, HUSTR_29, HUSTR_30, HUSTR_31, HUSTR_32,HUSTR_33 }; + HUSTR_27, HUSTR_28, HUSTR_29, HUSTR_30, HUSTR_31, HUSTR_32, HUSTR_33}; - protected String[] mapnamesp = // Plutonia WAD map names. - { PHUSTR_1, PHUSTR_2, PHUSTR_3, PHUSTR_4, PHUSTR_5, PHUSTR_6, PHUSTR_7, + protected String[] mapnamesp + = // Plutonia WAD map names. + {PHUSTR_1, PHUSTR_2, PHUSTR_3, PHUSTR_4, PHUSTR_5, PHUSTR_6, PHUSTR_7, PHUSTR_8, PHUSTR_9, PHUSTR_10, PHUSTR_11, - PHUSTR_12, PHUSTR_13, PHUSTR_14, PHUSTR_15, PHUSTR_16, PHUSTR_17, PHUSTR_18, PHUSTR_19, PHUSTR_20, - PHUSTR_21, PHUSTR_22, PHUSTR_23, PHUSTR_24, PHUSTR_25, PHUSTR_26, PHUSTR_27, PHUSTR_28, PHUSTR_29, PHUSTR_30, - PHUSTR_31, PHUSTR_32 }; + PHUSTR_31, PHUSTR_32}; - protected String[] mapnamest = // TNT WAD map names. - { THUSTR_1, THUSTR_2, THUSTR_3, THUSTR_4, THUSTR_5, THUSTR_6, THUSTR_7, + protected String[] mapnamest + = // TNT WAD map names. + {THUSTR_1, THUSTR_2, THUSTR_3, THUSTR_4, THUSTR_5, THUSTR_6, THUSTR_7, THUSTR_8, THUSTR_9, THUSTR_10, THUSTR_11, - THUSTR_12, THUSTR_13, THUSTR_14, THUSTR_15, THUSTR_16, THUSTR_17, THUSTR_18, THUSTR_19, THUSTR_20, - THUSTR_21, THUSTR_22, THUSTR_23, THUSTR_24, THUSTR_25, THUSTR_26, THUSTR_27, THUSTR_28, THUSTR_29, THUSTR_30, - THUSTR_31, THUSTR_32 }; + THUSTR_31, THUSTR_32}; char[] shiftxform; - public static final char[] french_shiftxform = - { + public static final char[] french_shiftxform + = { 0, 1, 2, @@ -269,10 +273,10 @@ public void setChatMacro(int i, String s){ 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', 127 - }; + }; - public static final char[] english_shiftxform = - { + public static final char[] english_shiftxform + = { 0, 1, 2, @@ -349,11 +353,11 @@ public void setChatMacro(int i, String s){ '\'', // shift-` 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', - 'Y', 'Z', '{', '|', '}', '~', 127 }; + 'Y', 'Z', '{', '|', '}', '~', 127}; // Maes: char? - char[] frenchKeyMap = - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + char[] frenchKeyMap + = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, ' ', '!', '"', '#', '$', '%', '&', '%', '(', ')', '*', '+', ';', '-', ':', '!', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', @@ -362,7 +366,7 @@ public void setChatMacro(int i, String s){ 'S', 'T', 'U', 'V', 'Z', 'X', 'Y', 'W', '^', '\\', '$', '^', '_', '@', 'Q', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', ',', 'N', 'O', 'P', 'A', 'R', 'S', 'T', 'U', 'V', - 'Z', 'X', 'Y', 'W', '^', '\\', '$', '^', 127 }; + 'Z', 'X', 'Y', 'W', '^', '\\', '$', '^', 127}; protected final char ForeignTranslation(char ch) { return ch < 128 ? frenchKeyMap[ch] : ch; @@ -386,7 +390,6 @@ public HU(final DoomMain DOOM) { * * @throws Exception */ - @Override public void Init() { if (DOOM.language == Language_t.french) { @@ -415,7 +418,7 @@ public void Init() { HU_INPUTY = (HU_MSGY + HU_MSGHEIGHT * hu_font[0].height + 1); } - + @Override public void Stop() { headsupactive = false; @@ -427,19 +430,18 @@ public void Start() { int i; String s; - + // MAES: fugly hax. These were compile-time inlines, // so they can either work as functions, or be set whenever the HU is started // (typically once per level). They need to be aware of game progress, // and episode numbers <1 will cause it to bomb. // MAES: hack to handle Betray in XBLA 31/5/2011 - if ((DOOM.gamemap>32) && (DOOM.getGameMode()==GameMode.pack_xbla)){ - this.HU_TITLE = mapnames[(DOOM.gameepisode - 1) * 9 + DOOM.gamemap - 2]; + if ((DOOM.gamemap > 32) && (DOOM.getGameMode() == GameMode.pack_xbla)) { + this.HU_TITLE = mapnames[(DOOM.gameepisode - 1) * 9 + DOOM.gamemap - 2]; - - this.HU_TITLE2 = mapnames2[DOOM.gamemap - 1]; - this.HU_TITLEP = mapnamesp[DOOM.gamemap - 2]; // fixed from HU_TITLEPw - this.HU_TITLET = mapnamest[DOOM.gamemap - 2]; + this.HU_TITLE2 = mapnames2[DOOM.gamemap - 1]; + this.HU_TITLEP = mapnamesp[DOOM.gamemap - 2]; // fixed from HU_TITLEPw + this.HU_TITLET = mapnamest[DOOM.gamemap - 2]; } else { this.HU_TITLE = mapnames[(DOOM.gameepisode - 1) * 9 + DOOM.gamemap - 1]; this.HU_TITLE2 = mapnames2[DOOM.gamemap - 1]; @@ -447,8 +449,9 @@ public void Start() { this.HU_TITLET = mapnamest[DOOM.gamemap - 1]; } - if (headsupactive) + if (headsupactive) { this.Stop(); + } plr = DOOM.players[DOOM.consoleplayer]; message_on[0] = false; @@ -458,7 +461,7 @@ public void Start() { // create the message widget this.w_message.initSText(HU_MSGX, HU_MSGY, HU_MSGHEIGHT, hu_font, - HU_FONTSTART, this.message_on); + HU_FONTSTART, this.message_on); // create the map title widget this.w_title.initTextLine(HU_TITLEX, HU_TITLEY, hu_font, HU_FONTSTART); @@ -488,15 +491,14 @@ public void Start() { // MAES: oh great, more pointer-char magic... oh no you don't, you ugly // cow horse and reindeer lover. - // while (*s) this.w_title.addCharToTextLine(*(s++)); - int ptr=0; - while(ptr= 'a' && c <= 'z') + } else { + if (c >= 'a' && c <= 'z') { c = (char) shiftxform[c]; + } rc = w_inputbuffer[i].keyInIText(c); if (rc && c == ScanCode.SC_ENTER.c) { if ((w_inputbuffer[i].l.len != 0) @@ -572,12 +577,12 @@ public void Ticker() { message_nottobefuckedwith = true; message_on[0] = true; message_counter = HU_MSGTIMEOUT; - if (DOOM.isCommercial()) + if (DOOM.isCommercial()) { DOOM.doomSound.StartSound(null, sfxenum_t.sfx_radio); - - else + } else { DOOM.doomSound.StartSound(null, sfxenum_t.sfx_tink); - + } + } w_inputbuffer[i].resetIText(); } @@ -631,7 +636,7 @@ public char dequeueChatChar() { protected boolean altdown = false; - protected char[] destination_keys = { HUSTR_KEYGREEN, HUSTR_KEYINDIGO, HUSTR_KEYBROWN, HUSTR_KEYRED }; + protected char[] destination_keys = {HUSTR_KEYGREEN, HUSTR_KEYINDIGO, HUSTR_KEYBROWN, HUSTR_KEYRED}; protected int num_nobrainers = 0; @@ -640,7 +645,7 @@ public char dequeueChatChar() { @HU_Stuff.C(HU_Responder) public boolean Responder(event_t ev) { - //System.out.println("Player "+DM.players[0].mo.x); + //System.out.println("Player "+DM.players[0].mo.x); int numplayers = 0; // MAES: Adding BOOLEANS to ints, are we ?! for (int i = 0; i < MAXPLAYERS; i++) { @@ -655,8 +660,9 @@ public boolean Responder(event_t ev) { return false; } - if (!ev.isType(evtype_t.ev_keydown)) + if (!ev.isType(evtype_t.ev_keydown)) { return false; + } final boolean eatkey; if (!chat_on[0]) { @@ -666,10 +672,12 @@ public boolean Responder(event_t ev) { eatkey = true; } else if (DOOM.netgame && ev.isKey(HU_INPUTTOGGLE)) { eatkey = chat_on[0] = true; - HUlib_resetIText: { + HUlib_resetIText: + { w_chat.resetIText(); } - HU_queueChatChar: { + HU_queueChatChar: + { this.queueChatChar(HU_BROADCAST); } } else if (DOOM.netgame && numplayers > 2) { @@ -679,112 +687,122 @@ public boolean Responder(event_t ev) { if (sc.c == destination_keys[i]) { if (DOOM.playeringame[i] && i != DOOM.consoleplayer) { r = chat_on[0] = true; - HUlib_resetIText: { + HUlib_resetIText: + { w_chat.resetIText(); } - HU_queueChatChar: { + HU_queueChatChar: + { this.queueChatChar((char) (i + 1)); } break; } else if (i == DOOM.consoleplayer) { num_nobrainers++; - if (num_nobrainers < 3) + if (num_nobrainers < 3) { plr.message = HUSTR_TALKTOSELF1; - else if (num_nobrainers < 6) + } else if (num_nobrainers < 6) { plr.message = HUSTR_TALKTOSELF2; - else if (num_nobrainers < 9) + } else if (num_nobrainers < 9) { plr.message = HUSTR_TALKTOSELF3; - else if (num_nobrainers < 32) + } else if (num_nobrainers < 32) { plr.message = HUSTR_TALKTOSELF4; - else + } else { plr.message = HUSTR_TALKTOSELF5; + } } } } return r; }); - } else eatkey = false; - } else eatkey = ev.ifKey(sc -> { - final boolean ret; - char c = sc.c; - // send a macro - if (altdown) { - c = (char) (c - '0'); - if (c > 9) - return false; - - // fprintf(stderr, "got here\n"); - char[] macromessage = chat_macros[c].toCharArray(); - - // kill last message with a '\n' - HU_queueChatChar: { - this.queueChatChar(ScanCode.SC_ENTER.c); - } // DEBUG!!! - - // send the macro message - int index = 0; - while (macromessage[index] != 0) { - HU_queueChatChar: { - this.queueChatChar(macromessage[index]); + } else { + eatkey = false; + } + } else { + eatkey = ev.ifKey(sc -> { + final boolean ret; + char c = sc.c; + // send a macro + if (altdown) { + c = (char) (c - '0'); + if (c > 9) { + return false; } - } - HU_queueChatChar: { - this.queueChatChar(ScanCode.SC_ENTER.c); - } - // leave chat mode and notify that it was sent - chat_on[0] = false; - lastmessage.setLength(0); - lastmessage.append(chat_macros[c]); - plr.message = lastmessage.toString(); - ret = true; - } else { - if (DOOM.language == Language_t.french) { - c = ForeignTranslation(c); - } - if (shiftdown || (c >= 'a' && c <= 'z')) { - c = shiftxform[c]; - } - HUlib_keyInIText: { - ret = w_chat.keyInIText(c); - } - if (ret) { - // static unsigned char buf[20]; // DEBUG - HU_queueChatChar: { - this.queueChatChar(c); + // fprintf(stderr, "got here\n"); + char[] macromessage = chat_macros[c].toCharArray(); + + // kill last message with a '\n' + HU_queueChatChar: + { + this.queueChatChar(ScanCode.SC_ENTER.c); + } // DEBUG!!! + + // send the macro message + int index = 0; + while (macromessage[index] != 0) { + HU_queueChatChar: + { + this.queueChatChar(macromessage[index]); + } + } + HU_queueChatChar: + { + this.queueChatChar(ScanCode.SC_ENTER.c); } - // sprintf(buf, "KEY: %d => %d", ev->data1, c); - // plr->message = buf; - } - if (c == ScanCode.SC_ENTER.c) { + // leave chat mode and notify that it was sent chat_on[0] = false; - if ((w_chat.l.len != 0)) { - lastmessage.setLength(0); - lastmessage.append( w_chat.l.text); - plr.message = new String(lastmessage); + lastmessage.setLength(0); + lastmessage.append(chat_macros[c]); + plr.message = lastmessage.toString(); + ret = true; + } else { + if (DOOM.language == Language_t.french) { + c = ForeignTranslation(c); + } + if (shiftdown || (c >= 'a' && c <= 'z')) { + c = shiftxform[c]; + } + HUlib_keyInIText: + { + ret = w_chat.keyInIText(c); + } + if (ret) { + // static unsigned char buf[20]; // DEBUG + HU_queueChatChar: + { + this.queueChatChar(c); + } + + // sprintf(buf, "KEY: %d => %d", ev->data1, c); + // plr->message = buf; + } + if (c == ScanCode.SC_ENTER.c) { + chat_on[0] = false; + if ((w_chat.l.len != 0)) { + lastmessage.setLength(0); + lastmessage.append(w_chat.l.text); + plr.message = new String(lastmessage); + } + } else if (c == ScanCode.SC_ESCAPE.c) { + chat_on[0] = false; } - } else if (c == ScanCode.SC_ESCAPE.c) { - chat_on[0] = false; } - } - return ret; - }); + return ret; + }); + } return eatkey; } // ///////////////////////////////// STRUCTS // /////////////////////////////////// - /** * Input Text Line widget * (child of Text Line widget) */ - class hu_itext_t { - hu_textline_t l; // text line to input on // left margin past which I am not to delete characters @@ -795,10 +813,10 @@ class hu_itext_t { boolean laston; // last value of *->on; - public hu_itext_t(){ - + public hu_itext_t() { + } - + public void initIText(int x, int y, patch_t[] font, int startchar, boolean[] on) { this.lm = 0; // default left margin is start of text @@ -812,15 +830,17 @@ public void initIText(int x, int y, patch_t[] font, int startchar, @HU_Lib.C(HUlib_delCharFromIText) public void delCharFromIText() { if (this.l.len != this.lm) { - HUlib_delCharFromTextLine: { + HUlib_delCharFromTextLine: + { this.l.delCharFromTextLine(); } } } public void eraseLineFromIText() { - while (this.lm != this.l.len) + while (this.lm != this.l.len) { l.delCharFromTextLine(); + } } // Resets left margin as well @@ -855,11 +875,13 @@ public void addPrefixToIText(String str) { public boolean keyInIText(char ch) { if (ch >= ' ' && ch <= '_') { - HUlib_addCharToTextLine: { + HUlib_addCharToTextLine: + { this.l.addCharToTextLine(ch); } } else if (ch == ScanCode.SC_BACKSPACE.c) { - HUlib_delCharFromIText: { + HUlib_delCharFromIText: + { this.delCharFromIText(); } } else if (ch != ScanCode.SC_ENTER.c) { @@ -871,15 +893,17 @@ public boolean keyInIText(char ch) { public void drawIText() { - if (!this.on[0]) + if (!this.on[0]) { return; + } this.l.drawTextLine(true); // draw the line w/ cursor } void eraseIText() { - if (this.laston && !this.on[0]) + if (this.laston && !this.on[0]) { this.l.needsupdate = 4; + } this.l.eraseTextLine(); this.laston = this.on[0]; } @@ -888,8 +912,7 @@ void eraseIText() { /** Scrolling Text window widget * (child of Text Line widget) - */ - + */ class hu_stext_t { hu_textline_t[] lines = new hu_textline_t[HU_MAXLINES]; // text lines to draw @@ -903,10 +926,10 @@ class hu_stext_t { boolean laston; // last value of *->on. - public hu_stext_t(){ - + public hu_stext_t() { + } - + public hu_stext_t(int x, int y, int h, patch_t[] font, int startchar, boolean[] on) { this.initSText(x, y, h, font, startchar, on); @@ -915,29 +938,32 @@ public hu_stext_t(int x, int y, int h, patch_t[] font, int startchar, public void initSText(int x, int y, int h, patch_t[] font, int startchar, boolean[] on) { - for (int i=0;i 0)) { - - while ((ptr < prefix.length) && (prefix[ptr] > 0)) + + while ((ptr < prefix.length) && (prefix[ptr] > 0)) { this.lines[this.currline].addCharToTextLine(prefix[ptr++]); } - - ptr = 0; - while ((ptr < msg.length) && (msg[ptr] > 0)) - this.lines[this.currline].addCharToTextLine(msg[ptr++]); } + ptr = 0; + while ((ptr < msg.length) && (msg[ptr] > 0)) { + this.lines[this.currline].addCharToTextLine(msg[ptr++]); + } + } + public void addMessageToSText(String prefix, String msg) { this.addLineToSText(); if ((prefix != null) && (prefix.length() > 0)) { - for (int i = 0; i < prefix.length(); i++) + for (int i = 0; i < prefix.length(); i++) { this.lines[this.currline].addCharToTextLine(prefix.charAt(i)); + } + } + for (int i = 0; i < msg.length(); i++) { + this.lines[this.currline].addCharToTextLine(msg.charAt(i)); } - for (int i = 0; i < msg.length(); i++) - this.lines[this.currline].addCharToTextLine(msg.charAt(i)); } public void drawSText() { int i, idx; hu_textline_t l; - if (!this.on[0]) + if (!this.on[0]) { return; // if not on, don't draw + } - - // draw everything - for (i = 0; i < this.height; i++) { + for (i = 0; i < this.height; i++) { idx = this.currline - i; - if (idx < 0) + if (idx < 0) { idx += this.height; // handle queue of lines - + } l = this.lines[idx]; // need a decision made here on whether to skip the draw @@ -990,8 +1019,9 @@ public void drawSText() { public void eraseSText() { for (int i = 0; i < this.height; i++) { - if (laston && !on[0]) + if (laston && !on[0]) { lines[i].needsupdate = 4; + } this.lines[i].eraseTextLine(); } laston = on[0]; @@ -1018,7 +1048,6 @@ public void setAutomapactive(boolean automapactive) { /** * Same here. */ - // TODO: boolean : whether the screen is always erased protected boolean noterased; // =viewwindowx; @@ -1029,10 +1058,10 @@ public boolean isNoterased() { public void setNoterased(boolean noterased) { this.noterased = noterased; } - - StringBuilder sb=new StringBuilder(); - - public String toString(){ + + StringBuilder sb = new StringBuilder(); + + public String toString() { sb.setLength(0); sb.append(this.lines[0].text); sb.append(this.lines[1].text); @@ -1045,7 +1074,6 @@ public String toString(){ // Text Line widget // (parent of Scrolling Text and Input Text widgets) - class hu_textline_t { // left-justified position of scrolling text window @@ -1058,28 +1086,27 @@ class hu_textline_t { int sc; // start character - char[] text = new char[HU_MAXLINELENGTH+1]; // line of text + char[] text = new char[HU_MAXLINELENGTH + 1]; // line of text int len; // current line length // whether this line needs to be udpated int needsupdate; - public hu_textline_t(){ - + public hu_textline_t() { + } - + @SourceCode.Compatible @HU_Lib.C(HUlib_clearTextLine) public void clearTextLine() { this.len = 0; - C2JUtils.memset(this.text, (char)0,this.text.length); + C2JUtils.memset(this.text, (char) 0, this.text.length); // It's actually used as a status, go figure. this.needsupdate = 1; } // Maes: this could as well be the contructor - public void initTextLine(int x, int y, patch_t[] f, int sc) { this.x = x; this.y = y; @@ -1100,11 +1127,11 @@ public hu_textline_t(int x, int y, patch_t[] f, int sc) { @HU_Lib.C(HUlib_addCharToTextLine) public boolean addCharToTextLine(char ch) { - if (len == HU_MAXLINELENGTH) + if (len == HU_MAXLINELENGTH) { return false; - else { - this.text[len++]=ch; - this.text[len]=(char)0; + } else { + this.text[len++] = ch; + this.text[len] = (char) 0; // this.l[this.len] = 0; // MAES: for some reason this is set as "4", so this is a status // rather than a boolean. @@ -1121,7 +1148,7 @@ public boolean addCharToTextLine(char ch) { * @param s * @return */ -/* + /* public boolean addStringToTextLine(String s) { int index = 0; if (this.len == HU_MAXLINELENGTH) @@ -1140,15 +1167,14 @@ public boolean addStringToTextLine(String s) { this.needsupdate = 4; return true; } */ - @SourceCode.Exact @HU_Lib.C(HUlib_delCharFromTextLine) boolean delCharFromTextLine() { - if (this.len == 0) + if (this.len == 0) { return false; - else { - this.text[--len]= (char)0; + } else { + this.text[--len] = (char) 0; this.needsupdate = 4; return true; } @@ -1169,16 +1195,18 @@ void drawTextLine(boolean drawcursor) { if (c != ' ' && c >= this.sc && c <= '_') { // MAES: fixed a FUCKING STUPID bug caused by SWAP.SHORT w = this.f[c - this.sc].width; - if (x + w > DOOM.vs.getScreenWidth()) + if (x + w > DOOM.vs.getScreenWidth()) { break; - + } + DOOM.graphicSystem.DrawPatchScaled(FG, f[c - sc], DOOM.vs, x, y); x += w; } else { // Leave a space x += 4; - if (x >= DOOM.vs.getScreenWidth()) + if (x >= DOOM.vs.getScreenWidth()) { break; + } } } @@ -1205,15 +1233,14 @@ void drawTextLine(boolean drawcursor) { public void eraseTextLine() { if (!DOOM.automapactive && DOOM.sceneRenderer.getView().windowx != 0 && this.needsupdate > 0) { final ViewVars active = DOOM.sceneRenderer.getView(); - final int - // active part of the screen - activeEndX = active.x + active.width, - activeEndY = active.y + active.height, - // scaled text ranges - dupY = DOOM.graphicSystem.getScalingY(), - lineY = y * dupY, - lineHeight = (this.f[0].height + 1) * dupY, - lineEndY = lineY + lineHeight; + final int // active part of the screen + activeEndX = active.x + active.width, + activeEndY = active.y + active.height, + // scaled text ranges + dupY = DOOM.graphicSystem.getScalingY(), + lineY = y * dupY, + lineHeight = (this.f[0].height + 1) * dupY, + lineEndY = lineY + lineHeight; final Rectangle rect = new Rectangle(0, lineY, DOOM.vs.getScreenWidth(), lineHeight); @@ -1256,15 +1283,16 @@ public void eraseTextLine() { DOOM.graphicSystem.CopyRect(BG, rect, FG); } } - + lastautomapactive = DOOM.automapactive; - if (this.needsupdate != 0) + if (this.needsupdate != 0) { this.needsupdate--; + } } } @Override - public patch_t[] getHUFonts() { + public patch_t[] getHUFonts() { return this.hu_font; } } @@ -1310,4 +1338,4 @@ public patch_t[] getHUFonts() { //FINALLY fixed a stupid bug that broke HU messages. // //Revision 1.21 2011/05/18 16:52:40 velktron -//Changed to DoomStatus \ No newline at end of file +//Changed to DoomStatus diff --git a/src/hu/IHeadsUp.java b/src/hu/IHeadsUp.java index 449a03e0..458d2711 100644 --- a/src/hu/IHeadsUp.java +++ b/src/hu/IHeadsUp.java @@ -7,25 +7,25 @@ public interface IHeadsUp { - void Ticker(); + void Ticker(); - void Erase(); + void Erase(); - void Drawer(); + void Drawer(); @HU_Stuff.C(HU_Responder) - boolean Responder(event_t ev); + boolean Responder(event_t ev); - patch_t[] getHUFonts(); + patch_t[] getHUFonts(); - char dequeueChatChar(); + char dequeueChatChar(); - void Init(); + void Init(); - void setChatMacro(int i, String s); + void setChatMacro(int i, String s); - void Start(); + void Start(); - void Stop(); + void Stop(); } diff --git a/src/i/DiskDrawer.java b/src/i/DiskDrawer.java index 44ff98c0..bc468f26 100644 --- a/src/i/DiskDrawer.java +++ b/src/i/DiskDrawer.java @@ -6,47 +6,49 @@ public class DiskDrawer implements IDiskDrawer { - private DoomMain DOOM; - private patch_t disk; - private int timer=0; - private String diskname; - - public static final String STDISK="STDISK"; - public static final String STCDROM="STCDROM"; - - public DiskDrawer(DoomMain DOOM, String icon){ - this.DOOM = DOOM; - this.diskname=icon; - } - - @Override - public void Init(){ - this.disk=DOOM.wadLoader.CachePatchName(diskname); - } - - @Override - public void Drawer() { - if (timer>0){ - if (timer%2==0) + private DoomMain DOOM; + private patch_t disk; + private int timer = 0; + private String diskname; + + public static final String STDISK = "STDISK"; + public static final String STCDROM = "STCDROM"; + + public DiskDrawer(DoomMain DOOM, String icon) { + this.DOOM = DOOM; + this.diskname = icon; + } + + @Override + public void Init() { + this.disk = DOOM.wadLoader.CachePatchName(diskname); + } + + @Override + public void Drawer() { + if (timer > 0) { + if (timer % 2 == 0) { DOOM.graphicSystem.DrawPatchScaled(FG, disk, DOOM.vs, 304, 184); - } - if (timer>=0) - timer--; - } - - @Override - public void setReading(int reading) { - timer=reading; - } - - @Override - public boolean isReading() { - return timer>0; - } - - @Override - public boolean justDoneReading() { - return timer==0; - } - + } + } + if (timer >= 0) { + timer--; + } + } + + @Override + public void setReading(int reading) { + timer = reading; + } + + @Override + public boolean isReading() { + return timer > 0; + } + + @Override + public boolean justDoneReading() { + return timer == 0; + } + } diff --git a/src/i/DoomEventInterface.java b/src/i/DoomEventInterface.java index d42c2634..99ad8f61 100644 --- a/src/i/DoomEventInterface.java +++ b/src/i/DoomEventInterface.java @@ -5,17 +5,15 @@ * @author Velktron * */ - - public interface DoomEventInterface { - /** The implementation is windowing subsystem-specific - * e.g. DOS, XServer, AWT or Swing or whatever. - * - */ - public void GetEvent(); + /** The implementation is windowing subsystem-specific + * e.g. DOS, XServer, AWT or Swing or whatever. + * + */ + public void GetEvent(); public boolean mouseMoving(); - + public void setMouseMoving(boolean mousMoving); } diff --git a/src/i/DoomSoundInterface.java b/src/i/DoomSoundInterface.java index 3a98e788..af4036ee 100644 --- a/src/i/DoomSoundInterface.java +++ b/src/i/DoomSoundInterface.java @@ -22,9 +22,6 @@ // System interface, sound. // //----------------------------------------------------------------------------- - - - import data.sfxinfo_t; @@ -35,83 +32,81 @@ extern FILE* sndserver; extern char* sndserver_filename; #endif*/ - - -public interface DoomSoundInterface{ - +public interface DoomSoundInterface { // Init at program start... -public void I_InitSound(); + public void I_InitSound(); // ... update sound buffer and audio device at runtime... -public void I_UpdateSound(); -public void I_SubmitSound(); + public void I_UpdateSound(); -// ... shut down and relase at program termination. -public void I_ShutdownSound(); + public void I_SubmitSound(); +// ... shut down and relase at program termination. + public void I_ShutdownSound(); // // SFX I/O // - // Initialize channels? -void I_SetChannels(); + void I_SetChannels(); // Get raw data lump index for sound descriptor. -public int I_GetSfxLumpNum (sfxinfo_t sfxinfo ); - + public int I_GetSfxLumpNum(sfxinfo_t sfxinfo); // Starts a sound in a particular sound channel. -public int -I_StartSound -( int id, - int vol, - int sep, - int pitch, - int priority ); - + public int + I_StartSound(int id, + int vol, + int sep, + int pitch, + int priority); // Stops a sound channel. -public void I_StopSound(int handle); + public void I_StopSound(int handle); // Called by S_*() functions // to see if a channel is still playing. // Returns 0 if no longer playing, 1 if playing. -public boolean I_SoundIsPlaying(int handle); + public boolean I_SoundIsPlaying(int handle); // Updates the volume, separation, // and pitch of a sound channel. -public void -I_UpdateSoundParams -( int handle, - int vol, - int sep, - int pitch ); - + public void + I_UpdateSoundParams(int handle, + int vol, + int sep, + int pitch); // // MUSIC I/O // -public void I_InitMusic(); -public void I_ShutdownMusic(); + public void I_InitMusic(); + + public void I_ShutdownMusic(); // Volume. -public void I_SetMusicVolume(int volume); + + public void I_SetMusicVolume(int volume); // PAUSE game handling. -public void I_PauseSong(int handle); -public void I_ResumeSong(int handle); + + public void I_PauseSong(int handle); + + public void I_ResumeSong(int handle); // Registers a song handle to song data. -public int I_RegisterSong(byte[] data); + + public int I_RegisterSong(byte[] data); // Called by anything that wishes to start music. // plays a song, and when the song is done, // starts playing it again in an endless loop. // Horrible thing to do, considering. -public void -I_PlaySong -( int handle, - int looping ); + + public void + I_PlaySong(int handle, + int looping); // Stops a song over 3 seconds. -public void I_StopSong(int handle); + + public void I_StopSong(int handle); // See above (register), then think backwards -public void I_UnRegisterSong(int handle); -} \ No newline at end of file + + public void I_UnRegisterSong(int handle); +} diff --git a/src/i/DoomSystem.java b/src/i/DoomSystem.java index 3852e104..5bcff3ab 100644 --- a/src/i/DoomSystem.java +++ b/src/i/DoomSystem.java @@ -109,13 +109,16 @@ import doom.DoomMain; import doom.ticcmd_t; import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; public class DoomSystem implements IDoomSystem { + private static final Logger LOGGER = Loggers.getLogger(DoomSystem.class.getName()); + public static void MiscError(String error, Object... args) { - System.err.print("Error: "); - System.err.print(error); - System.err.print("\n"); + LOGGER.log(Level.SEVERE, String.format("Error: %s", error)); } static int mb_used = 6; @@ -159,8 +162,7 @@ public void Quit() { try { DM.QuitNetGame(); } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Error: Quit() / DM.QuitNetGame()", e); } //DM.debugEnd(); /** @@ -187,8 +189,7 @@ public void WaitVBL(int count) { try { Thread.sleep(count * 1000 / 70); } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Error: WaitVBL / Thread.sleep()", e); } } @@ -209,7 +210,8 @@ public void EndRead() { @Override public void AllocLow(int length) { - ; // Dummy + // Dummy + } // @@ -217,12 +219,9 @@ public void AllocLow(int length) { // @Override public void Error(String error, Object... args) { + LOGGER.log(Level.SEVERE, String.format("Error: " + error, args)); - System.err.print("Error: "); - System.err.printf(error, args); - System.err.print("\n"); //va_end (argptr); - //fflush( stderr ); // Shutdown. Here might be other errors. if (DM.demorecording) { @@ -232,8 +231,7 @@ public void Error(String error, Object... args) { try { DM.QuitNetGame(); } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Error: Error() / DM.QuitNetGame()", e); } // DM.VI.ShutdownGraphics(); @@ -246,9 +244,7 @@ public void Error(String error) { // Message first. //va_start (argptr,error); - System.err.print("Error: "); - System.err.printf(error); - System.err.print("\n"); + LOGGER.log(Level.SEVERE, String.format("Error: %s", error)); //va_end (argptr); //fflush( stderr ); @@ -262,8 +258,8 @@ public void Error(String error) { // This particular implementation will generate a popup box.// @Override - public boolean GenerateAlert(String title, String cause) { - MsgBox alert = new MsgBox(null, title, cause, true); + public boolean GenerateAlert(String title, String cause, boolean showCancelButton) { + MsgBox alert = new MsgBox(null, title, cause, showCancelButton); return alert.isOk(); } } diff --git a/src/i/DummySystem.java b/src/i/DummySystem.java index 2bdf9b5f..a5a7bcf1 100644 --- a/src/i/DummySystem.java +++ b/src/i/DummySystem.java @@ -2,30 +2,30 @@ import doom.ticcmd_t; -public class DummySystem implements IDoomSystem{ +public class DummySystem implements IDoomSystem { @Override public void AllocLow(int length) { // TODO Auto-generated method stub - + } @Override public void BeginRead() { // TODO Auto-generated method stub - + } @Override public void EndRead() { // TODO Auto-generated method stub - + } @Override public void WaitVBL(int count) { // TODO Auto-generated method stub - + } @Override @@ -43,13 +43,13 @@ public int GetHeapSize() { @Override public void Tactile(int on, int off, int total) { // TODO Auto-generated method stub - + } @Override public void Quit() { // TODO Auto-generated method stub - + } @Override @@ -61,23 +61,23 @@ public ticcmd_t BaseTiccmd() { @Override public void Error(String error, Object... args) { // TODO Auto-generated method stub - + } @Override public void Error(String error) { // TODO Auto-generated method stub - + } @Override public void Init() { // TODO Auto-generated method stub - + } @Override - public boolean GenerateAlert(String title, String cause) { + public boolean GenerateAlert(String title, String cause, boolean showCancelButton) { // TODO Auto-generated method stub return false; } diff --git a/src/i/IDoomSystem.java b/src/i/IDoomSystem.java index 29e45971..7a2893a8 100644 --- a/src/i/IDoomSystem.java +++ b/src/i/IDoomSystem.java @@ -4,39 +4,38 @@ public interface IDoomSystem { - public void AllocLow(int length); + public void AllocLow(int length); - public void BeginRead(); + public void BeginRead(); - public void EndRead(); + public void EndRead(); - public void WaitVBL(int count); + public void WaitVBL(int count); - public byte[] ZoneBase(int size); + public byte[] ZoneBase(int size); - public int GetHeapSize(); + public int GetHeapSize(); - public void Tactile(int on, int off, int total); + public void Tactile(int on, int off, int total); - public void Quit(); + public void Quit(); - public ticcmd_t BaseTiccmd(); + public ticcmd_t BaseTiccmd(); - public void Error(String error, Object ... args); + public void Error(String error, Object... args); - void Error(String error); - - void Init(); - - /** Generate a blocking alert with the intention of continuing or aborting - * a certain game-altering action. E.g. loading PWADs, or upon critical - * level loading failures. This can be either a popup panel or console - * message. - * - * @param cause Provide a clear string explaining why the alert was generated - * @return true if we should continue, false if an alternate action should be taken. - */ - boolean GenerateAlert(String title,String cause); + void Error(String error); + void Init(); + + /** Generate a blocking alert with the intention of continuing or aborting + * a certain game-altering action. E.g. loading PWADs, or upon critical + * level loading failures. This can be either a popup panel or console + * message. + * + * @param cause Provide a clear string explaining why the alert was generated + * @return true if we should continue, false if an alternate action should be taken. + */ + boolean GenerateAlert(String title, String cause, boolean showCancelButton); } diff --git a/src/i/IDrawer.java b/src/i/IDrawer.java index 334876ba..10342776 100644 --- a/src/i/IDrawer.java +++ b/src/i/IDrawer.java @@ -2,6 +2,6 @@ public interface IDrawer { - public void Drawer(); - + public void Drawer(); + } diff --git a/src/i/Strings.java b/src/i/Strings.java index c057b7d5..f0e673a3 100644 --- a/src/i/Strings.java +++ b/src/i/Strings.java @@ -1,36 +1,41 @@ package i; public final class Strings { - public static final String MOCHA_DOOM_TITLE="Mocha Doom Alpha 1.6"; - - public static final String MODIFIED_GAME= - ("===========================================================================\n"+ - "ATTENTION: This version of DOOM has been modified. If you would like to\n"+ - "get a copy of the original game, call 1-800-IDGAMES or see the readme file.\n"+ - " You will not receive technical support for modified games.\n"+ - " press enter to continue\n"+ - "===========================================================================\n"); - - public static final String MODIFIED_GAME_TITLE="Modified game alert"; - - public static final String MODIFIED_GAME_DIALOG= - - ("
"+ - "===========================================================================
"+ - "ATTENTION: This version of DOOM has been modified. If you would like to
"+ - "get a copy of the original game, call 1-800-IDGAMES or see the readme file.
"+ - " You will not receive technical support for modified games.
"+ - " press OK to continue
"+ - "===========================================================================
"+ - "
"); - - public static final String LEVEL_FAILURE_TITLE="Level loading failure"; - - public static final String LEVEL_FAILURE_CAUSE= - - ("
"+ - "Level loading failed!
"+ - "Press OK to end this game without exiting, or cancel to quit Doom."+ - "
"); - + + public static final String MOCHA_DOOM_TITLE = "Mocha Doom Alpha 1.6"; + + public static final String MODIFIED_GAME_TITLE = "Modified game alert"; + + public static final String MODIFIED_GAME_DIALOG + = ("
" + + "===========================================================================
" + + "ATTENTION: This version of DOOM has been modified. If you would like to
" + + "get a copy of the original game, call 1-800-IDGAMES or see the readme file.
" + + " You will not receive technical support for modified games.
" + + " press OK to continue
" + + "===========================================================================
" + + "
"); + + public static final String LEVEL_FAILURE_TITLE = "Level loading failure"; + + public static final String LEVEL_FAILURE_CAUSE + = ("
" + + "Level loading failed!
" + + "Press OK to end this game without exiting, or cancel to quit Doom." + + "
"); + + public static final String NO_WAD_FILE_FOUND_TITLE = "Cannot find a game IWAD"; + + public static final String NO_WAD_FILE_FOUND_NOTE = "" + + "===========================================================================
" + + "Execution could not continue:
" + + "Cannot find a game IWAD (doom.wad, doom2.wad, etc.).
" + + "
" + + "You can do either of the following:
" + + "- Place one or more of these WADs in the same directory as Mocha Doom.
" + + "- Start Mocha Doom with '-iwad' parameter e.g. 'mochadoom -iwad wads/doom.wad'
" + + "- Define 'DOOMWADDIR' environment variable which points to a directory of WAD files.
" + + "===========================================================================
" + + ""; + } diff --git a/src/i/SystemSoundInterface.java b/src/i/SystemSoundInterface.java index eadbc574..72f54ba5 100644 --- a/src/i/SystemSoundInterface.java +++ b/src/i/SystemSoundInterface.java @@ -22,9 +22,6 @@ // System interface, sound. // //----------------------------------------------------------------------------- - - - import data.sfxinfo_t; @@ -35,83 +32,81 @@ extern FILE* sndserver; extern char* sndserver_filename; #endif*/ - - -public interface SystemSoundInterface{ - +public interface SystemSoundInterface { // Init at program start... -public void InitSound(); + public void InitSound(); // ... update sound buffer and audio device at runtime... -public void UpdateSound(); -public void SubmitSound(); + public void UpdateSound(); -// ... shut down and relase at program termination. -public void ShutdownSound(); + public void SubmitSound(); +// ... shut down and relase at program termination. + public void ShutdownSound(); // // SFX I/O // - // Initialize channels? -void SetChannels(); + void SetChannels(); // Get raw data lump index for sound descriptor. -public int GetSfxLumpNum (sfxinfo_t sfxinfo ); - + public int GetSfxLumpNum(sfxinfo_t sfxinfo); // Starts a sound in a particular sound channel. -public int -StartSound -( int id, - int vol, - int sep, - int pitch, - int priority ); - + public int + StartSound(int id, + int vol, + int sep, + int pitch, + int priority); // Stops a sound channel. -public void StopSound(int handle); + public void StopSound(int handle); // Called by S_*() functions // to see if a channel is still playing. // Returns 0 if no longer playing, 1 if playing. -public boolean SoundIsPlaying(int handle); + public boolean SoundIsPlaying(int handle); // Updates the volume, separation, // and pitch of a sound channel. -public void -UpdateSoundParams -( int handle, - int vol, - int sep, - int pitch ); - + public void + UpdateSoundParams(int handle, + int vol, + int sep, + int pitch); // // MUSIC I/O // -public void InitMusic(); -public void ShutdownMusic(); + public void InitMusic(); + + public void ShutdownMusic(); // Volume. -public void SetMusicVolume(int volume); + + public void SetMusicVolume(int volume); // PAUSE game handling. -public void PauseSong(int handle); -public void ResumeSong(int handle); + + public void PauseSong(int handle); + + public void ResumeSong(int handle); // Registers a song handle to song data. -public int RegisterSong(byte[] data); + + public int RegisterSong(byte[] data); // Called by anything that wishes to start music. // plays a song, and when the song is done, // starts playing it again in an endless loop. // Horrible thing to do, considering. -public void -PlaySong -( int handle, - int looping ); + + public void + PlaySong(int handle, + int looping); // Stops a song over 3 seconds. -public void StopSong(int handle); + + public void StopSong(int handle); // See above (register), then think backwards -public void UnRegisterSong(int handle); -} \ No newline at end of file + + public void UnRegisterSong(int handle); +} diff --git a/src/i/system.java b/src/i/system.java index b257045d..98d2e113 100644 --- a/src/i/system.java +++ b/src/i/system.java @@ -36,12 +36,17 @@ // DESCRIPTION: // //----------------------------------------------------------------------------- - package i; -public class system{ - -/* +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; + +public class system { + + private static final Logger LOGGER = Loggers.getLogger(system.class.getName()); + + /* #include #include #include @@ -63,45 +68,36 @@ public class system{ #endif #include "i_system.h" -*/ - + */ + static int mb_used = 6; -static int mb_used = 6; + public void + Tactile(int on, + int off, + int total) { + // UNUSED. + on = off = total = 0; + } - -public void -Tactile -( int on, - int off, - int total ) -{ - // UNUSED. - on = off = total = 0; -} - -/* + /* ticcmd_t emptycmd; ticcmd_t* I_BaseTiccmd(void) { return &emptycmd; } -*/ - -public static int GetHeapSize () -{ - return mb_used*1024*1024; -} + */ + public static int GetHeapSize() { + return mb_used * 1024 * 1024; + } -/* + /* byte* I_ZoneBase (int* size) { *size = mb_used*1024*1024; return (byte *) malloc (*size); } -*/ - - + */ // // I_GetTime // returns time in 1/70th second tics @@ -120,9 +116,7 @@ int I_GetTime () newtics = (tp.tv_sec-basetime)*TICRATE + tp.tv_usec*TICRATE/1000000; return newtics; } -*/ - - + */ // // I_Init // @@ -176,33 +170,26 @@ void I_EndRead(void) return mem; } -*/ - + */ // // I_Error // -public static boolean demorecording; - -public static void Error (String error, Object ... args) -{ - //va_list argptr; - - // Message first. - //va_start (argptr,error); - System.err.print("Error: "); - System.err.printf(error,args); - System.err.print("\n"); - //va_end (argptr); + public static boolean demorecording; - //fflush( stderr ); + public static void Error(String error, Object... args) { + //va_list argptr; - // Shutdown. Here might be other errors. - //if (demorecording) - //G_CheckDemoStatus(); + // Message first. + //va_start (argptr,error); + LOGGER.log(Level.SEVERE, String.format("Error: " + error, args)); + //va_end (argptr); - //D_QuitNetGame (); - //I_ShutdownGraphics(); - - System.exit(-1); -} + //fflush( stderr ); + // Shutdown. Here might be other errors. + //if (demorecording) + //G_CheckDemoStatus(); + //D_QuitNetGame (); + //I_ShutdownGraphics(); + System.exit(-1); + } } diff --git a/src/m/AbstractDoomMenu.java b/src/m/AbstractDoomMenu.java index 1de92ccb..81407866 100644 --- a/src/m/AbstractDoomMenu.java +++ b/src/m/AbstractDoomMenu.java @@ -5,10 +5,9 @@ public abstract class AbstractDoomMenu implements IDoomMenu { ////////////////////// CONTEXT /////////////////// - final DoomMain DOOM; public AbstractDoomMenu(DoomMain DOOM) { this.DOOM = DOOM; } -} \ No newline at end of file +} diff --git a/src/m/BBox.java b/src/m/BBox.java index ed876f67..951676a1 100644 --- a/src/m/BBox.java +++ b/src/m/BBox.java @@ -1,6 +1,7 @@ package m; -import static data.Limits.*; +import static data.Limits.MAXINT; +import static data.Limits.MININT; /** A fucked-up bounding box class. * Fucked-up because it's supposed to wrap fixed_t's.... no fucking way I'm doing @@ -9,142 +10,156 @@ * @author admin * */ - public class BBox { - public static final int BOXTOP = 0; - public static final int BOXBOTTOM = 1; - public static final int BOXLEFT = 2; - public static final int BOXRIGHT = 3; - /** (fixed_t) */ - public int[] bbox; - - /** Points of the bbox as an object */ - - public BBox() { - bbox = new int[4]; - } - - // Static method - - public static void ClearBox(fixed_t[] box) { - box[BOXRIGHT].set(MININT); - box[BOXTOP].set(MININT); - box[BOXLEFT].set(MAXINT); - box[BOXBOTTOM].set(MAXINT); - } - - // Instance method - - public void ClearBox() { - bbox[BOXRIGHT]=(MININT); - bbox[BOXTOP]=(MININT); - bbox[BOXLEFT]=(MAXINT); - bbox[BOXBOTTOM]=(MAXINT); - } - - public static void AddToBox(fixed_t[] box, fixed_t x, fixed_t y) { - if (x.compareTo(box[BOXLEFT]) < 0) - box[BOXLEFT].copy(x); - else if (x.compareTo(box[BOXRIGHT]) > 0) - box[BOXRIGHT].copy(x); - if (y.compareTo(box[BOXBOTTOM]) < 0) - box[BOXBOTTOM] = y; - else if (y.compareTo(box[BOXTOP]) > 0) - box[BOXTOP] = y; - } - - public void AddToBox(fixed_t x, fixed_t y) { - if (x.compareTo(bbox[BOXLEFT]) < 0) - bbox[BOXLEFT]=x.val; - else if (x.compareTo(bbox[BOXRIGHT]) > 0) - bbox[BOXRIGHT]=x.val; - if (y.compareTo(bbox[BOXBOTTOM]) < 0) - bbox[BOXBOTTOM] = y.val; - else if (y.compareTo(bbox[BOXTOP]) > 0) - bbox[BOXTOP] = y.val; - } - - /** - * MAES: Keeping with C's type (in)consistency, we also allow to input ints - * -_- - * - * @param x - * @param y - */ - public void AddToBox(int x, int y) { - if (x < bbox[BOXLEFT]) - bbox[BOXLEFT]=(x); - if (x > bbox[BOXRIGHT]) - bbox[BOXRIGHT]=(x); - if (y < bbox[BOXBOTTOM]) - bbox[BOXBOTTOM]=(y); - if (y > bbox[BOXTOP]) - bbox[BOXTOP]=(y); - } - - /** - * R_AddPointToBox Expand a given bbox so that it encloses a given point. - * - * @param x - * @param y - * @param box - */ - - public static void AddPointToBox(int x, int y, fixed_t[] box) { - if (x < box[BOXLEFT].val) - box[BOXLEFT].set(x); - if (x > box[BOXRIGHT].val) - box[BOXRIGHT].set(x); - if (y < box[BOXBOTTOM].val) - box[BOXBOTTOM].set(y); - if (y > box[BOXTOP].val) - box[BOXTOP].set(y); - } - - /** - * R_AddPointToBox Expand this bbox so that it encloses a given point. - * - * @param x - * @param y - * @param box - */ - - public void AddPointToBox(int x, int y) { - if (x < bbox[BOXLEFT]) - bbox[BOXLEFT]=x; - if (x > bbox[BOXRIGHT]) - bbox[BOXRIGHT]=x; - if (y < bbox[BOXBOTTOM]) - bbox[BOXBOTTOM]=y; - if (y > bbox[BOXTOP]) - bbox[BOXTOP]=y; - } - - public int get(int BOXCOORDS){ - return this.bbox[BOXCOORDS]; - } - - public void set(int BOXCOORDS, int val){ - this.bbox[BOXCOORDS]=val; + public static final int BOXTOP = 0; + public static final int BOXBOTTOM = 1; + public static final int BOXLEFT = 2; + public static final int BOXRIGHT = 3; + /** (fixed_t) */ + public int[] bbox; + + /** Points of the bbox as an object */ + public BBox() { + bbox = new int[4]; + } + + // Static method + public static void ClearBox(fixed_t[] box) { + box[BOXRIGHT].set(MININT); + box[BOXTOP].set(MININT); + box[BOXLEFT].set(MAXINT); + box[BOXBOTTOM].set(MAXINT); + } + + // Instance method + public void ClearBox() { + bbox[BOXRIGHT] = (MININT); + bbox[BOXTOP] = (MININT); + bbox[BOXLEFT] = (MAXINT); + bbox[BOXBOTTOM] = (MAXINT); + } + + public static void AddToBox(fixed_t[] box, fixed_t x, fixed_t y) { + if (x.compareTo(box[BOXLEFT]) < 0) { + box[BOXLEFT].copy(x); + } else if (x.compareTo(box[BOXRIGHT]) > 0) { + box[BOXRIGHT].copy(x); + } + if (y.compareTo(box[BOXBOTTOM]) < 0) { + box[BOXBOTTOM] = y; + } else if (y.compareTo(box[BOXTOP]) > 0) { + box[BOXTOP] = y; + } + } + + public void AddToBox(fixed_t x, fixed_t y) { + if (x.compareTo(bbox[BOXLEFT]) < 0) { + bbox[BOXLEFT] = x.val; + } else if (x.compareTo(bbox[BOXRIGHT]) > 0) { + bbox[BOXRIGHT] = x.val; + } + if (y.compareTo(bbox[BOXBOTTOM]) < 0) { + bbox[BOXBOTTOM] = y.val; + } else if (y.compareTo(bbox[BOXTOP]) > 0) { + bbox[BOXTOP] = y.val; + } + } + + /** + * MAES: Keeping with C's type (in)consistency, we also allow to input ints + * -_- + * + * @param x + * @param y + */ + public void AddToBox(int x, int y) { + if (x < bbox[BOXLEFT]) { + bbox[BOXLEFT] = (x); + } + if (x > bbox[BOXRIGHT]) { + bbox[BOXRIGHT] = (x); + } + if (y < bbox[BOXBOTTOM]) { + bbox[BOXBOTTOM] = (y); + } + if (y > bbox[BOXTOP]) { + bbox[BOXTOP] = (y); + } + } + + /** + * R_AddPointToBox Expand a given bbox so that it encloses a given point. + * + * @param x + * @param y + * @param box + */ + public static void AddPointToBox(int x, int y, fixed_t[] box) { + if (x < box[BOXLEFT].val) { + box[BOXLEFT].set(x); + } + if (x > box[BOXRIGHT].val) { + box[BOXRIGHT].set(x); + } + if (y < box[BOXBOTTOM].val) { + box[BOXBOTTOM].set(y); + } + if (y > box[BOXTOP].val) { + box[BOXTOP].set(y); + } + } + + /** + * R_AddPointToBox Expand this bbox so that it encloses a given point. + * + * @param x + * @param y + * @param box + */ + public void AddPointToBox(int x, int y) { + if (x < bbox[BOXLEFT]) { + bbox[BOXLEFT] = x; + } + if (x > bbox[BOXRIGHT]) { + bbox[BOXRIGHT] = x; + } + if (y < bbox[BOXBOTTOM]) { + bbox[BOXBOTTOM] = y; + } + if (y > bbox[BOXTOP]) { + bbox[BOXTOP] = y; + } + } + + public int get(int BOXCOORDS) { + return this.bbox[BOXCOORDS]; + } + + public void set(int BOXCOORDS, int val) { + this.bbox[BOXCOORDS] = val; } public static void ClearBox(int[] bbox) { - bbox[BOXRIGHT]=(MININT); - bbox[BOXTOP]=(MININT); - bbox[BOXLEFT]=(MAXINT); - bbox[BOXBOTTOM]=(MAXINT); + bbox[BOXRIGHT] = (MININT); + bbox[BOXTOP] = (MININT); + bbox[BOXLEFT] = (MAXINT); + bbox[BOXBOTTOM] = (MAXINT); } public static void AddToBox(int[] box, int x, int y) { - if (x < box[BOXLEFT]) - box[BOXLEFT]=x; - if (x > box[BOXRIGHT]) - box[BOXRIGHT]=x; - if (y < box[BOXBOTTOM]) - box[BOXBOTTOM]=y; - if (y > box[BOXTOP]) - box[BOXTOP]=y; + if (x < box[BOXLEFT]) { + box[BOXLEFT] = x; + } + if (x > box[BOXRIGHT]) { + box[BOXRIGHT] = x; + } + if (y < box[BOXBOTTOM]) { + box[BOXBOTTOM] = y; + } + if (y > box[BOXTOP]) { + box[BOXTOP] = y; + } } - + } diff --git a/src/m/DelegateRandom.java b/src/m/DelegateRandom.java index 43c24120..734a085c 100644 --- a/src/m/DelegateRandom.java +++ b/src/m/DelegateRandom.java @@ -19,7 +19,12 @@ import data.Defines; import data.mobjtype_t; import doom.SourceCode.M_Random; -import static doom.SourceCode.M_Random.*; +import static doom.SourceCode.M_Random.M_ClearRandom; +import static doom.SourceCode.M_Random.M_Random; +import static doom.SourceCode.M_Random.P_Random; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import p.ActiveStates; import utils.C2JUtils; @@ -39,7 +44,9 @@ * @author Good Sign */ public class DelegateRandom implements IRandom { - + + private static final Logger LOGGER = Loggers.getLogger(DelegateRandom.class.getName()); + private IRandom random; private IRandom altRandom; @@ -60,11 +67,11 @@ private void switchRandom(boolean which) { if (arandom != null && ((!which && arandom instanceof DoomRandom) || (which && arandom instanceof JavaRandom))) { this.altRandom = random; this.random = arandom; - System.out.print(String.format("M_Random: Switching to %s\n", random.getClass().getSimpleName())); + LOGGER.log(Level.INFO, String.format("M_Random: Switching to %s\n", random.getClass().getSimpleName())); } else { this.altRandom = random; this.random = which ? new JavaRandom() : new DoomRandom(); - System.out.print(String.format("M_Random: Switching to %s (new instance)\n", random.getClass().getSimpleName())); + LOGGER.log(Level.INFO, String.format("M_Random: Switching to %s (new instance)\n", random.getClass().getSimpleName())); } //random.ClearRandom(); } @@ -111,5 +118,5 @@ public int P_Random(ActiveStates caller, int sequence) { public int P_Random(ActiveStates caller, mobjtype_t type, int sequence) { return random.P_Random(caller, type, sequence); } - + } diff --git a/src/m/DoomRandom.java b/src/m/DoomRandom.java index a85ae3a2..bdadbba5 100644 --- a/src/m/DoomRandom.java +++ b/src/m/DoomRandom.java @@ -73,32 +73,31 @@ // Random number LUT. // //----------------------------------------------------------------------------- - -class DoomRandom implements IRandom{ +class DoomRandom implements IRandom { /** * M_Random * Returns a 0-255 number. Made into shorts for Java, because of their nature. */ public static short rndtable[] = { - 0, 8, 109, 220, 222, 241, 149, 107, 75, 248, 254, 140, 16, 66 , - 74, 21, 211, 47, 80, 242, 154, 27, 205, 128, 161, 89, 77, 36 , - 95, 110, 85, 48, 212, 140, 211, 249, 22, 79, 200, 50, 28, 188 , - 52, 140, 202, 120, 68, 145, 62, 70, 184, 190, 91, 197, 152, 224 , - 149, 104, 25, 178, 252, 182, 202, 182, 141, 197, 4, 81, 181, 242 , - 145, 42, 39, 227, 156, 198, 225, 193, 219, 93, 122, 175, 249, 0 , - 175, 143, 70, 239, 46, 246, 163, 53, 163, 109, 168, 135, 2, 235 , - 25, 92, 20, 145, 138, 77, 69, 166, 78, 176, 173, 212, 166, 113 , - 94, 161, 41, 50, 239, 49, 111, 164, 70, 60, 2, 37, 171, 75 , - 136, 156, 11, 56, 42, 146, 138, 229, 73, 146, 77, 61, 98, 196 , - 135, 106, 63, 197, 195, 86, 96, 203, 113, 101, 170, 247, 181, 113 , - 80, 250, 108, 7, 255, 237, 129, 226, 79, 107, 112, 166, 103, 241 , - 24, 223, 239, 120, 198, 58, 60, 82, 128, 3, 184, 66, 143, 224 , - 145, 224, 81, 206, 163, 45, 63, 90, 168, 114, 59, 33, 159, 95 , - 28, 139, 123, 98, 125, 196, 15, 70, 194, 253, 54, 14, 109, 226 , - 71, 17, 161, 93, 186, 87, 244, 138, 20, 52, 123, 251, 26, 36 , - 17, 46, 52, 231, 232, 76, 31, 221, 84, 37, 216, 165, 212, 106 , - 197, 242, 98, 43, 39, 175, 254, 145, 190, 84, 118, 222, 187, 136 , + 0, 8, 109, 220, 222, 241, 149, 107, 75, 248, 254, 140, 16, 66, + 74, 21, 211, 47, 80, 242, 154, 27, 205, 128, 161, 89, 77, 36, + 95, 110, 85, 48, 212, 140, 211, 249, 22, 79, 200, 50, 28, 188, + 52, 140, 202, 120, 68, 145, 62, 70, 184, 190, 91, 197, 152, 224, + 149, 104, 25, 178, 252, 182, 202, 182, 141, 197, 4, 81, 181, 242, + 145, 42, 39, 227, 156, 198, 225, 193, 219, 93, 122, 175, 249, 0, + 175, 143, 70, 239, 46, 246, 163, 53, 163, 109, 168, 135, 2, 235, + 25, 92, 20, 145, 138, 77, 69, 166, 78, 176, 173, 212, 166, 113, + 94, 161, 41, 50, 239, 49, 111, 164, 70, 60, 2, 37, 171, 75, + 136, 156, 11, 56, 42, 146, 138, 229, 73, 146, 77, 61, 98, 196, + 135, 106, 63, 197, 195, 86, 96, 203, 113, 101, 170, 247, 181, 113, + 80, 250, 108, 7, 255, 237, 129, 226, 79, 107, 112, 166, 103, 241, + 24, 223, 239, 120, 198, 58, 60, 82, 128, 3, 184, 66, 143, 224, + 145, 224, 81, 206, 163, 45, 63, 90, 168, 114, 59, 33, 159, 95, + 28, 139, 123, 98, 125, 196, 15, 70, 194, 253, 54, 14, 109, 226, + 71, 17, 161, 93, 186, 87, 244, 138, 20, 52, 123, 251, 26, 36, + 17, 46, 52, 231, 232, 76, 31, 221, 84, 37, 216, 165, 212, 106, + 197, 242, 98, 43, 39, 175, 254, 145, 190, 84, 118, 222, 187, 136, 120, 163, 236, 249 }; @@ -137,20 +136,20 @@ public int P_Random(String message) { @Override public int P_Random(ActiveStates caller, int sequence) { - int value = P_Random(); /* - SLY.sync("PR #%d %s_%d [%d]=%d\n", caller.ordinal(),caller,sequence, - prndindex, value);*/ - return value; + SLY.sync("PR #%d %s_%d [%d]=%d\n", caller.ordinal(),caller,sequence, + prndindex, value);*/ + + return P_Random(); } @Override public int P_Random(ActiveStates caller, mobjtype_t type, int sequence) { - int value = P_Random(); /* - SLY.sync("PR #%d %s_%d %s [%d]=%d\n", caller.ordinal(),caller,sequence, + SLY.sync("PR #%d %s_%d %s [%d]=%d\n", caller.ordinal(),caller,sequence, type, prndindex, value);*/ - return value; + + return P_Random(); } @Override diff --git a/src/m/DoomSetting.java b/src/m/DoomSetting.java index 2ec78871..aecd90f2 100644 --- a/src/m/DoomSetting.java +++ b/src/m/DoomSetting.java @@ -19,19 +19,18 @@ * * */ - public class DoomSetting implements Comparable { - - public static final int BOOLEAN=1; - public static final int CHAR=2; - public static final int DOUBLE=4; - public static final int INTEGER=8; - public static final int STRING=16; - + + public static final int BOOLEAN = 1; + public static final int CHAR = 2; + public static final int DOUBLE = 4; + public static final int INTEGER = 8; + public static final int STRING = 16; + private String name; - + private int typeflag; - + // Every setting can be readily interpreted as any of these private int int_val; private long long_val; @@ -39,194 +38,186 @@ public class DoomSetting implements Comparable { private double double_val; private boolean boolean_val; private String string_val; - + /** Should be saved to file */ private boolean persist; - - public DoomSetting(String name, String value, boolean persist){ - this.name=name; - this.typeflag=STRING; + + public DoomSetting(String name, String value, boolean persist) { + this.name = name; + this.typeflag = STRING; this.updateValue(value); - this.persist=persist; + this.persist = persist; } - - public String getName(){ + + public String getName() { return name; } - - public int getInteger(){ + + public int getInteger() { return int_val; } - - public long getLong(){ + + public long getLong() { return long_val; } - - public char getChar(){ - return (char)int_val; + + public char getChar() { + return (char) int_val; } - - public String getString(){ + + public String getString() { return string_val; } - - public double getDouble(){ + + public double getDouble() { return double_val; } - public boolean getBoolean(){ + public boolean getBoolean() { return boolean_val; } - - public boolean getPersist(){ + + public boolean getPersist() { return persist; } - public int getTypeFlag(){ + public int getTypeFlag() { return typeflag; } - /** All the gory disambiguation work should go here. * * @param value */ - - public void updateValue(String value){ - - boolean quoted=false; - - if (value.length()>2) - if (quoted=C2JUtils.isQuoted(value,'"' )) - value=C2JUtils.unquote(value, '"'); - else - if (quoted=C2JUtils.isQuoted(value,'\'' )) - value=C2JUtils.unquote(value, '\''); + public void updateValue(String value) { + + boolean quoted = false; + + if (value.length() > 2) { + if (quoted = C2JUtils.isQuoted(value, '"')) { + value = C2JUtils.unquote(value, '"'); + } else if (quoted = C2JUtils.isQuoted(value, '\'')) { + value = C2JUtils.unquote(value, '\''); + } + } // String value always available - this.string_val=value; - + this.string_val = value; + // If quoted and sensibly ranged, it gets priority as a "character" - - if (quoted && value.length()==1 && value.charAt(0)>=0 && value.charAt(0)<255){ - char_val=Character.toLowerCase(value.charAt(0)); - int_val=char_val; - long_val=char_val; - double_val=char_val; - typeflag|=CHAR; + if (quoted && value.length() == 1 && value.charAt(0) >= 0 && value.charAt(0) < 255) { + char_val = Character.toLowerCase(value.charAt(0)); + int_val = char_val; + long_val = char_val; + double_val = char_val; + typeflag |= CHAR; return; } - + // Not a character, try all other stuff - - try { - this.int_val=Integer.parseInt(value); - typeflag|=INTEGER; - } catch (NumberFormatException e) { - // No nookie - this.int_val=-1; - } - - try { - this.long_val=Long.parseLong(value); - } catch (NumberFormatException e) { - try { - // Try decoding it as hex, octal, whatever. - this.long_val=Long.decode(value); - typeflag|=INTEGER; - } catch (NumberFormatException h){ - // If even THAT fails, then no nookie. - this.long_val=-1; - } - } - - try { - this.double_val=Double.parseDouble(value); - typeflag|=DOUBLE; - } catch (NumberFormatException e) { - // No nookie - this.double_val=Double.NaN; - } - - // Use long value to "trump" smaller ones - int_val=(int)long_val; - char_val=(char)int_val; - - // Boolean has a few more options; - // Only mark something explicitly as boolean if the string reads - // actually "true" or "false". Numbers such as 0 and 1 might still get - // interpreted as booleans, but that shouldn't trump the entire number, - // otherwise everything and the cat is boolean - - this.boolean_val=(int_val==1); - - if (Boolean.parseBoolean(value) || - (value.compareToIgnoreCase("false")==0)){ - this.boolean_val=(int_val==1) || Boolean.parseBoolean(value); - this.typeflag|=BOOLEAN; - } + try { + this.int_val = Integer.parseInt(value); + typeflag |= INTEGER; + } catch (NumberFormatException e) { + // No nookie + this.int_val = -1; } - - /** Answer definitively if a setting cannot ABSOLUTELY be - * parsed into a number using simple Integer rules. - * This excludes some special names like "+Inf" and "NaN". - * - * @return - */ - - public boolean isIntegerNumeric(){ - + + try { + this.long_val = Long.parseLong(value); + } catch (NumberFormatException e) { try { - this.long_val=Long.parseLong(string_val); - } catch (NumberFormatException e) { - try { - // Try decoding it as hex, octal, whatever. - Long.decode(string_val); - - } catch (NumberFormatException h){ - // If even THAT fails, then no nookie. - return false; - } - } - - // Everything OK, I presume... - return true; + // Try decoding it as hex, octal, whatever. + this.long_val = Long.decode(value); + typeflag |= INTEGER; + } catch (NumberFormatException h) { + // If even THAT fails, then no nookie. + this.long_val = -1; + } } - /** Settings are "comparable" to each other by name, so we can save - * nicely sorted setting files ;-) - * - * @param o - * @return - */ - - @Override - public int compareTo(DoomSetting o) { - return this.name.compareToIgnoreCase(o.getName()); + try { + this.double_val = Double.parseDouble(value); + typeflag |= DOUBLE; + } catch (NumberFormatException e) { + // No nookie + this.double_val = Double.NaN; } - - public String toString(){ - return string_val; + + // Use long value to "trump" smaller ones + int_val = (int) long_val; + char_val = (char) int_val; + + // Boolean has a few more options; + // Only mark something explicitly as boolean if the string reads + // actually "true" or "false". Numbers such as 0 and 1 might still get + // interpreted as booleans, but that shouldn't trump the entire number, + // otherwise everything and the cat is boolean + this.boolean_val = (int_val == 1); + + if (Boolean.parseBoolean(value) + || (value.compareToIgnoreCase("false") == 0)) { + this.boolean_val = (int_val == 1) || Boolean.parseBoolean(value); + this.typeflag |= BOOLEAN; } + } + + /** Answer definitively if a setting cannot ABSOLUTELY be + * parsed into a number using simple Integer rules. + * This excludes some special names like "+Inf" and "NaN". + * + * @return + */ + public boolean isIntegerNumeric() { + + try { + this.long_val = Long.parseLong(string_val); + } catch (NumberFormatException e) { + try { + // Try decoding it as hex, octal, whatever. + Long.decode(string_val); - /** A special setting that returns false, 0 and an empty string, if required. - * Simplifies handling of nulls A LOT. So code that relies on specific settings - * should be organized to work only on clear positivies (e.g. use a "fullscreen" setting - * that must exist and be equal to 1 or true, instead of assuming that a zero/false - * value enables it. */ - - public static DoomSetting NULL_SETTING=new DoomSetting("NULL","",false); - - static { - // It's EVERYTHING - NULL_SETTING.typeflag=0x1F; - NULL_SETTING.string_val=""; - NULL_SETTING.char_val=0; - NULL_SETTING.double_val=0; - NULL_SETTING.boolean_val=false; - NULL_SETTING.int_val=0; - NULL_SETTING.long_val=0; + } catch (NumberFormatException h) { + // If even THAT fails, then no nookie. + return false; + } } - - + + // Everything OK, I presume... + return true; + } + + /** Settings are "comparable" to each other by name, so we can save + * nicely sorted setting files ;-) + * + * @param o + * @return + */ + @Override + public int compareTo(DoomSetting o) { + return this.name.compareToIgnoreCase(o.getName()); + } + + public String toString() { + return string_val; + } + + /** A special setting that returns false, 0 and an empty string, if required. + * Simplifies handling of nulls A LOT. So code that relies on specific settings + * should be organized to work only on clear positivies (e.g. use a "fullscreen" setting + * that must exist and be equal to 1 or true, instead of assuming that a zero/false + * value enables it. */ + public static DoomSetting NULL_SETTING = new DoomSetting("NULL", "", false); + + static { + // It's EVERYTHING + NULL_SETTING.typeflag = 0x1F; + NULL_SETTING.string_val = ""; + NULL_SETTING.char_val = 0; + NULL_SETTING.double_val = 0; + NULL_SETTING.boolean_val = false; + NULL_SETTING.int_val = 0; + NULL_SETTING.long_val = 0; } + +} diff --git a/src/m/DrawRoutine.java b/src/m/DrawRoutine.java index 2ba52273..752eba15 100644 --- a/src/m/DrawRoutine.java +++ b/src/m/DrawRoutine.java @@ -8,6 +8,6 @@ * */ public interface DrawRoutine { - -public void invoke(); + + public void invoke(); } diff --git a/src/m/DummyMenu.java b/src/m/DummyMenu.java index 65ce1efa..f64f79cc 100644 --- a/src/m/DummyMenu.java +++ b/src/m/DummyMenu.java @@ -9,12 +9,12 @@ * @author Maes * */ - public class DummyMenu extends AbstractDoomMenu { + public DummyMenu(DoomMain DOOM) { super(DOOM); } - + @Override public boolean Responder(event_t ev) { // TODO Auto-generated method stub @@ -75,10 +75,10 @@ public int getDetailLevel() { return 0; } - @Override - public void ClearMenus() { - // TODO Auto-generated method stub - - } + @Override + public void ClearMenus() { + // TODO Auto-generated method stub + + } } diff --git a/src/m/FixedFloat.java b/src/m/FixedFloat.java index 63c1f4c0..ca5c5903 100644 --- a/src/m/FixedFloat.java +++ b/src/m/FixedFloat.java @@ -9,80 +9,82 @@ * @author Maes * */ - public class FixedFloat { // Various bit masks for IEEE-754 floating point - public static final int MANTISSA_32=0x007FFFFF; - public static final int EXP_32=0x7F800000; - public static final int IMPLICIT_32=0x00800000; - public static final int SIGN_32=0x80000000; - public static final int NONSIGN_32=0x7FFFFFFF; - public static final long SIGN_64=0x8000000000000000L; - public static final long EXP_64=0x7FF0000000000000L; - public static final long IMPLICIT_64=0x0010000000000000L; - public static final long MANTISSA_64=0x000fffffffffffffL; - - public static float toFloat(int fixed){ - if (fixed==0) return (float)(0.0); + public static final int MANTISSA_32 = 0x007FFFFF; + public static final int EXP_32 = 0x7F800000; + public static final int IMPLICIT_32 = 0x00800000; + public static final int SIGN_32 = 0x80000000; + public static final int NONSIGN_32 = 0x7FFFFFFF; + public static final long SIGN_64 = 0x8000000000000000L; + public static final long EXP_64 = 0x7FF0000000000000L; + public static final long IMPLICIT_64 = 0x0010000000000000L; + public static final long MANTISSA_64 = 0x000fffffffffffffL; + + public static float toFloat(int fixed) { + if (fixed == 0) { + return (float) (0.0); + } // Remember sign. - int sign=fixed&SIGN_32; - if (fixed<0) fixed=-fixed; - int exp=findShift(fixed); + int sign = fixed & SIGN_32; + if (fixed < 0) { + fixed = -fixed; + } + int exp = findShift(fixed); // First shift to left to "cancel" bits "above" the first. - int mantissa=(fixed<<(exp+2))>>>9; - int result=sign|(((14-exp)+127)<<23)|mantissa; + int mantissa = (fixed << (exp + 2)) >>> 9; + int result = sign | (((14 - exp) + 127) << 23) | mantissa; /*if (fixed<0) System.out.println(Integer.toBinaryString(fixed) +"\n"+ Integer.toBinaryString(-fixed) +"\n"+ Integer.toBinaryString(result));*/ return Float.intBitsToFloat(result); } - - private static int findShift(int fixed){ + + private static int findShift(int fixed) { // only non-sign bits. - fixed&=NONSIGN_32; + fixed &= NONSIGN_32; // We assume that the MSb after the sign is set. - int shift=30; - while((shift>=0)&&(fixed>>>shift)==0) - // It's not, apparently + int shift = 30; + while ((shift >= 0) && (fixed >>> shift) == 0) // It's not, apparently + { shift--; + } // Positions 0-15 are fractional, anything above 15 is integer. // Return two's complement shift. - return (30-shift); - + return (30 - shift); + } - - public static double toDouble(int fixed){ - - + + public static double toDouble(int fixed) { + // Remember sign. - - long fx=fixed; - fx<<=32; - long sign=(long)fx&SIGN_64; - - if (fixed<0) { - fixed=-fixed; - fx=-fx; - } - long exp=findShift(fixed); + long fx = fixed; + fx <<= 32; + long sign = (long) fx & SIGN_64; + + if (fixed < 0) { + fixed = -fixed; + fx = -fx; + } + long exp = findShift(fixed); // First shift to left to "swallow" sign and implicit 1. - long bits=(fx<<(exp+2))>>>12; - long result=sign|(((14-exp)+1023)<<52)|bits; + long bits = (fx << (exp + 2)) >>> 12; + long result = sign | (((14 - exp) + 1023) << 52) | bits; return Double.longBitsToDouble(result); } - - public static int toFixed(float fl){ + + public static int toFixed(float fl) { // Get the raw bits. - int flbits=Float.floatToRawIntBits(fl); + int flbits = Float.floatToRawIntBits(fl); // Remember sign. - int sign=flbits&SIGN_32; + int sign = flbits & SIGN_32; // Join together: the implcit 1 and the mantissa bits. // We now have the "denormalized" value. - int denorm=IMPLICIT_32|(flbits&MANTISSA_32); + int denorm = IMPLICIT_32 | (flbits & MANTISSA_32); // Get exponent...acceptable values are (-15 ~ 15), else wrap around (use only sign and lowest 4 bits). - int exp=(((flbits&EXP_32)>>23)-127)&0x8000000F; + int exp = (((flbits & EXP_32) >> 23) - 127) & 0x8000000F; /* Remember, leftmost "1" will be at position 23. * So for an exponent of 0, we must shift to position 16. * For positive exponents in general, we must shift -7 + exp. @@ -92,25 +94,26 @@ public static int toFixed(float fl){ * */ int result; - if ((exp-7)>=0) - result=sign|(denorm<<(exp-7)); - else - result=sign|(denorm>>>(7-exp)); - return result; + if ((exp - 7) >= 0) { + result = sign | (denorm << (exp - 7)); + } else { + result = sign | (denorm >>> (7 - exp)); } - - public static int toFixed(double fl){ - + return result; + } + + public static int toFixed(double fl) { + // Get the raw bits. - long flbits=Double.doubleToRawLongBits(fl); + long flbits = Double.doubleToRawLongBits(fl); // Remember sign. - int sign=(int)((flbits&SIGN_64)>>32); + int sign = (int) ((flbits & SIGN_64) >> 32); // Join together: the implcit 1 and the mantissa bits. // We now have the "denormalized" value. - long denorm=IMPLICIT_64|(flbits&MANTISSA_64); + long denorm = IMPLICIT_64 | (flbits & MANTISSA_64); //System.out.println("Denorm"+Integer.toBinaryString(denorm)); // Get exponent...acceptable values are (-15 ~ 15), else wrap around (use only sign and lowest 4 bits). - int exp=(int)(((flbits&EXP_64)>>52)-1023)&0x8000000F; + int exp = (int) (((flbits & EXP_64) >> 52) - 1023) & 0x8000000F; /* Remember, leftmost "1" will be at position 53. * So for an exponent of 0, we must shift to position 16. * For positive exponents in general, we must shift -37 + exp. @@ -120,12 +123,13 @@ public static int toFixed(double fl){ * */ int result; - if ((exp-36)>=0) - result=(int) (sign|(denorm<<(exp-36))); - else - result=(int) (sign|(denorm>>>(36-exp))); + if ((exp - 36) >= 0) { + result = (int) (sign | (denorm << (exp - 36))); + } else { + result = (int) (sign | (denorm >>> (36 - exp))); + } //int result=sign|(IMPLICIT_32|(mantissa<<(exp-127)))<<8; return result; - } - + } + } diff --git a/src/m/IDoomMenu.java b/src/m/IDoomMenu.java index 042cbf31..e35b76ad 100644 --- a/src/m/IDoomMenu.java +++ b/src/m/IDoomMenu.java @@ -1,7 +1,11 @@ package m; import doom.SourceCode.M_Menu; -import static doom.SourceCode.M_Menu.*; +import static doom.SourceCode.M_Menu.M_Drawer; +import static doom.SourceCode.M_Menu.M_Init; +import static doom.SourceCode.M_Menu.M_Responder; +import static doom.SourceCode.M_Menu.M_StartControlPanel; +import static doom.SourceCode.M_Menu.M_Ticker; import doom.event_t; // Emacs style mode select -*- C++ -*- @@ -25,17 +29,14 @@ // Menu widget stuff, episode selection and such. // // ----------------------------------------------------------------------------- - /** * */ - public interface IDoomMenu { // // MENUS // - /** * Called by main loop, saves config file and calls I_Quit when user exits. * Even when the menu is not displayed, this can resize the view and change @@ -72,13 +73,12 @@ public interface IDoomMenu { public boolean getShowMessages(); public void setShowMessages(boolean val); - + public int getScreenBlocks(); - + public void setScreenBlocks(int val); - + public int getDetailLevel(); - void ClearMenus(); + void ClearMenus(); } - \ No newline at end of file diff --git a/src/m/IRandom.java b/src/m/IRandom.java index 3f4f05aa..7896c4a1 100644 --- a/src/m/IRandom.java +++ b/src/m/IRandom.java @@ -4,12 +4,20 @@ import p.ActiveStates; public interface IRandom { - public int P_Random (); - public int M_Random (); - public void ClearRandom (); - public int getIndex(); - public int P_Random(int caller); - public int P_Random(String message); - public int P_Random(ActiveStates caller, int sequence); - public int P_Random(ActiveStates caller, mobjtype_t type,int sequence); + + public int P_Random(); + + public int M_Random(); + + public void ClearRandom(); + + public int getIndex(); + + public int P_Random(int caller); + + public int P_Random(String message); + + public int P_Random(ActiveStates caller, int sequence); + + public int P_Random(ActiveStates caller, mobjtype_t type, int sequence); } diff --git a/src/m/ISyncLogger.java b/src/m/ISyncLogger.java index 8dd1ded9..845c5bf0 100644 --- a/src/m/ISyncLogger.java +++ b/src/m/ISyncLogger.java @@ -4,8 +4,9 @@ public interface ISyncLogger { - public void debugStart() throws IOException; - public void debugEnd(); - public void sync(String format, Object ... args); -} + public void debugStart() throws IOException; + + public void debugEnd(); + public void sync(String format, Object... args); +} diff --git a/src/m/Menu.java b/src/m/Menu.java index 57945f87..b9005cdb 100644 --- a/src/m/Menu.java +++ b/src/m/Menu.java @@ -8,7 +8,9 @@ import static data.dstrings.SAVEGAMENAME; import static data.dstrings.endmsg; import data.sounds.sfxenum_t; -import defines.*; +import defines.Language_t; +import defines.gamestate_t; +import defines.skill_t; import doom.CommandVariable; import doom.DoomMain; import doom.SourceCode; @@ -45,38 +47,38 @@ import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import rr.patch_t; import timing.DelegateTicker; import utils.C2JUtils; -import static v.renderers.DoomScreen.*; +import static v.renderers.DoomScreen.FG; import w.DoomIO; public class Menu extends AbstractDoomMenu { - ////////////////// CONSTRUCTOR //////////////// - - public Menu(DoomMain DOOM){ - super(DOOM); + private static final Logger LOGGER = Loggers.getLogger(Menu.class.getName()); + + ////////////////// CONSTRUCTOR //////////////// + public Menu(DoomMain DOOM) { + super(DOOM); } /** The fonts ... must "peg" them to those from HU */ patch_t[] hu_font = new patch_t[HU_FONTSIZE]; /** WTF?! */ - boolean message_dontfuckwithme; - - // int mouseSensitivity; // has default + // int mouseSensitivity; // has default /** Show messages has default, 0 = off, 1 = on */ - - private boolean showMessages=false; + private boolean showMessages = false; /** * showMessages can be read outside of Menu, but not modified. Menu has the * actual C definition (not declaration) */ - @Override public boolean getShowMessages() { return showMessages; @@ -84,13 +86,13 @@ public boolean getShowMessages() { @Override public void setShowMessages(boolean val) { - this.showMessages=val; + this.showMessages = val; } - + /** Blocky mode, has default, 0 = high, 1 = normal */ int detailLevel; - int screenblocks=10; // has default + int screenblocks = 10; // has default /** temp for screenblocks (0-9) */ int screenSize; @@ -115,7 +117,6 @@ public void setShowMessages(boolean val) { /** Probably I need some MessageRoutine interface at this point? */ public MenuRoutine messageRoutine; - /** we are going to be entering a savegame string */ boolean saveStringEnter; @@ -129,7 +130,6 @@ public void setShowMessages(boolean val) { boolean inhelpscreens; //int menuactive; - protected static final int SKULLXOFF = -32; protected static final int LINEHEIGHT = 16; @@ -141,7 +141,6 @@ public void setShowMessages(boolean val) { // // MENU TYPEDEFS // - /** menu item skull is on */ short itemOn; @@ -155,7 +154,7 @@ public void setShowMessages(boolean val) { * graphic name of skulls warning: initializer-string for array of chars is * too long */ - private static String[] skullName = { "M_SKULL1", "M_SKULL2" }; + private static String[] skullName = {"M_SKULL1", "M_SKULL2"}; /** current menudef */ // MAES: pointer? array? @@ -164,10 +163,8 @@ public void setShowMessages(boolean val) { // // DOOM MENU // - // MAES: was an enum called "main_e" used purely as numerals. No need for // strong typing. - /** * MenuRoutine class definitions, replacing "function pointers". */ @@ -178,12 +175,10 @@ public void setShowMessages(boolean val) { QuitResponse, QuickLoadResponse, QuickSaveResponse, ReadThis, ReadThis2; /** DrawRoutine class definitions, replacing "function pointers". */ - - DrawRoutine DrawEpisode, DrawLoad,DrawMainMenu,DrawNewGame,DrawOptions, - DrawReadThis1, DrawReadThis2, DrawSave, DrawSound; + DrawRoutine DrawEpisode, DrawLoad, DrawMainMenu, DrawNewGame, DrawOptions, + DrawReadThis1, DrawReadThis2, DrawSave, DrawSound; /** Initialize menu routines first */ - private void initMenuRoutines() { ChangeMessages = new M_ChangeMessages(); ChangeDetail = new M_ChangeDetail(); @@ -192,32 +187,30 @@ private void initMenuRoutines() { EndGame = new M_EndGame(); EndGameResponse = new M_EndGameResponse(); Episode = new M_Episode(); - FinishReadThis=new M_FinishReadThis(); - LoadGame=new M_LoadGame(); - LoadSelect=new M_LoadSelect(); - MusicVol=new M_MusicVol(); + FinishReadThis = new M_FinishReadThis(); + LoadGame = new M_LoadGame(); + LoadSelect = new M_LoadSelect(); + MusicVol = new M_MusicVol(); NewGame = new M_NewGame(); Options = new M_Options(); - QuitDOOM = new M_QuitDOOM(); QuickLoadResponse = new M_QuickLoadResponse(); - QuickSaveResponse= new M_QuickSaveResponse(); + QuickSaveResponse = new M_QuickSaveResponse(); QuitResponse = new M_QuitResponse(); - + ReadThis = new M_ReadThis(); ReadThis2 = new M_ReadThis2(); - - SaveGame=new M_SaveGame(); - SaveSelect= new M_SaveSelect(); - SfxVol=new M_SfxVol(); + + SaveGame = new M_SaveGame(); + SaveSelect = new M_SaveSelect(); + SfxVol = new M_SfxVol(); SizeDisplay = new M_SizeDisplay(); Sound = new M_Sound(); VerifyNightmare = new M_VerifyNightmare(); } /** Then drawroutines */ - private void initDrawRoutines() { DrawEpisode = new M_DrawEpisode(); DrawNewGame = new M_DrawNewGame(); @@ -226,20 +219,19 @@ private void initDrawRoutines() { DrawOptions = new M_DrawOptions(); DrawLoad = new M_DrawLoad(); DrawSave = new M_DrawSave(); - DrawSound=new M_DrawSound(); + DrawSound = new M_DrawSound(); DrawMainMenu = new M_DrawMainMenu(); } /** Menuitem definitions. A "menu" can consist of multiple menuitems */ - menuitem_t[] MainMenu,EpisodeMenu,NewGameMenu, OptionsMenu,ReadMenu1,ReadMenu2,SoundMenu,LoadMenu,SaveMenu; - + menuitem_t[] MainMenu, EpisodeMenu, NewGameMenu, OptionsMenu, ReadMenu1, ReadMenu2, SoundMenu, LoadMenu, SaveMenu; + /** Actual menus. Each can point to an array of menuitems */ - menu_t MainDef, EpiDef,NewDef,OptionsDef,ReadDef1, ReadDef2,SoundDef,LoadDef,SaveDef; - + menu_t MainDef, EpiDef, NewDef, OptionsDef, ReadDef1, ReadDef2, SoundDef, LoadDef, SaveDef; + /** First initialize those */ - - private void initMenuItems(){ - MainMenu = new menuitem_t[] { + private void initMenuItems() { + MainMenu = new menuitem_t[]{ new menuitem_t(1, "M_NGAME", NewGame, SC_N), new menuitem_t(1, "M_OPTION", Options, SC_O), new menuitem_t(1, "M_LOADG", LoadGame, SC_L), @@ -254,7 +246,7 @@ private void initMenuItems(){ // // EPISODE SELECT // - EpisodeMenu = new menuitem_t[] { + EpisodeMenu = new menuitem_t[]{ new menuitem_t(1, "M_EPI1", Episode, SC_K), new menuitem_t(1, "M_EPI2", Episode, SC_T), new menuitem_t(1, "M_EPI3", Episode, SC_I), @@ -262,18 +254,18 @@ private void initMenuItems(){ }; EpiDef = new menu_t( - ep_end, // # of menu items - MainDef, // previous menu - EpisodeMenu, // menuitem_t -> - DrawEpisode, // drawing routine -> - 48, 63, // x,y - ep1 // lastOn + ep_end, // # of menu items + MainDef, // previous menu + EpisodeMenu, // menuitem_t -> + DrawEpisode, // drawing routine -> + 48, 63, // x,y + ep1 // lastOn ); // // NEW GAME // - NewGameMenu = new menuitem_t[] { + NewGameMenu = new menuitem_t[]{ new menuitem_t(1, "M_JKILL", ChooseSkill, SC_I), new menuitem_t(1, "M_ROUGH", ChooseSkill, SC_H), new menuitem_t(1, "M_HURT", ChooseSkill, SC_H), @@ -282,18 +274,18 @@ private void initMenuItems(){ }; NewDef = new menu_t( - newg_end, // # of menu items - EpiDef, // previous menu - NewGameMenu, // menuitem_t -> - DrawNewGame, // drawing routine -> - 48, 63, // x,y - hurtme // lastOn + newg_end, // # of menu items + EpiDef, // previous menu + NewGameMenu, // menuitem_t -> + DrawNewGame, // drawing routine -> + 48, 63, // x,y + hurtme // lastOn ); // // OPTIONS MENU // - OptionsMenu = new menuitem_t[] { + OptionsMenu = new menuitem_t[]{ new menuitem_t(1, "M_ENDGAM", EndGame, SC_3), new menuitem_t(1, "M_MESSG", ChangeMessages, SC_M), new menuitem_t(1, "M_DETAIL", ChangeDetail, SC_G), @@ -319,7 +311,7 @@ private void initMenuItems(){ // // SOUND VOLUME MENU // - SoundMenu = new menuitem_t[] { + SoundMenu = new menuitem_t[]{ new menuitem_t(2, "M_SFXVOL", SfxVol, SC_S), new menuitem_t(-1, "", null), new menuitem_t(2, "M_MUSVOL", MusicVol, SC_M), @@ -344,7 +336,7 @@ private void initMenuItems(){ // // SAVE GAME MENU // - SaveMenu = new menuitem_t[] { + SaveMenu = new menuitem_t[]{ new menuitem_t(1, "", SaveSelect, SC_1), new menuitem_t(1, "", SaveSelect, SC_2), new menuitem_t(1, "", SaveSelect, SC_3), @@ -355,12 +347,11 @@ private void initMenuItems(){ SaveDef = new menu_t(load_end, MainDef, SaveMenu, DrawSave, 80, 54, 0); } - + /** * M_ReadSaveStrings * read the strings from the savegame files */ - public void ReadSaveStrings() { DataInputStream handle; int count; @@ -368,15 +359,16 @@ public void ReadSaveStrings() { String name; for (i = 0; i < load_end; i++) { - if (DOOM.cVarManager.bool(CommandVariable.CDROM)) + if (DOOM.cVarManager.bool(CommandVariable.CDROM)) { name = "c:\\doomdata\\" + SAVEGAMENAME + (i) + ".dsg"; - else + } else { name = SAVEGAMENAME + (i) + ".dsg"; + } try { handle = new DataInputStream(new BufferedInputStream(new FileInputStream(name))); - savegamestrings[i] = - DoomIO.readString(handle,SAVESTRINGSIZE).toCharArray(); + savegamestrings[i] + = DoomIO.readString(handle, SAVESTRINGSIZE).toCharArray(); handle.close(); LoadMenu[i].status = 1; } catch (IOException e) { @@ -413,7 +405,6 @@ private void DrawSaveLoadBorder(int x, int y) { * @param thermWidth * @param thermDot */ - public void DrawThermo(int x, int y, int thermWidth, int thermDot) { int xx = x; DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("M_THERML"), DOOM.vs, xx, y); @@ -438,20 +429,21 @@ public void DrawSelCell(menu_t menu, int item) { // M_SaveGame & Cie. // public class M_DrawSave implements DrawRoutine { - @Override - public void invoke(){ - int i; - DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("M_SAVEG"), DOOM.vs, 72, 28); - for (i = 0; i < load_end; i++) { - DrawSaveLoadBorder(LoadDef.x, LoadDef.y + LINEHEIGHT * i); - WriteText(LoadDef.x, LoadDef.y + LINEHEIGHT * i, savegamestrings[i]); - } - if (saveStringEnter) { - i = StringWidth(savegamestrings[saveSlot]); - WriteText(LoadDef.x + i, LoadDef.y + LINEHEIGHT * saveSlot, "_"); + @Override + public void invoke() { + int i; + DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("M_SAVEG"), DOOM.vs, 72, 28); + for (i = 0; i < load_end; i++) { + DrawSaveLoadBorder(LoadDef.x, LoadDef.y + LINEHEIGHT * i); + WriteText(LoadDef.x, LoadDef.y + LINEHEIGHT * i, savegamestrings[i]); + } + + if (saveStringEnter) { + i = StringWidth(savegamestrings[saveSlot]); + WriteText(LoadDef.x + i, LoadDef.y + LINEHEIGHT * saveSlot, "_"); + } } - } } /** @@ -459,31 +451,32 @@ public void invoke(){ * * @param slot */ - public void DoSave(int slot) { DOOM.SaveGame(slot, new String(savegamestrings[slot])); ClearMenus(); // PICK QUICKSAVE SLOT YET? - if (quickSaveSlot == -2) + if (quickSaveSlot == -2) { quickSaveSlot = slot; + } } /** * User wants to save. Start string input for M_Responder */ - class M_SaveSelect implements MenuRoutine { + @Override public void invoke(int choice) { // we are going to be intercepting all chars - //System.out.println("ACCEPTING typing input"); + //System.out.println("ACCEPTING typing input"); saveStringEnter = true; saveSlot = choice; C2JUtils.strcpy(saveOldString, savegamestrings[choice]); - if (C2JUtils.strcmp(savegamestrings[choice], EMPTYSTRING)) + if (C2JUtils.strcmp(savegamestrings[choice], EMPTYSTRING)) { savegamestrings[choice][0] = 0; + } saveCharIndex = C2JUtils.strlen(savegamestrings[choice]); } } @@ -492,6 +485,7 @@ public void invoke(int choice) { * Selected from DOOM menu */ class M_SaveGame implements MenuRoutine { + @Override public void invoke(int choice) { if (!DOOM.usergame) { @@ -499,8 +493,9 @@ public void invoke(int choice) { return; } - if (DOOM.gamestate != gamestate_t.GS_LEVEL) + if (DOOM.gamestate != gamestate_t.GS_LEVEL) { return; + } SetupNextMenu(SaveDef); ReadSaveStrings(); @@ -513,6 +508,7 @@ public void invoke(int choice) { private String tempstring; class M_QuickSaveResponse implements MenuRoutine { + @Override public void invoke(int ch) { if (ch == 'y') { @@ -528,8 +524,9 @@ private void QuickSave() { return; } - if (DOOM.gamestate != gamestate_t.GS_LEVEL) + if (DOOM.gamestate != gamestate_t.GS_LEVEL) { return; + } if (quickSaveSlot < 0) { StartControlPanel(); @@ -538,14 +535,15 @@ private void QuickSave() { quickSaveSlot = -2; // means to pick a slot now return; } - tempstring = String.format(QSPROMPT,C2JUtils.nullTerminatedString(savegamestrings[quickSaveSlot])); - StartMessage(tempstring,this.QuickSaveResponse,true); + tempstring = String.format(QSPROMPT, C2JUtils.nullTerminatedString(savegamestrings[quickSaveSlot])); + StartMessage(tempstring, this.QuickSaveResponse, true); } // // M_QuickLoad // class M_QuickLoadResponse implements MenuRoutine { + @Override public void invoke(int ch) { if (ch == 'y') { @@ -556,15 +554,18 @@ public void invoke(int ch) { } class M_QuitResponse implements MenuRoutine { + @Override public void invoke(int ch) { - if (ch != 'y') + if (ch != 'y') { return; + } if (!DOOM.netgame) { - if (DOOM.isCommercial()) + if (DOOM.isCommercial()) { DOOM.doomSound.StartSound(null, quitsounds2[(DOOM.gametic >> 2) & 7]); - else + } else { DOOM.doomSound.StartSound(null, quitsounds[(DOOM.gametic >> 2) & 7]); + } // TI.WaitVBL(105); } DOOM.doomSystem.Quit(); @@ -586,6 +587,7 @@ public void QuickLoad() { } class M_Sound implements MenuRoutine { + @Override public void invoke(int choice) { SetupNextMenu(SoundDef); @@ -593,38 +595,44 @@ public void invoke(int choice) { } class M_SfxVol implements MenuRoutine { + @Override public void invoke(int choice) { switch (choice) { - case 0: - if (DOOM.snd_SfxVolume != 0) - DOOM.snd_SfxVolume--; - break; - case 1: - if (DOOM.snd_SfxVolume < 15) - DOOM.snd_SfxVolume++; - break; + case 0: + if (DOOM.snd_SfxVolume != 0) { + DOOM.snd_SfxVolume--; + } + break; + case 1: + if (DOOM.snd_SfxVolume < 15) { + DOOM.snd_SfxVolume++; + } + break; } - DOOM.doomSound.SetSfxVolume(DOOM.snd_SfxVolume *8); + DOOM.doomSound.SetSfxVolume(DOOM.snd_SfxVolume * 8); } } class M_MusicVol implements MenuRoutine { + @Override public void invoke(int choice) { switch (choice) { - case 0: - if (DOOM.snd_MusicVolume != 0) - DOOM.snd_MusicVolume--; - break; - case 1: - if (DOOM.snd_MusicVolume < 15) - DOOM.snd_MusicVolume++; - break; + case 0: + if (DOOM.snd_MusicVolume != 0) { + DOOM.snd_MusicVolume--; + } + break; + case 1: + if (DOOM.snd_MusicVolume < 15) { + DOOM.snd_MusicVolume++; + } + break; } - DOOM.doomSound.SetMusicVolume(DOOM.snd_MusicVolume*8); + DOOM.doomSound.SetMusicVolume(DOOM.snd_MusicVolume * 8); } } @@ -634,10 +642,12 @@ public void invoke(int choice) { private int epi; class M_VerifyNightmare implements MenuRoutine { + @Override public void invoke(int ch) { - if (ch != 'y') + if (ch != 'y') { return; + } DOOM.DeferedInitNew(skill_t.sk_nightmare, epi + 1, 1); ClearMenus(); @@ -647,8 +657,8 @@ public void invoke(int ch) { /** * M_ReadThis */ - class M_ReadThis implements MenuRoutine { + @Override public void invoke(int choice) { choice = 0; @@ -657,6 +667,7 @@ public void invoke(int choice) { } class M_ReadThis2 implements MenuRoutine { + @Override public void invoke(int choice) { choice = 0; @@ -665,6 +676,7 @@ public void invoke(int choice) { } class M_FinishReadThis implements MenuRoutine { + @Override public void invoke(int choice) { choice = 0; @@ -675,62 +687,68 @@ public void invoke(int choice) { // // M_QuitDOOM // - class M_QuitDOOM implements MenuRoutine { + @Override public void invoke(int choice) { // We pick index 0 which is language sensitive, // or one at random, between 1 and maximum number. - if (DOOM.language != Language_t.english) + if (DOOM.language != Language_t.english) { endstring = endmsg[0] + "\n\n" + DOSY; - else - endstring = - endmsg[(DOOM.gametic % (NUM_QUITMESSAGES - 2)) + 1] + "\n\n" - + DOSY; + } else { + endstring + = endmsg[(DOOM.gametic % (NUM_QUITMESSAGES - 2)) + 1] + "\n\n" + + DOSY; + } StartMessage(endstring, QuitResponse, true); } } class M_QuitGame implements MenuRoutine { + @Override public void invoke(int ch) { - if (ch != 'y') + if (ch != 'y') { return; + } if (!DOOM.netgame) { - if (DOOM.isCommercial()) - DOOM.doomSound.StartSound(null,quitsounds2[(DOOM.gametic>>2)&7]); - else - DOOM.doomSound.StartSound(null,quitsounds[(DOOM.gametic>>2)&7]); + if (DOOM.isCommercial()) { + DOOM.doomSound.StartSound(null, quitsounds2[(DOOM.gametic >> 2) & 7]); + } else { + DOOM.doomSound.StartSound(null, quitsounds[(DOOM.gametic >> 2) & 7]); + } DOOM.doomSystem.WaitVBL(105); } - DOOM.doomSystem.Quit (); + DOOM.doomSystem.Quit(); } } class M_SizeDisplay implements MenuRoutine { + @Override public void invoke(int choice) { switch (choice) { - case 0: - if (screenSize > 0) { - screenblocks--; - screenSize--; - } - break; - case 1: - if (screenSize < 8) { - screenblocks++; - screenSize++; - } - break; + case 0: + if (screenSize > 0) { + screenblocks--; + screenSize--; + } + break; + case 1: + if (screenSize < 8) { + screenblocks++; + screenSize++; + } + break; } - DOOM.sceneRenderer.SetViewSize (screenblocks, detailLevel); + DOOM.sceneRenderer.SetViewSize(screenblocks, detailLevel); } } class M_Options implements MenuRoutine { + @Override public void invoke(int choice) { SetupNextMenu(OptionsDef); @@ -739,6 +757,7 @@ public void invoke(int choice) { } class M_NewGame implements MenuRoutine { + @Override public void invoke(int choice) { if (DOOM.netgame && !DOOM.demoplayback) { @@ -746,10 +765,11 @@ public void invoke(int choice) { return; } - if (DOOM.isCommercial()) + if (DOOM.isCommercial()) { SetupNextMenu(NewDef); - else + } else { SetupNextMenu(EpiDef); + } } } @@ -778,10 +798,11 @@ public int StringWidth(char[] string) { for (i = 0; i < C2JUtils.strlen(string); i++) { c = Character.toUpperCase(string[i]) - HU_FONTSTART; - if (c < 0 || c >= HU_FONTSIZE) + if (c < 0 || c >= HU_FONTSIZE) { w += 4; - else + } else { w += hu_font[c].width; + } } return w; @@ -798,9 +819,11 @@ private int StringHeight(char[] string) { int height = hu_font[0].height; h = height; - for (i = 0; i < string.length; i++) - if (string[i] == '\n') + for (i = 0; i < string.length; i++) { + if (string[i] == '\n') { h += height; + } + } return h; } @@ -815,7 +838,6 @@ private int StringHeight(String string) { /** * Write a string using the hu_font */ - private void WriteText(int x, int y, char[] string) { int w; char[] ch; @@ -828,17 +850,18 @@ private void WriteText(int x, int y, char[] string) { cx = x; cy = y; - while (chptr= HU_FONTSIZE) { cx += 4; @@ -846,9 +869,10 @@ private void WriteText(int x, int y, char[] string) { } w = hu_font[c].width; - if (cx + w > DOOM.vs.getScreenWidth()) + if (cx + w > DOOM.vs.getScreenWidth()) { break; - + } + DOOM.graphicSystem.DrawPatchScaled(FG, hu_font[c], DOOM.vs, cx, cy); cx += w; } @@ -856,8 +880,9 @@ private void WriteText(int x, int y, char[] string) { } private void WriteText(int x, int y, String string) { - if (string == null || string.length() == 0) + if (string == null || string.length() == 0) { return; + } int w; int cx; @@ -869,10 +894,11 @@ private void WriteText(int x, int y, String string) { cx = x; cy = y; - while (chptr DOOM.vs.getScreenWidth()) + if (cx + w > DOOM.vs.getScreenWidth()) { break; + } DOOM.graphicSystem.DrawPatchScaled(FG, hu_font[c], DOOM.vs, cx, cy); cx += w; } @@ -895,7 +922,6 @@ private void WriteText(int x, int y, String string) { } // These belong to the responder. - private int joywait = 0; private int mousewait = 0; @@ -913,8 +939,8 @@ private void WriteText(int x, int y, String string) { @M_Menu.C(M_Responder) public boolean Responder(event_t ev) { final ScanCode sc; - - if (ev.isType(evtype_t.ev_joystick) && joywait < DOOM.ticker.GetTime()) { + + if (DOOM.use_joystick && ev.isType(evtype_t.ev_joystick) && joywait < DOOM.ticker.GetTime()) { // Joystick input sc = ev.mapByJoy(joyEvent -> { ScanCode r = SC_NULL; @@ -943,7 +969,7 @@ public boolean Responder(event_t ev) { } return r; }); - } else if (ev.isType(evtype_t.ev_mouse) && mousewait < DOOM.ticker.GetTime()) { + } else if (DOOM.use_mouse && ev.isType(evtype_t.ev_mouse) && mousewait < DOOM.ticker.GetTime()) { // Mouse input if ((sc = ev.mapByMouse(mouseEvent -> { ScanCode r = SC_NULL; @@ -977,10 +1003,14 @@ public boolean Responder(event_t ev) { mousewait = DOOM.ticker.GetTime() + 15; } return r; - })) == SC_NULL) { return false; } + })) == SC_NULL) { + return false; + } } else if (ev.isType(evtype_t.ev_keydown)) { sc = ev.getSC(); - } else return false; + } else { + return false; + } // Save Game string input if (saveStringEnter) { @@ -995,10 +1025,11 @@ public boolean Responder(event_t ev) { saveStringEnter = false; C2JUtils.strcpy(savegamestrings[saveSlot], saveOldString); break; - case SC_ENTER: + case SC_ENTER: saveStringEnter = false; - if (savegamestrings[saveSlot][0] != 0) + if (savegamestrings[saveSlot][0] != 0) { DoSave(saveSlot); + } break; default: char ch = Character.toUpperCase(sc.c); @@ -1007,10 +1038,9 @@ public boolean Responder(event_t ev) { break; } } - + if (ch >= ' ' && ch <= 0x7F && saveCharIndex < SAVESTRINGSIZE - 1 - && StringWidth(savegamestrings[saveSlot]) < (SAVESTRINGSIZE - 2) * 8) - { + && StringWidth(savegamestrings[saveSlot]) < (SAVESTRINGSIZE - 2) * 8) { savegamestrings[saveSlot][saveCharIndex++] = ch; savegamestrings[saveSlot][saveCharIndex] = 0; } @@ -1027,8 +1057,9 @@ && StringWidth(savegamestrings[saveSlot]) < (SAVESTRINGSIZE - 2) * 8) DOOM.menuactive = messageLastMenuActive; messageToPrint = false; - if (messageRoutine != null) + if (messageRoutine != null) { messageRoutine.invoke(sc.c); + } DOOM.menuactive = false; // "false" DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchx); @@ -1041,103 +1072,107 @@ && StringWidth(savegamestrings[saveSlot]) < (SAVESTRINGSIZE - 2) * 8) } // F-Keys - if (!DOOM.menuactive){ + if (!DOOM.menuactive) { switch (sc) { - case SC_MINUS: // Screen size down - if (DOOM.automapactive || DOOM.headsUp.chat_on[0]) - return false; - SizeDisplay.invoke(0); - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_stnmov); - return true; + case SC_MINUS: // Screen size down + if (DOOM.automapactive || DOOM.headsUp.chat_on[0]) { + return false; + } + SizeDisplay.invoke(0); + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_stnmov); + return true; - case SC_EQUALS: // Screen size up - if (DOOM.automapactive || DOOM.headsUp.chat_on[0]) - return false; - SizeDisplay.invoke(1); - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_stnmov); - return true; + case SC_EQUALS: // Screen size up + if (DOOM.automapactive || DOOM.headsUp.chat_on[0]) { + return false; + } + SizeDisplay.invoke(1); + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_stnmov); + return true; - case SC_F1: // Help key - StartControlPanel(); + case SC_F1: // Help key + StartControlPanel(); - if (DOOM.isRegistered() || DOOM.isShareware()) - currentMenu = ReadDef2; - else - currentMenu = ReadDef1; - itemOn = 0; - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); - return true; + if (DOOM.isRegistered() || DOOM.isShareware()) { + currentMenu = ReadDef2; + } else { + currentMenu = ReadDef1; + } + itemOn = 0; + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); + return true; - case SC_F2: // Save - StartControlPanel(); - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); - SaveGame.invoke(0); - return true; + case SC_F2: // Save + StartControlPanel(); + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); + SaveGame.invoke(0); + return true; - case SC_F3: // Load - StartControlPanel(); - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); - LoadGame.invoke(0); - return true; + case SC_F3: // Load + StartControlPanel(); + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); + LoadGame.invoke(0); + return true; - case SC_F4: // Sound Volume - StartControlPanel(); - currentMenu = SoundDef; - itemOn = (short) sfx_vol; - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); - return true; + case SC_F4: // Sound Volume + StartControlPanel(); + currentMenu = SoundDef; + itemOn = (short) sfx_vol; + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); + return true; - case SC_F5: // Detail toggle - ChangeDetail.invoke(0); - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); - return true; + case SC_F5: // Detail toggle + ChangeDetail.invoke(0); + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); + return true; - case SC_F6: // Quicksave - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); - QuickSave(); - return true; + case SC_F6: // Quicksave + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); + QuickSave(); + return true; - case SC_F7: // End game - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); - EndGame.invoke(0); - return true; + case SC_F7: // End game + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); + EndGame.invoke(0); + return true; - case SC_F8: // Toggle messages - ChangeMessages.invoke(0); - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); - return true; + case SC_F8: // Toggle messages + ChangeMessages.invoke(0); + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); + return true; - case SC_F9: // Quickload - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); - QuickLoad(); - return true; + case SC_F9: // Quickload + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); + QuickLoad(); + return true; - case SC_F10: // Quit DOOM - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); - QuitDOOM.invoke(0); - return true; + case SC_F10: // Quit DOOM + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_swtchn); + QuitDOOM.invoke(0); + return true; + + case SC_F11: // gamma toggle + int usegamma = DOOM.graphicSystem.getUsegamma(); + usegamma++; + if (usegamma > 4) { + usegamma = 0; + } + DOOM.players[DOOM.consoleplayer].message = gammamsg[usegamma]; + DOOM.graphicSystem.setUsegamma(usegamma); + DOOM.autoMap.Repalette(); + return true; - case SC_F11: // gamma toggle - int usegamma = DOOM.graphicSystem.getUsegamma(); - usegamma++; - if (usegamma > 4) - usegamma = 0; - DOOM.players[DOOM.consoleplayer].message = gammamsg[usegamma]; - DOOM.graphicSystem.setUsegamma(usegamma); - DOOM.autoMap.Repalette(); - return true; - - default: - break; + default: + break; } } else if (sc == SC_F5 && DOOM.ticker instanceof DelegateTicker) { // Toggle ticker ((DelegateTicker) DOOM.ticker).changeTicker(); - System.err.println("Warning! Ticker changed; time reset"); + LOGGER.log(Level.WARNING, "Warning! Ticker changed; time reset"); DOOM.doomSound.StartSound(null, sfxenum_t.sfx_radio); return true; } - + // Pop-up menu? if (!DOOM.menuactive) { if (sc == SC_ESCAPE) { @@ -1328,7 +1363,7 @@ public void ClearMenus() { DOOM.menuactive = false; //Engine.getEngine().window.setMouseCaptured(); DOOM.graphicSystem.forcePalette(); - + // MAES: was commented out :-/ //if (!DM.netgame && DM.usergame && DM.paused) // DM.setPaused(true); @@ -1359,12 +1394,12 @@ public void Ticker() { * M_Init */ public void Init() { - + // Init menus. this.initMenuRoutines(); this.initDrawRoutines(); this.initMenuItems(); - this.hu_font=DOOM.headsUp.getHUFonts(); + this.hu_font = DOOM.headsUp.getHUFonts(); currentMenu = MainDef; DOOM.menuactive = false; @@ -1379,43 +1414,40 @@ public void Init() { // Here we could catch other version dependencies, // like HELP1/2, and four episodes. - switch (DOOM.getGameMode()) { - case freedm: - case freedoom2: - case commercial: - case pack_plut: - case pack_tnt: - // This is used because DOOM 2 had only one HELP - // page. I use CREDIT as second page now, but - // kept this hack for educational purposes. - MainMenu[readthis] = MainMenu[quitdoom]; - MainDef.numitems--; - MainDef.y += 8; - NewDef.prevMenu = MainDef; - ReadDef1.routine = DrawReadThis1; - ReadDef1.x = 330; - ReadDef1.y = 165; - ReadMenu1[0].routine = FinishReadThis; - break; - case shareware: + case freedm: + case freedoom2: + case commercial: + case pack_plut: + case pack_tnt: + // This is used because DOOM 2 had only one HELP + // page. I use CREDIT as second page now, but + // kept this hack for educational purposes. + MainMenu[readthis] = MainMenu[quitdoom]; + MainDef.numitems--; + MainDef.y += 8; + NewDef.prevMenu = MainDef; + ReadDef1.routine = DrawReadThis1; + ReadDef1.x = 330; + ReadDef1.y = 165; + ReadMenu1[0].routine = FinishReadThis; + break; + case shareware: // Episode 2 and 3 are handled, // branching to an ad screen. // We need to remove the fourth episode. - case registered: - EpiDef.numitems--; - break; - case freedoom1: - case retail: + case registered: + EpiDef.numitems--; + break; + case freedoom1: + case retail: // We are fine. - default: - break; + default: + break; } } - - /** * M_DrawText Returns the final X coordinate HU_Init must have been called * to init the font. Unused? @@ -1426,13 +1458,12 @@ public void Init() { * @param string * @return */ - public int DrawText(int x, int y, boolean direct, String string) { int c; int w; int ptr = 0; - - while ((c=string.charAt(ptr)) > 0) { + + while ((c = string.charAt(ptr)) > 0) { c = Character.toUpperCase(c) - HU_FONTSTART; ptr++; if (c < 0 || c > HU_FONTSIZE) { @@ -1441,23 +1472,22 @@ public int DrawText(int x, int y, boolean direct, String string) { } w = hu_font[c].width; - if (x + w > DOOM.vs.getScreenWidth()) + if (x + w > DOOM.vs.getScreenWidth()) { break; - if (direct) + } + if (direct) { DOOM.graphicSystem.DrawPatchScaled(FG, hu_font[c], DOOM.vs, x, y); - else + } else { DOOM.graphicSystem.DrawPatchScaled(FG, hu_font[c], DOOM.vs, x, y); + } x += w; } return x; } - - // ////////////////////////// DRAWROUTINES // ////////////////////////////////// - class M_DrawEpisode implements DrawRoutine { @@ -1471,9 +1501,9 @@ public void invoke() { /** * M_LoadGame & Cie. */ - class M_DrawLoad implements DrawRoutine { + @Override public void invoke() { int i; @@ -1482,7 +1512,7 @@ public void invoke() { for (i = 0; i < load_end; i++) { DrawSaveLoadBorder(LoadDef.x, LoadDef.y + LINEHEIGHT * i); WriteText(LoadDef.x, LoadDef.y + LINEHEIGHT * i, - savegamestrings[i]); + savegamestrings[i]); } } @@ -1490,6 +1520,7 @@ public void invoke() { class M_DrawMainMenu implements DrawRoutine { + @Override public void invoke() { DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("M_DOOM"), DOOM.vs, 94, 2); @@ -1509,20 +1540,20 @@ public void invoke() { class M_DrawOptions implements DrawRoutine { - private final String detailNames[] = { "M_GDHIGH", "M_GDLOW" }; - private final String msgNames[] = { "M_MSGOFF", "M_MSGON" }; + private final String detailNames[] = {"M_GDHIGH", "M_GDLOW"}; + private final String msgNames[] = {"M_MSGOFF", "M_MSGON"}; @Override public void invoke() { DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName("M_OPTTTL"), DOOM.vs, 108, 15); DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName(detailNames[detailLevel]), DOOM.vs, OptionsDef.x + 175, OptionsDef.y + LINEHEIGHT * detail); - DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName(msgNames[showMessages?1:0]), DOOM.vs, OptionsDef.x + 120, OptionsDef.y + LINEHEIGHT * messages); + DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CachePatchName(msgNames[showMessages ? 1 : 0]), DOOM.vs, OptionsDef.x + 120, OptionsDef.y + LINEHEIGHT * messages); DrawThermo(OptionsDef.x, OptionsDef.y + LINEHEIGHT * (mousesens + 1), 10, DOOM.mouseSensitivity); DrawThermo(OptionsDef.x, - OptionsDef.y + LINEHEIGHT * (scrnsize + 1), 9, screenSize); + OptionsDef.y + LINEHEIGHT * (scrnsize + 1), 9, screenSize); } @@ -1532,7 +1563,6 @@ public void invoke() { * Read This Menus * Had a "quick hack to fix romero bug" */ - class M_DrawReadThis1 implements DrawRoutine { @Override @@ -1604,17 +1634,17 @@ public void invoke() { DOOM.graphicSystem.DrawPatchScaled(FG, DOOM.wadLoader.CacheLumpName("M_SVOL", PU_CACHE, patch_t.class), DOOM.vs, 60, 38); DrawThermo(SoundDef.x, SoundDef.y + LINEHEIGHT * (sfx_vol + 1), 16, - DOOM.snd_SfxVolume); + DOOM.snd_SfxVolume); DrawThermo(SoundDef.x, SoundDef.y + LINEHEIGHT * (music_vol + 1), - 16, DOOM.snd_MusicVolume); + 16, DOOM.snd_MusicVolume); } } // /////////////////////////// MENU ROUTINES // /////////////////////////////////// - class M_ChangeDetail implements MenuRoutine { + @Override public void invoke(int choice) { choice = 0; @@ -1622,13 +1652,13 @@ public void invoke(int choice) { // FIXME - does not work. Remove anyway? //System.err.print("M_ChangeDetail: low detail mode n.a.\n"); - //return; - - DOOM.sceneRenderer.SetViewSize (screenblocks, detailLevel); - if (detailLevel==0) DOOM.players[DOOM.consoleplayer].message = englsh.DETAILHI; - else DOOM.players[DOOM.consoleplayer].message = englsh.DETAILLO; - + DOOM.sceneRenderer.SetViewSize(screenblocks, detailLevel); + if (detailLevel == 0) { + DOOM.players[DOOM.consoleplayer].message = englsh.DETAILHI; + } else { + DOOM.players[DOOM.consoleplayer].message = englsh.DETAILLO; + } } } @@ -1637,38 +1667,44 @@ public void invoke(int choice) { * Toggle messages on/off */ class M_ChangeMessages implements MenuRoutine { + @Override public void invoke(int choice) { // warning: unused parameter `int choice' //choice = 0; showMessages = !showMessages; - if (!showMessages) + if (!showMessages) { DOOM.players[DOOM.consoleplayer].message = MSGOFF; - else + } else { DOOM.players[DOOM.consoleplayer].message = MSGON; + } message_dontfuckwithme = true; } } class M_ChangeSensitivity implements MenuRoutine { + @Override public void invoke(int choice) { switch (choice) { - case 0: - if (DOOM.mouseSensitivity != 0) - DOOM.mouseSensitivity--; - break; - case 1: - if (DOOM.mouseSensitivity < 9) - DOOM.mouseSensitivity++; - break; + case 0: + if (DOOM.mouseSensitivity != 0) { + DOOM.mouseSensitivity--; + } + break; + case 1: + if (DOOM.mouseSensitivity < 9) { + DOOM.mouseSensitivity++; + } + break; } } } class M_ChooseSkill implements MenuRoutine { + @Override public void invoke(int choice) { if (choice == nightmare) { @@ -1685,13 +1721,13 @@ public void invoke(int choice) { /** * M_EndGame */ - class M_EndGame implements MenuRoutine { + @Override public void invoke(int choice) { choice = 0; if (!DOOM.usergame) { - DOOM.doomSound.StartSound(null, sfxenum_t.sfx_oof); + DOOM.doomSound.StartSound(null, sfxenum_t.sfx_oof); return; } @@ -1705,10 +1741,12 @@ public void invoke(int choice) { } class M_EndGameResponse implements MenuRoutine { + @Override public void invoke(int ch) { - if (ch != 'y') + if (ch != 'y') { return; + } currentMenu.lastOn = itemOn; ClearMenus(); @@ -1717,6 +1755,7 @@ public void invoke(int ch) { } class M_Episode implements MenuRoutine { + @Override public void invoke(int choice) { @@ -1728,8 +1767,7 @@ public void invoke(int choice) { // Yet another hack... if (!DOOM.isRetail() && (choice > 2)) { - System.err - .print("M_Episode: 4th episode requires UltimateDOOM\n"); + LOGGER.log(Level.WARNING, "M_Episode: 4th episode requires UltimateDOOM"); choice = 0; } @@ -1743,14 +1781,16 @@ public void invoke(int choice) { * User wants to load this game */ class M_LoadSelect implements MenuRoutine { + @Override public void invoke(int choice) { String name; - if (DOOM.cVarManager.bool(CommandVariable.CDROM)) + if (DOOM.cVarManager.bool(CommandVariable.CDROM)) { name = ("c:\\doomdata\\" + SAVEGAMENAME + (choice) + ".dsg"); - else + } else { name = (SAVEGAMENAME + (choice) + ".dsg"); + } DOOM.LoadGame(name); ClearMenus(); } @@ -1760,6 +1800,7 @@ public void invoke(int choice) { * Selected from DOOM menu */ class M_LoadGame implements MenuRoutine { + @Override public void invoke(int choice) { @@ -1774,16 +1815,15 @@ public void invoke(int choice) { } // ////////////////////// VARIOUS CONSTS ////////////////////// - - private static final sfxenum_t[] quitsounds = - { sfxenum_t.sfx_pldeth, sfxenum_t.sfx_dmpain, sfxenum_t.sfx_popain, + private static final sfxenum_t[] quitsounds + = {sfxenum_t.sfx_pldeth, sfxenum_t.sfx_dmpain, sfxenum_t.sfx_popain, sfxenum_t.sfx_slop, sfxenum_t.sfx_telept, sfxenum_t.sfx_posit1, - sfxenum_t.sfx_posit3, sfxenum_t.sfx_sgtatk }; + sfxenum_t.sfx_posit3, sfxenum_t.sfx_sgtatk}; - private static final sfxenum_t[] quitsounds2 = - { sfxenum_t.sfx_vilact, sfxenum_t.sfx_getpow, sfxenum_t.sfx_boscub, + private static final sfxenum_t[] quitsounds2 + = {sfxenum_t.sfx_vilact, sfxenum_t.sfx_getpow, sfxenum_t.sfx_boscub, sfxenum_t.sfx_slop, sfxenum_t.sfx_skeswg, sfxenum_t.sfx_kntdth, - sfxenum_t.sfx_bspact, sfxenum_t.sfx_sgtatk }; + sfxenum_t.sfx_bspact, sfxenum_t.sfx_sgtatk}; /** episodes_e enum */ private static final int ep1 = 0, ep2 = 1, ep3 = 2, ep4 = 3, ep_end = 4; @@ -1793,13 +1833,12 @@ public void invoke(int choice) { load6 = 5, load_end = 6; /** options_e enum; */ - private static final int endgame = 0, messages = 1, detail = 2, scrnsize = 3, option_empty1 = 4, mousesens = 5, option_empty2 = 6, soundvol = 7, opt_end = 8; /** main_e enum; */ - private static final int newgame = 0, options = 1, loadgam = 2, savegame = 3, + private static final int newgame = 0, options = 1, loadgam = 2, savegame = 3, readthis = 4, quitdoom = 5, main_end = 6; /** read_e enum */ @@ -1811,10 +1850,9 @@ public void invoke(int choice) { /** newgame_e enum;*/ public static final int killthings = 0, toorough = 1, hurtme = 2, violence = 3, nightmare = 4, newg_end = 5; - - private static final String[] gammamsg = { GAMMALVL0, - GAMMALVL1, GAMMALVL2, GAMMALVL3, GAMMALVL4 }; + private static final String[] gammamsg = {GAMMALVL0, + GAMMALVL1, GAMMALVL2, GAMMALVL3, GAMMALVL4}; /** sound_e enum */ static final int sfx_vol = 0, sfx_empty1 = 1, music_vol = 2, sfx_empty2 = 3, @@ -1822,16 +1860,16 @@ public void invoke(int choice) { @Override public void setScreenBlocks(int val) { - this.screenblocks=val; - } - - @Override - public int getScreenBlocks() { - return this.screenblocks; - } - - @Override - public int getDetailLevel() { - return this.detailLevel; - } -} \ No newline at end of file + this.screenblocks = val; + } + + @Override + public int getScreenBlocks() { + return this.screenblocks; + } + + @Override + public int getDetailLevel() { + return this.detailLevel; + } +} diff --git a/src/m/MenuMisc.java b/src/m/MenuMisc.java index b5c8ab4e..236cb662 100644 --- a/src/m/MenuMisc.java +++ b/src/m/MenuMisc.java @@ -16,7 +16,10 @@ import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.Arrays; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.imageio.ImageIO; +import mochadoom.Loggers; import w.IWritableDoomObject; // Emacs style mode select -*- C++ -*- @@ -43,19 +46,19 @@ // PCX Screenshots. // //----------------------------------------------------------------------------- +public abstract class MenuMisc { -public abstract class MenuMisc{ + private static final Logger LOGGER = Loggers.getLogger(MenuMisc.class.getName()); public static final String rcsid = "$Id: MenuMisc.java,v 1.29 2012/09/24 17:16:22 velktron Exp $"; - + // // SCREEN SHOTS // - public static boolean WriteFile(String name, byte[] source, int length) { OutputStream handle; try { - handle = new FileOutputStream(name); + handle = new FileOutputStream(name); handle.write(source, 0, length); handle.close(); } catch (Exception e) { @@ -80,7 +83,6 @@ public static boolean WriteFile(String name, IWritableDoomObject source) { return true; } - /** M_ReadFile * This version returns a variable-size ByteBuffer, so * we don't need to know a-priori how much stuff to read. @@ -107,7 +109,7 @@ public static ByteBuffer ReadFile(String name) { /** M_ReadFile */ public static int ReadFile(String name, byte[] buffer) { - BufferedInputStream handle; + BufferedInputStream handle; int count, length; // struct stat fileinfo; byte[] buf; @@ -118,96 +120,91 @@ public static int ReadFile(String name, byte[] buffer) { count = handle.read(buf); handle.close(); - if (count < length) + if (count < length) { throw new Exception("Read only " + count + " bytes out of " - + length); + + length); + } } catch (Exception e) { DoomSystem.MiscError("Couldn't read file %s (%s)", name, e.getMessage()); return -1; } - System.arraycopy(buf, 0, buffer, 0, Math.min(count,buffer.length)); + System.arraycopy(buf, 0, buffer, 0, Math.min(count, buffer.length)); return length; } // - // WritePCXfile - // - public static void - WritePCXfile - ( String filename, - byte[] data, - int width, - int height, - byte[] palette ) - { - int length; - pcx_t pcx; - byte[] pack; - - pcx = new pcx_t(); - pack=new byte[width*height*2]; // allocate that much data, just in case. + // WritePCXfile + // + public static void + WritePCXfile(String filename, + byte[] data, + int width, + int height, + byte[] palette) { + int length; + pcx_t pcx; + byte[] pack; - pcx.manufacturer = 0x0a; // PCX id - pcx.version = 5; // 256 color - pcx.encoding = 1; // uncompressed - pcx.bits_per_pixel = 8; // 256 color - pcx.xmin = 0; - pcx.ymin = 0; - pcx.xmax = (char) (width-1); - pcx.ymax = (char) (height-1); - pcx.hres = (char) width; - pcx.vres = (char) height; - // memset (pcx->palette,0,sizeof(pcx->palette)); - pcx.color_planes = 1; // chunky image - pcx.bytes_per_line = (char) width; - pcx.palette_type = 2; // not a grey scale - //memset (pcx->filler,0,sizeof(pcx->filler)); + pcx = new pcx_t(); + pack = new byte[width * height * 2]; // allocate that much data, just in case. + pcx.manufacturer = 0x0a; // PCX id + pcx.version = 5; // 256 color + pcx.encoding = 1; // uncompressed + pcx.bits_per_pixel = 8; // 256 color + pcx.xmin = 0; + pcx.ymin = 0; + pcx.xmax = (char) (width - 1); + pcx.ymax = (char) (height - 1); + pcx.hres = (char) width; + pcx.vres = (char) height; + // memset (pcx->palette,0,sizeof(pcx->palette)); + pcx.color_planes = 1; // chunky image + pcx.bytes_per_line = (char) width; + pcx.palette_type = 2; // not a grey scale + //memset (pcx->filler,0,sizeof(pcx->filler)); + + // pack the image + //pack = &pcx->data; + int p_pack = 0; + + for (int i = 0; i < width * height; i++) { + if ((data[i] & 0xc0) != 0xc0) { + pack[p_pack++] = data[i]; + } else { + pack[p_pack++] = (byte) 0xc1; + pack[p_pack++] = data[i]; + } + } + + // write the palette + pack[p_pack++] = 0x0c; // palette ID byte + for (int i = 0; i < 768; i++) { + pack[p_pack++] = palette[i]; + } + + // write output file + length = p_pack; + pcx.data = Arrays.copyOf(pack, length); + + DataOutputStream f = null; + try { + f = new DataOutputStream(new FileOutputStream(filename)); + + } catch (FileNotFoundException e) { + LOGGER.log(Level.SEVERE, "WritePCXfile: not found", e); + } + + try { + //f.setLength(0); + pcx.write(f); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, "WritePCXfile: I/O error", e); + } - // pack the image - //pack = &pcx->data; - int p_pack=0; - - for (int i=0 ; i> SETTINGS_MAP = new HashMap<>(); - + static { Arrays.stream(values()).forEach(Settings::updateConfig); } @@ -139,7 +155,7 @@ > Settings(Files config, final T defaultValue) { this.valueType = defaultValue.getClass(); this.configBase = config; } - + Settings(Files config, final String defaultValue) { this.defaultValue = defaultValue; this.valueType = String.class; @@ -179,11 +195,11 @@ > Settings(Files config, final T defaultValue) { public final Class valueType; public final Object defaultValue; private Files configBase; - + public boolean is(Object obj) { return Engine.getConfig().equals(obj); } - + public ConfigManager.UpdateStatus hasChange(boolean b) { configBase.changed = configBase.changed || b; return b ? ConfigManager.UpdateStatus.UPDATED : ConfigManager.UpdateStatus.UNCHANGED; @@ -197,17 +213,20 @@ public void rebase(Files newConfig) { configBase = newConfig; updateConfig(); } - + public Optional quoteType() { - if (valueType == String.class) + if (valueType == String.class) { return Optional.of(QuoteType.DOUBLE); - else if (valueType == Character.class) + } else if (valueType == Character.class) { return Optional.of(QuoteType.SINGLE); - + } + return Optional.empty(); } - - public enum LOS {Vanilla, Boom} + + public enum LOS { + Vanilla, Boom + } private void updateConfig() { SETTINGS_MAP.compute(configBase, (c, list) -> { @@ -216,7 +235,7 @@ private void updateConfig() { } else { list.add(this); } - + return list; }); } diff --git a/src/m/Swap.java b/src/m/Swap.java index 94d156f7..d1eddbce 100644 --- a/src/m/Swap.java +++ b/src/m/Swap.java @@ -23,48 +23,40 @@ // built-in endianness settings), but they are still used occasionally. // //----------------------------------------------------------------------------- - -public final class Swap{ - +public final class Swap { // Swap 16bit, that is, MSB and LSB byte. -public final static short SHORT(short x) -{ - // No masking with 0xFF should be necessary. - // MAES: necessary with java due to sign trailing. - - return (short) ((short) ((x>>>8)&0xFF) | (x<<8)); -} + public final static short SHORT(short x) { + // No masking with 0xFF should be necessary. + // MAES: necessary with java due to sign trailing. + + return (short) ((short) ((x >>> 8) & 0xFF) | (x << 8)); + } //Swap 16bit, that is, MSB and LSB byte. -public final static short SHORT(char x) -{ - // No masking with 0xFF should be necessary. - // MAES: necessary with java due to sign trailing. - - return (short) ((short) ((x>>>8)&0xFF) | (x<<8)); -} + public final static short SHORT(char x) { + // No masking with 0xFF should be necessary. + // MAES: necessary with java due to sign trailing. + + return (short) ((short) ((x >>> 8) & 0xFF) | (x << 8)); + } //Swap 16bit, that is, MSB and LSB byte. -public final static char USHORT(char x) -{ - // No masking with 0xFF should be necessary. - // MAES: necessary with java due to sign trailing. - - return (char) ((char) ((x>>>8)&0xFF) | (x<<8)); -} + public final static char USHORT(char x) { + // No masking with 0xFF should be necessary. + // MAES: necessary with java due to sign trailing. + return (char) ((char) ((x >>> 8) & 0xFF) | (x << 8)); + } // Swapping 32bit. // Maes: the "long" here is really 32-bit. -public final static int LONG( int x) -{ - return - (x>>>24) - | ((x>>>8) & 0xff00) - | ((x<<8) & 0xff0000) - | (x<<24); -} + public final static int LONG(int x) { + return (x >>> 24) + | ((x >>> 8) & 0xff00) + | ((x << 8) & 0xff0000) + | (x << 24); + } } //$Log: Swap.java,v $ diff --git a/src/m/cheatseq_t.java b/src/m/cheatseq_t.java index 0e165196..dd2ae567 100644 --- a/src/m/cheatseq_t.java +++ b/src/m/cheatseq_t.java @@ -63,14 +63,12 @@ // Cheat sequence checking. // // ----------------------------------------------------------------------------- - /** * Cheat sequence checking. MAES: all of this stuff used to be in cheat.h and * cheat.c, but seeing how all manipulation is done on "cheatseq_t" objects, it * makes more sense to move this functionality in here, and go OO all the way. * So away with the fugly static methods!!! */ - public class cheatseq_t { // This holds the actual data (was a char*). @@ -90,16 +88,16 @@ public cheatseq_t(char[] sequence) { this.p = 0; } - public cheatseq_t(String sequence, boolean prescrambled){ - if (prescrambled){ - this.sequence=sequence.toCharArray(); - p=0; - } else { - this.sequence=scrambleString(sequence); - p=0; - } - } - + public cheatseq_t(String sequence, boolean prescrambled) { + if (prescrambled) { + this.sequence = sequence.toCharArray(); + p = 0; + } else { + this.sequence = scrambleString(sequence); + p = 0; + } + } + /** * This was in cheat.c, but makes more sense to be used as an * initializer/constructor. @@ -124,8 +122,9 @@ public void GetParam(char[] buffer) { this.sequence[ptr++] = 0; } while ((c != 0) && (this.sequence[ptr] != 0xff)); - if (this.sequence[ptr] == 0xff) + if (this.sequence[ptr] == 0xff) { buffer[bptr] = 0; + } } @@ -137,26 +136,26 @@ public void GetParam(char[] buffer) { * @param key * @return */ - public boolean CheckCheat(cheatseq_t cht, int key) { boolean rc = false; - if (cht.p < 0) + if (cht.p < 0) { cht.p = 0; // initialize if first time - - if (cht.p == 0) - // This actually points inside "sequence" - // *(cht->p++) = key; + } + if (cht.p == 0) // This actually points inside "sequence" + // *(cht->p++) = key; + { cht.sequence[cht.p++] = (char) key; - else if (cheat_xlate_table[(char) key] == cht.sequence[cht.p]) + } else if (cheat_xlate_table[(char) key] == cht.sequence[cht.p]) { cht.p++; - else - // Failure: back to the beginning. + } else // Failure: back to the beginning. + { cht.p = 0; + } - if (cht.sequence[cht.p] == 1) + if (cht.sequence[cht.p] == 1) { cht.p++; - else if (cht.sequence[cht.p] == 0xff) // end of sequence character + } else if (cht.sequence[cht.p] == 0xff) // end of sequence character { cht.p = 0; rc = true; @@ -172,26 +171,26 @@ else if (cht.sequence[cht.p] == 0xff) // end of sequence character * @param key * @return */ - public boolean CheckCheat(int key) { boolean rc = false; - if (this.p < 0) + if (this.p < 0) { this.p = 0; // initialize if first time - - if (sequence[p] == 0) - // This actually points inside "sequence" - // *(cht->p++) = key; + } + if (sequence[p] == 0) // This actually points inside "sequence" + // *(cht->p++) = key; + { sequence[p++] = (char) key; - //p++; //_D_: this fixed cheat with parm problem (IDCLIP) - else if (cheat_xlate_table[(char) key] == sequence[p]) + } //p++; //_D_: this fixed cheat with parm problem (IDCLIP) + else if (cheat_xlate_table[(char) key] == sequence[p]) { p++; - else - // Failure: back to the beginning. + } else // Failure: back to the beginning. + { p = 0; - if (sequence[p] == 1) + } + if (sequence[p] == 1) { p++; - else if (sequence[p] == 0xff) // end of sequence character + } else if (sequence[p] == 0xff) // end of sequence character { p = 0; rc = true; @@ -212,16 +211,16 @@ public static char SCRAMBLE(char a) { + (((a) & 8) << 1) + (((a) & 16) >>> 1) + ((a) & 32) + (((a) & 64) >>> 5) + (((a) & 128) >>> 7)); } - - public static char[] scrambleString(String s){ - - char[] tmp=new char[s.length()+1]; - for (int i=0;i { -public class fixed_t implements Comparable{ - - public static final int FRACBITS = 16; - public static final int FRACUNIT = (1<>> FRACBITS); -} - -public static int FixedMul -( int a, - fixed_t b ) -{ - return (int)(((long) a * (long ) b.val) >>> FRACBITS); -} - -public static final int FixedMul -( int a, - int b ) -{ - return (int)(((long) a * (long ) b) >>> FRACBITS); -} + public fixed_t(int val) { + this.val = val; + } -/** Returns result straight as an int.. - * - * @param a - * @param b - * @return - */ + public fixed_t(fixed_t x) { + this.val = x.val; + } -public static int FixedMulInt -( fixed_t a, - fixed_t b ) -{ - return (int)(((long) a.val * (long ) b.val) >> FRACBITS); -} + public static final String rcsid = "$Id: fixed_t.java,v 1.14 2011/10/25 19:52:13 velktron Exp $"; + + /** Creates a new fixed_t object for the result a*b + * + * @param a + * @param b + * @return + */ + public static int FixedMul(fixed_t a, + fixed_t b) { + return (int) (((long) a.val * (long) b.val) >>> FRACBITS); + } -/** In-place c=a*b - * - * @param a - * @param b - * @param c - */ - -public final static void FixedMul -( fixed_t a, - fixed_t b, - fixed_t c) -{ - c.set((int)(((long) a.val * (long ) b.val) >> FRACBITS)); -} + public static int FixedMul(int a, + fixed_t b) { + return (int) (((long) a * (long) b.val) >>> FRACBITS); + } + public static final int FixedMul(int a, + int b) { + return (int) (((long) a * (long) b) >>> FRACBITS); + } -/** In-place this=this*a - * - * @param a - * @param b - * @param c - */ + /** Returns result straight as an int.. + * + * @param a + * @param b + * @return + */ + public static int FixedMulInt(fixed_t a, + fixed_t b) { + return (int) (((long) a.val * (long) b.val) >> FRACBITS); + } -public final void FixedMul -( fixed_t a) -{ - this.set((int)(((long) a.val * (long ) this.val) >> FRACBITS)); -} + /** In-place c=a*b + * + * @param a + * @param b + * @param c + */ + public final static void FixedMul(fixed_t a, + fixed_t b, + fixed_t c) { + c.set((int) (((long) a.val * (long) b.val) >> FRACBITS)); + } + /** In-place this=this*a + * + * @param a + * @param b + * @param c + */ + public final void FixedMul(fixed_t a) { + this.set((int) (((long) a.val * (long) this.val) >> FRACBITS)); + } -public final static int -FixedDiv -( int a, - int b ) -{ - if ((Math.abs(a) >> 14) >= Math.abs(b)) - { - return (a^b) < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE; - } - else - { - long result; + public final static int + FixedDiv(int a, + int b) { + if ((Math.abs(a) >> 14) >= Math.abs(b)) { + return (a ^ b) < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE; + } else { + long result; - result = ((long) a << 16) / b; + result = ((long) a << 16) / b; - return (int) result; - } -} + return (int) result; + } + } + public final static int + FixedDiv2(int a, + int b) { -public final static int -FixedDiv2 -( int a, - int b ) -{ + int c; + c = (int) (((long) a << 16) / (long) b); + return c; - - int c; - c = (int)(((long)a<<16) / (long)b); - return c; - - /* + /* double c; c = ((double)a) / ((double)b) * FRACUNIT; @@ -189,123 +159,126 @@ public fixed_t(fixed_t x) { throw new ArithmeticException("FixedDiv: divide by zero"); return (int)c;*/ -} - -@Override -public int compareTo(fixed_t o) { - if (o.getClass()!=fixed_t.class) return -1; - if (this.val==((fixed_t)(o)).val) return 0; - if (this.val>((fixed_t)(o)).val) return 1; - else return -1; } -public int compareTo(int o) { - if (this.val==o) return 0; - if (this.val>o) return 1; - else return -1; + @Override + public int compareTo(fixed_t o) { + if (o.getClass() != fixed_t.class) { + return -1; + } + if (this.val == ((fixed_t) (o)).val) { + return 0; + } + if (this.val > ((fixed_t) (o)).val) { + return 1; + } else { + return -1; + } } -public void add(fixed_t a){ - this.val+=a.val; -} - -public void sub(fixed_t a){ - this.val-=a.val; -} - -public void add(int a){ - this.val+=a; -} - -public void sub(int a){ - this.val-=a; -} - -/** a+b - * - * @param a - * @param b - * @return - */ - -public static int add(fixed_t a,fixed_t b){ - return a.val+b.val; -} - -/** a-b - * - * @param a - * @param b - * @return - */ + public int compareTo(int o) { + if (this.val == o) { + return 0; + } + if (this.val > o) { + return 1; + } else { + return -1; + } + } -public static int sub(fixed_t a,fixed_t b){ - return a.val-b.val; -} + public void add(fixed_t a) { + this.val += a.val; + } -/** c=a+b - * - * @param c - * @param a - * @param b - */ + public void sub(fixed_t a) { + this.val -= a.val; + } -public static void add(fixed_t c, fixed_t a,fixed_t b){ - c.val= a.val+b.val; -} + public void add(int a) { + this.val += a; + } -/** c=a-b - * - * @param c - * @param a - * @param b - */ + public void sub(int a) { + this.val -= a; + } -public static void sub(fixed_t c,fixed_t a,fixed_t b){ - c.val= a.val-b.val; -} + /** a+b + * + * @param a + * @param b + * @return + */ + public static int add(fixed_t a, fixed_t b) { + return a.val + b.val; + } + /** a-b + * + * @param a + * @param b + * @return + */ + public static int sub(fixed_t a, fixed_t b) { + return a.val - b.val; + } -/** Equals Zero - * - * @return - */ + /** c=a+b + * + * @param c + * @param a + * @param b + */ + public static void add(fixed_t c, fixed_t a, fixed_t b) { + c.val = a.val + b.val; + } -public boolean isEZ() { - return (this.val==0); + /** c=a-b + * + * @param c + * @param a + * @param b + */ + public static void sub(fixed_t c, fixed_t a, fixed_t b) { + c.val = a.val - b.val; } -/** Greater than Zero - * - * @return - */ + /** Equals Zero + * + * @return + */ + public boolean isEZ() { + return (this.val == 0); + } -public boolean isGZ() { - return (this.val>0); + /** Greater than Zero + * + * @return + */ + public boolean isGZ() { + return (this.val > 0); } -/** Less than Zero - * - * @return - */ -public boolean isLZ() { - return (this.val<0); + /** Less than Zero + * + * @return + */ + public boolean isLZ() { + return (this.val < 0); } // These are here to make easier handling all those methods in R // that return "1" or "0" based on one result. + public int oneEZ() { + return (this.val == 0) ? 1 : 0; + } -public int oneEZ(){ - return (this.val==0)?1:0; -} + public int oneGZ() { + return (this.val > 0) ? 1 : 0; + } -public int oneGZ(){ - return (this.val>0)?1:0; -} + public int oneLZ() { + return (this.val < 0) ? 1 : 0; + } -public int oneLZ(){ - return (this.val<0)?1:0; } - - -} \ No newline at end of file diff --git a/src/m/menu_t.java b/src/m/menu_t.java index 62df06c0..96264f56 100644 --- a/src/m/menu_t.java +++ b/src/m/menu_t.java @@ -7,31 +7,31 @@ * @author Maes * */ - public class menu_t { - public menu_t(int numitems, menu_t prev, menuitem_t[] items, + + public menu_t(int numitems, menu_t prev, menuitem_t[] items, DrawRoutine drawroutine, int x, int y, int lastOn) { - this.numitems=numitems; - this.prevMenu=prev; - this.menuitems=items; - this.routine=drawroutine; - this.x=x; - this.y=y; - this.lastOn=lastOn; - + this.numitems = numitems; + this.prevMenu = prev; + this.menuitems = items; + this.routine = drawroutine; + this.x = x; + this.y = y; + this.lastOn = lastOn; + } - /** # of menu items */ - public int numitems; - - /** previous menu */ - public menu_t prevMenu; + /** # of menu items */ + public int numitems; + + /** previous menu */ + public menu_t prevMenu; - /** menu items */ - public menuitem_t[] menuitems; - /** draw routine */ - public DrawRoutine routine; - /** x,y of menu */ - public int x,y; - /** last item user was on in menu */ - public int lastOn; - } + /** menu items */ + public menuitem_t[] menuitems; + /** draw routine */ + public DrawRoutine routine; + /** x,y of menu */ + public int x, y; + /** last item user was on in menu */ + public int lastOn; +} diff --git a/src/m/pcx_t.java b/src/m/pcx_t.java index 085abdb4..a8a94622 100644 --- a/src/m/pcx_t.java +++ b/src/m/pcx_t.java @@ -2,7 +2,6 @@ import java.io.DataOutputStream; import java.io.IOException; - import w.IWritableDoomObject; /** Yeah, this is actually a PCX header implementation, and Mocha Doom @@ -12,84 +11,82 @@ * @author Maes * */ +public class pcx_t implements IWritableDoomObject { + + // + // SCREEN SHOTS + // + // char -> byte Bytes. + /** manufacturer byte, must be 10 decimal */ + public byte manufacturer; + + /** PCX version number */ + byte version; + + /** run length encoding byte, must be 1 */ + byte encoding; + + /** number of bits per pixel per bit plane */ + byte bits_per_pixel; + + /** image limits in pixels: Xmin, Ymin, Xmax, Ymax */ + public char xmin, ymin, xmax, ymax; + + /** horizontal dots per inch when printed (unreliable) */ + char hres; + + /** vertical dots per inch when printed (unreliable) */ + char vres; + + /** 16-color palette (16 RGB triples between 0-255) + * UNUSED in Doom. */ + byte[] palette = new byte[48]; + + /** reserved, must be zero */ + byte reserved; + + /** number of bit planes */ + byte color_planes; + + /** video memory bytes per image row */ + char bytes_per_line; + + /** 16-color palette interpretation (unreliable) 0=color/b&w 1=grayscale */ + char palette_type; + + // Seems off-spec. However it's left all zeroed out. + byte[] filler = new byte[58]; + + //unsigned char data; + byte[] data; + + @Override + public void write(DataOutputStream f) throws IOException { + // char -> byte Bytes. + + f.writeByte(manufacturer); + f.writeByte(version); + f.writeByte(encoding); + f.writeByte(bits_per_pixel); + + // unsigned short -> char + f.writeChar(Swap.SHORT(xmin)); + f.writeChar(Swap.SHORT(ymin)); + f.writeChar(Swap.SHORT(xmax)); + f.writeChar(Swap.SHORT(ymax)); + + f.writeChar(Swap.SHORT(hres)); + f.writeChar(Swap.SHORT(vres)); + f.write(palette); + + f.writeByte(reserved); + f.writeByte(color_planes); + // unsigned short -> char + f.writeChar(Swap.SHORT(bytes_per_line)); + f.writeChar(Swap.SHORT(palette_type)); -public class pcx_t implements IWritableDoomObject{ - - // - // SCREEN SHOTS - // - - // char -> byte Bytes. - /** manufacturer byte, must be 10 decimal */ - public byte manufacturer; - - /** PCX version number */ - byte version; - - /** run length encoding byte, must be 1 */ - byte encoding; - - /** number of bits per pixel per bit plane */ - byte bits_per_pixel; - - /** image limits in pixels: Xmin, Ymin, Xmax, Ymax */ - public char xmin,ymin,xmax,ymax; - - /** horizontal dots per inch when printed (unreliable) */ - char hres; - - /** vertical dots per inch when printed (unreliable) */ - char vres; - - /** 16-color palette (16 RGB triples between 0-255) - * UNUSED in Doom. */ - byte[] palette=new byte[48]; - - /** reserved, must be zero */ - byte reserved; - - /** number of bit planes */ - byte color_planes; - - /** video memory bytes per image row */ - char bytes_per_line; - - /** 16-color palette interpretation (unreliable) 0=color/b&w 1=grayscale */ - char palette_type; - - // Seems off-spec. However it's left all zeroed out. - byte[] filler=new byte[58]; - - //unsigned char data; - byte[] data; - - @Override - public void write(DataOutputStream f) throws IOException { - // char -> byte Bytes. - - f.writeByte(manufacturer); - f.writeByte(version); - f.writeByte(encoding); - f.writeByte(bits_per_pixel); - - // unsigned short -> char - f.writeChar(Swap.SHORT(xmin)); - f.writeChar(Swap.SHORT(ymin)); - f.writeChar(Swap.SHORT(xmax)); - f.writeChar(Swap.SHORT(ymax)); - - f.writeChar(Swap.SHORT(hres)); - f.writeChar(Swap.SHORT(vres)); - f.write(palette); - - f.writeByte(reserved); - f.writeByte(color_planes); - // unsigned short -> char - f.writeChar(Swap.SHORT(bytes_per_line)); - f.writeChar(Swap.SHORT(palette_type)); - - f.write(filler); - //unsigned char data; // unbounded - f.write(data); - } - } ; + f.write(filler); + //unsigned char data; // unbounded + f.write(data); + } +}; diff --git a/src/mochadoom/Engine.java b/src/mochadoom/Engine.java index ca8f04e6..45c2ab85 100644 --- a/src/mochadoom/Engine.java +++ b/src/mochadoom/Engine.java @@ -14,19 +14,22 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package mochadoom; import awt.DoomWindow; import awt.DoomWindowController; import awt.EventBase.KeyStateInterest; -import static awt.EventBase.KeyStateSatisfaction.*; +import static awt.EventBase.KeyStateSatisfaction.WANTS_MORE_ATE; +import static awt.EventBase.KeyStateSatisfaction.WANTS_MORE_PASS; import awt.EventHandler; import doom.CVarManager; import doom.CommandVariable; import doom.ConfigManager; import doom.DoomMain; -import static g.Signals.ScanCode.*; +import static g.Signals.ScanCode.SC_ENTER; +import static g.Signals.ScanCode.SC_ESCAPE; +import static g.Signals.ScanCode.SC_LALT; +import static g.Signals.ScanCode.SC_PAUSE; import i.Strings; import java.io.IOException; import java.util.Arrays; @@ -34,17 +37,21 @@ import java.util.logging.Logger; public class Engine { + + private static final Logger LOGGER = Loggers.getLogger(Engine.class.getName()); + private static volatile Engine instance; - + /** * Mocha Doom engine entry point */ public static void main(final String[] argv) throws IOException { + LOGGER.log(Level.INFO, Strings.MOCHA_DOOM_TITLE); final Engine local; synchronized (Engine.class) { local = new Engine(argv); } - + /** * Add eventHandler listeners to JFrame and its Canvas elememt */ @@ -57,85 +64,85 @@ public static void main(final String[] argv) throws IOException { // never returns try { local.DOOM.setupLoop(); - } catch(Exception e) { - e.printStackTrace(); + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "DOOM.setupLoop failure", e); System.exit(1); } - } - + } + public final CVarManager cvm; public final ConfigManager cm; public final DoomWindowController windowController; private final DoomMain DOOM; - + @SuppressWarnings("unchecked") private Engine(final String... argv) throws IOException { instance = this; - + // reads command line arguments this.cvm = new CVarManager(Arrays.asList(argv)); - + // reads default.cfg and mochadoom.cfg this.cm = new ConfigManager(); - + // intiializes stuff this.DOOM = new DoomMain<>(); - + // opens a window this.windowController = /*cvm.bool(CommandVariable.AWTFRAME) - ? */DoomWindow.createCanvasWindowController( - DOOM.graphicSystem::getScreenImage, - DOOM::PostEvent, - DOOM.graphicSystem.getScreenWidth(), - DOOM.graphicSystem.getScreenHeight() - )/* : DoomWindow.createJPanelWindowController( + ? */ DoomWindow.createCanvasWindowController( + DOOM.graphicSystem::getScreenImage, + DOOM::PostEvent, + DOOM.graphicSystem.getScreenWidth(), + DOOM.graphicSystem.getScreenHeight() + )/* : DoomWindow.createJPanelWindowController( DOOM.graphicSystem::getScreenImage, DOOM::PostEvent, DOOM.graphicSystem.getScreenWidth(), DOOM.graphicSystem.getScreenHeight() )*/; - + windowController.getObserver().addInterest( - new KeyStateInterest<>(obs -> { - EventHandler.fullscreenChanges(windowController.getObserver(), windowController.switchFullscreen()); - return WANTS_MORE_ATE; - }, SC_LALT, SC_ENTER) + new KeyStateInterest<>(obs -> { + EventHandler.fullscreenChanges(windowController.getObserver(), windowController.switchFullscreen()); + return WANTS_MORE_ATE; + }, SC_LALT, SC_ENTER) ).addInterest( - new KeyStateInterest<>(obs -> { - if (!windowController.isFullscreen()) { - if (DOOM.menuactive || DOOM.paused || DOOM.demoplayback) { - EventHandler.menuCaptureChanges(obs, DOOM.mousecaptured = !DOOM.mousecaptured); - } else { // can also work when not DOOM.mousecaptured - EventHandler.menuCaptureChanges(obs, DOOM.mousecaptured = true); + new KeyStateInterest<>(obs -> { + if (!windowController.isFullscreen()) { + if (DOOM.menuactive || DOOM.paused || DOOM.demoplayback) { + EventHandler.menuCaptureChanges(obs, DOOM.mousecaptured = !DOOM.mousecaptured); + } else { // can also work when not DOOM.mousecaptured + EventHandler.menuCaptureChanges(obs, DOOM.mousecaptured = true); + } } - } - return WANTS_MORE_PASS; - }, SC_LALT) + return WANTS_MORE_PASS; + }, SC_LALT) ).addInterest( - new KeyStateInterest<>(obs -> { - if (!windowController.isFullscreen() && !DOOM.mousecaptured && DOOM.menuactive) { - EventHandler.menuCaptureChanges(obs, DOOM.mousecaptured = true); - } - - return WANTS_MORE_PASS; - }, SC_ESCAPE) + new KeyStateInterest<>(obs -> { + if (!windowController.isFullscreen() && !DOOM.mousecaptured && DOOM.menuactive) { + EventHandler.menuCaptureChanges(obs, DOOM.mousecaptured = true); + } + + return WANTS_MORE_PASS; + }, SC_ESCAPE) ).addInterest( - new KeyStateInterest<>(obs -> { - if (!windowController.isFullscreen() && !DOOM.mousecaptured && DOOM.paused) { - EventHandler.menuCaptureChanges(obs, DOOM.mousecaptured = true); - } - return WANTS_MORE_PASS; - }, SC_PAUSE) + new KeyStateInterest<>(obs -> { + if (!windowController.isFullscreen() && !DOOM.mousecaptured && DOOM.paused) { + EventHandler.menuCaptureChanges(obs, DOOM.mousecaptured = true); + } + return WANTS_MORE_PASS; + }, SC_PAUSE) ); } - + /** - * Temporary solution. Will be later moved in more detalied place + * Temporary solution. Will be later moved in more detailed place */ public static void updateFrame() { instance.windowController.updateFrame(); } - + public String getWindowTitle(double frames) { if (cvm.bool(CommandVariable.SHOWFPS)) { return String.format("%s - %s FPS: %.2f", Strings.MOCHA_DOOM_TITLE, DOOM.bppMode, frames); @@ -153,20 +160,20 @@ public static Engine getEngine() { try { Engine.instance = local = new Engine(); } catch (IOException ex) { - Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, null, ex); + LOGGER.log(Level.SEVERE, "Engine I/O error", ex); throw new Error("This launch is DOOMed"); } } } } - + return local; } - + public static CVarManager getCVM() { return getEngine().cvm; } - + public static ConfigManager getConfig() { return getEngine().cm; } diff --git a/src/mochadoom/Loggers.java b/src/mochadoom/Loggers.java index 5bc945be..c5cb1bd8 100644 --- a/src/mochadoom/Loggers.java +++ b/src/mochadoom/Loggers.java @@ -14,7 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package mochadoom; import awt.DoomWindow; @@ -22,6 +21,10 @@ import awt.EventBase.ActionMode; import awt.EventBase.ActionStateHolder; import awt.EventBase.RelationType; +import doom.CVarManager; +import doom.ConfigManager; +import doom.DoomMain; +import i.DoomSystem; import java.awt.AWTEvent; import java.io.OutputStream; import java.util.Arrays; @@ -44,44 +47,55 @@ * @author Good Sign */ public class Loggers { + + static { + System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] [%4$-7s] [%3$-20s] %5$s %n"); + } + private static final Level DEFAULT_LEVEL = Level.WARNING; - + private static final Map PARENT_LOGGERS_MAP = Stream.of( Level.FINE, Level.FINER, Level.FINEST, Level.INFO, Level.SEVERE, Level.WARNING - ).collect(Collectors.toMap(l -> l, Loggers::newLoggerHandlingLevel)); - + ).collect(Collectors.toMap(l -> l, Loggers::newLoggerHandlingLevel)); + private static final Logger DEFAULT_LOGGER = PARENT_LOGGERS_MAP.get(DEFAULT_LEVEL); private static final HashMap INDIVIDUAL_CLASS_LOGGERS = new HashMap<>(); - + static { //INDIVIDUAL_CLASS_LOGGERS.put(EventObserver.class.getName(), PARENT_LOGGERS_MAP.get(Level.FINE)); //INDIVIDUAL_CLASS_LOGGERS.put(TraitFactory.class.getName(), PARENT_LOGGERS_MAP.get(Level.FINER)); INDIVIDUAL_CLASS_LOGGERS.put(ActiveStates.class.getName(), PARENT_LOGGERS_MAP.get(Level.FINER)); INDIVIDUAL_CLASS_LOGGERS.put(DoomWindow.class.getName(), PARENT_LOGGERS_MAP.get(Level.FINE)); INDIVIDUAL_CLASS_LOGGERS.put(Patches.class.getName(), PARENT_LOGGERS_MAP.get(Level.INFO)); + INDIVIDUAL_CLASS_LOGGERS.put(ConfigManager.class.getName(), PARENT_LOGGERS_MAP.get(Level.INFO)); + INDIVIDUAL_CLASS_LOGGERS.put(DoomMain.class.getName(), PARENT_LOGGERS_MAP.get(Level.INFO)); + INDIVIDUAL_CLASS_LOGGERS.put(DoomSystem.class.getName(), PARENT_LOGGERS_MAP.get(Level.INFO)); + INDIVIDUAL_CLASS_LOGGERS.put(CVarManager.class.getName(), PARENT_LOGGERS_MAP.get(Level.INFO)); + INDIVIDUAL_CLASS_LOGGERS.put(Engine.class.getName(), PARENT_LOGGERS_MAP.get(Level.INFO)); } - + public static Logger getLogger(final String className) { final Logger ret = Logger.getLogger(className); ret.setParent(INDIVIDUAL_CLASS_LOGGERS.getOrDefault(className, DEFAULT_LOGGER)); - + return ret; } - + private static EventBase lastHandler = null; - + public static & EventBase> void LogEvent( - final Logger logger, - final ActionStateHolder actionStateHolder, - final EventHandler handler, - final AWTEvent event + final Logger logger, + final ActionStateHolder actionStateHolder, + final EventHandler handler, + final AWTEvent event ) { if (!logger.isLoggable(Level.ALL) && lastHandler == handler) { return; } - + lastHandler = handler; - + + @SuppressWarnings("unchecked") final IntFunction[]> arrayGenerator = EventBase[]::new; final EventBase[] depends = actionStateHolder .cooperations(handler, RelationType.DEPEND) @@ -91,7 +105,7 @@ public static & EventBase final Map> adjusts = actionStateHolder .adjustments(handler); - + final EventBase[] causes = actionStateHolder .cooperations(handler, RelationType.CAUSE) .stream() @@ -103,36 +117,37 @@ public static & EventBase .stream() .filter(hdl -> actionStateHolder.hasActionsEnabled(hdl, ActionMode.DEPEND)) .toArray(arrayGenerator); - - if (logger.isLoggable(Level.FINEST)) + + if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, () -> String.format( - "\n\nENCOUNTERED EVENT: %s [%s] \n%s: %s \n%s \n%s: %s \n%s: %s \nOn event: %s", - handler, ActionMode.PERFORM, - RelationType.DEPEND, Arrays.toString(depends), - adjusts.entrySet().stream().collect(StringBuilder::new, (sb, e) -> sb.append(e.getKey()).append(' ').append(e.getValue()).append('\n'), StringBuilder::append), - RelationType.CAUSE, Arrays.toString(causes), - RelationType.REVERT, Arrays.toString(reverts), - event + "\n\nENCOUNTERED EVENT: %s [%s] \n%s: %s \n%s \n%s: %s \n%s: %s \nOn event: %s", + handler, ActionMode.PERFORM, + RelationType.DEPEND, Arrays.toString(depends), + adjusts.entrySet().stream().collect(StringBuilder::new, (sb, e) -> sb.append(e.getKey()).append(' ').append(e.getValue()).append('\n'), StringBuilder::append), + RelationType.CAUSE, Arrays.toString(causes), + RelationType.REVERT, Arrays.toString(reverts), + event )); - else if (logger.isLoggable(Level.FINER)) { + } else if (logger.isLoggable(Level.FINER)) { logger.log(Level.FINER, () -> String.format( - "\n\nENCOUNTERED EVENT: %s [%s] \n%s: %s \n%s \n%s: %s \n%s: %s \n", - handler, ActionMode.PERFORM, - RelationType.DEPEND, Arrays.toString(depends), - adjusts.entrySet().stream().collect(StringBuilder::new, (sb, e) -> sb.append(e.getKey()).append(' ').append(e.getValue()).append('\n'), StringBuilder::append), - RelationType.CAUSE, Arrays.toString(causes), - RelationType.REVERT, Arrays.toString(reverts) + "\n\nENCOUNTERED EVENT: %s [%s] \n%s: %s \n%s \n%s: %s \n%s: %s \n", + handler, ActionMode.PERFORM, + RelationType.DEPEND, Arrays.toString(depends), + adjusts.entrySet().stream().collect(StringBuilder::new, (sb, e) -> sb.append(e.getKey()).append(' ').append(e.getValue()).append('\n'), StringBuilder::append), + RelationType.CAUSE, Arrays.toString(causes), + RelationType.REVERT, Arrays.toString(reverts) )); } else { logger.log(Level.FINE, () -> String.format( - "\nENCOUNTERED EVENT: %s [%s]", - handler, ActionMode.PERFORM + "\nENCOUNTERED EVENT: %s [%s]", + handler, ActionMode.PERFORM )); } } - - private Loggers() {} - + + private Loggers() { + } + private static Logger newLoggerHandlingLevel(final Level l) { final OutHandler h = new OutHandler(); h.setLevel(l); @@ -142,8 +157,9 @@ private static Logger newLoggerHandlingLevel(final Level l) { ret.addHandler(h); return ret; } - + private static final class OutHandler extends ConsoleHandler { + @Override @SuppressWarnings("UseOfSystemOutOrSystemErr") protected synchronized void setOutputStream(final OutputStream out) throws SecurityException { diff --git a/src/n/BasicNetworkInterface.java b/src/n/BasicNetworkInterface.java index c6c8b4c1..cf814003 100644 --- a/src/n/BasicNetworkInterface.java +++ b/src/n/BasicNetworkInterface.java @@ -16,6 +16,9 @@ import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import w.DoomBuffer; // Emacs style mode select -*- C++ -*- @@ -63,6 +66,8 @@ //----------------------------------------------------------------------------- public class BasicNetworkInterface implements DoomSystemNetworking { + static final Logger LOGGER = Loggers.getLogger(BasicNetworkInterface.class.getName()); + protected DoomMain DOOM; public BasicNetworkInterface(DoomMain DOOM) { @@ -183,7 +188,6 @@ public void invoke() { sendPacket.setSocketAddress(sendsocket.getRemoteSocketAddress()); sendSocketPacket(sendsocket, sendPacket); } catch (Exception e) { - e.printStackTrace(); DOOM.doomSystem.Error("SendPacket error: %s", e.getMessage()); } @@ -240,7 +244,7 @@ public void invoke() { sb.append(" 0x"); sb.append(DoomBuffer.getBEInt(recvData.retransmitfrom, recvData.starttic, recvData.player, recvData.numtics)); sb.append("numtics: ").append(recvData.numtics); - System.out.println(sb.toString()); + LOGGER.log(Level.FINE, sb.toString()); first = false; } } @@ -325,7 +329,7 @@ public void InitNetwork() { DOOM.cVarManager.with(CommandVariable.PORT, 0, (Integer port) -> { DOOMPORT = port; - System.out.println("using alternate port " + DOOMPORT); + LOGGER.log(Level.INFO, String.format("using alternate port %d", DOOMPORT)); }); // parse network game options, @@ -355,7 +359,7 @@ public void InitNetwork() { doomcom.numnodes = 1; // this node for sure String[] hosts = DOOM.cVarManager.get(CommandVariable.NET, String[].class, 1).get(); - for (String host: hosts) { + for (String host : hosts) { try { InetAddress addr = InetAddress.getByName(host); DatagramSocket ds = new DatagramSocket(null); @@ -364,7 +368,7 @@ public void InitNetwork() { sendaddress[doomcom.numnodes] = ds; } catch (SocketException | UnknownHostException e) { - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "InitNetwork: failure", e); } doomcom.numnodes++; @@ -380,8 +384,7 @@ public void InitNetwork() { insocket.setSoTimeout(1); insocket.bind(new InetSocketAddress(RECVPORT)); } catch (SocketException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); + LOGGER.log(Level.SEVERE, "InitNetwork: failure", e1); } } diff --git a/src/n/DoomSystemNetworking.java b/src/n/DoomSystemNetworking.java index 58c8f8c3..83c67b8b 100644 --- a/src/n/DoomSystemNetworking.java +++ b/src/n/DoomSystemNetworking.java @@ -21,15 +21,12 @@ // System specific network interface stuff. // //----------------------------------------------------------------------------- - -public interface DoomSystemNetworking{ - +public interface DoomSystemNetworking { // Called by D_DoomMain. + public void InitNetwork(); -public void InitNetwork (); -public void NetCmd (); - + public void NetCmd(); } diff --git a/src/n/DummyNetworkDriver.java b/src/n/DummyNetworkDriver.java index a4b3cf23..5ff32222 100644 --- a/src/n/DummyNetworkDriver.java +++ b/src/n/DummyNetworkDriver.java @@ -13,35 +13,33 @@ * @author Velktron * */ - public class DummyNetworkDriver implements NetConsts, DoomSystemNetworking { - ////////////// STATUS /////////// - + ////////////// STATUS /////////// private final DoomMain DOOM; - public DummyNetworkDriver(DoomMain DOOM){ + public DummyNetworkDriver(DoomMain DOOM) { this.DOOM = DOOM; - } + } - @Override - public void InitNetwork() { - doomcom_t doomcom =new doomcom_t(); - doomcom.id=DOOMCOM_ID; - doomcom.ticdup=1; + @Override + public void InitNetwork() { + doomcom_t doomcom = new doomcom_t(); + doomcom.id = DOOMCOM_ID; + doomcom.ticdup = 1; - // single player game + // single player game DOOM.netgame = Engine.getCVM().present(CommandVariable.NET); - doomcom.id = DOOMCOM_ID; - doomcom.numplayers = doomcom.numnodes = 1; - doomcom.deathmatch = 0; - doomcom.consoleplayer = 0; - DOOM.gameNetworking.setDoomCom(doomcom); - } - - @Override - public void NetCmd() { - // TODO Auto-generated method stub - - } + doomcom.id = DOOMCOM_ID; + doomcom.numplayers = doomcom.numnodes = 1; + doomcom.deathmatch = 0; + doomcom.consoleplayer = 0; + DOOM.gameNetworking.setDoomCom(doomcom); + } + + @Override + public void NetCmd() { + // TODO Auto-generated method stub + + } } diff --git a/src/n/DummyNetworkHandler.java b/src/n/DummyNetworkHandler.java index 4070fc2f..4686e0c2 100644 --- a/src/n/DummyNetworkHandler.java +++ b/src/n/DummyNetworkHandler.java @@ -3,18 +3,18 @@ import doom.IDoomGameNetworking; import doom.doomcom_t; -public class DummyNetworkHandler implements IDoomGameNetworking{ +public class DummyNetworkHandler implements IDoomGameNetworking { @Override public void NetUpdate() { // TODO Auto-generated method stub - + } @Override public void TryRunTics() { // TODO Auto-generated method stub - + } @Override @@ -26,7 +26,7 @@ public doomcom_t getDoomCom() { @Override public void setDoomCom(doomcom_t doomcom) { // TODO Auto-generated method stub - + } @Override @@ -38,7 +38,7 @@ public int getTicdup() { @Override public void setTicdup(int ticdup) { // TODO Auto-generated method stub - + } } diff --git a/src/n/IDoomNet.java b/src/n/IDoomNet.java index 39eb7150..21790b88 100644 --- a/src/n/IDoomNet.java +++ b/src/n/IDoomNet.java @@ -1,5 +1,6 @@ package n; public interface IDoomNet { + public void NetUpdate(); } diff --git a/src/p/AbstractLevelLoader.java b/src/p/AbstractLevelLoader.java index ac6c59a9..031dddc3 100644 --- a/src/p/AbstractLevelLoader.java +++ b/src/p/AbstractLevelLoader.java @@ -12,12 +12,15 @@ import doom.SourceCode.P_MapUtl; import static doom.SourceCode.P_MapUtl.P_SetThingPosition; import doom.SourceCode.R_Main; -import static doom.SourceCode.R_Main.*; +import static doom.SourceCode.R_Main.R_PointInSubsector; import doom.SourceCode.fixed_t; +import java.util.logging.Level; +import java.util.logging.Logger; import m.BBox; import m.Settings; import static m.fixed_t.FRACBITS; import mochadoom.Engine; +import mochadoom.Loggers; import static p.mobj_t.MF_NOBLOCKMAP; import static p.mobj_t.MF_NOSECTOR; import rr.line_t; @@ -40,12 +43,12 @@ * * @author velktron */ - public abstract class AbstractLevelLoader implements ILevelLoader { - // ///////////////// Status objects /////////////////// + private static final Logger LOGGER = Loggers.getLogger(AbstractLevelLoader.class.getName()); - final DoomMain DOOM; + // ///////////////// Status objects /////////////////// + final DoomMain DOOM; // // MAP related Lookup tables. @@ -66,7 +69,6 @@ public abstract class AbstractLevelLoader implements ILevelLoader { public int numsides; public side_t[] sides; - // BLOCKMAP // Created from axis aligned bounding box // of the map, a rectangular array of @@ -92,7 +94,8 @@ public abstract class AbstractLevelLoader implements ILevelLoader { */ protected int[] blockmaplump; // was short -- killough - @fixed_t public int bmaporgx, bmaporgy; + @fixed_t + public int bmaporgx, bmaporgy; /** for thing chains */ public mobj_t[] blocklinks; @@ -102,11 +105,9 @@ public abstract class AbstractLevelLoader implements ILevelLoader { * LineOf Sight calculation. Without special effect, this could be used as a * PVS lookup as well. */ - public byte[] rejectmatrix; // Maintain single and multi player starting spots. - // 1/11/98 killough: Remove limit on deathmatch starts protected mapthing_t[] deathmatchstarts; // killough @@ -117,7 +118,7 @@ public abstract class AbstractLevelLoader implements ILevelLoader { protected mapthing_t[] playerstarts = new mapthing_t[Limits.MAXPLAYERS]; - public AbstractLevelLoader(DoomMain DOOM) { + public AbstractLevelLoader(DoomMain DOOM) { this.DOOM = DOOM; } @@ -125,7 +126,6 @@ public AbstractLevelLoader(DoomMain DOOM) { * P_SetThingPosition Links a thing into both a block and a subsector based * on it's x y. Sets thing.subsector properly */ - @Override @SourceCode.Exact @P_MapUtl.C(P_SetThingPosition) @@ -137,7 +137,8 @@ public void SetThingPosition(mobj_t thing) { final mobj_t link; // link into subsector - R_PointInSubsector: { + R_PointInSubsector: + { ss = PointInSubsector(thing.x, thing.y); } thing.subsector = ss; @@ -161,13 +162,12 @@ public void SetThingPosition(mobj_t thing) { // inert things don't need to be in blockmap blockx = getSafeBlockX(thing.x - bmaporgx); blocky = getSafeBlockY(thing.y - bmaporgy); - + // Valid block? if (blockx >= 0 - && blockx < bmapwidth - && blocky >= 0 - && blocky < bmapheight - ) { + && blockx < bmapwidth + && blocky >= 0 + && blocky < bmapheight) { // Get said block. link = blocklinks[blocky * bmapwidth + blockx]; thing.bprev = null; // Thing is put at head of block... @@ -201,12 +201,13 @@ public subsector_t PointInSubsector(@fixed_t int x, @fixed_t int y) { if (numnodes == 0) { return subsectors[0]; } - + nodenum = numnodes - 1; - + while (!C2JUtils.flags(nodenum, NF_SUBSECTOR)) { node = nodes[nodenum]; - R_PointOnSide: { + R_PointOnSide: + { side = node.PointOnSide(x, y); } nodenum = node.children[side]; @@ -220,11 +221,10 @@ public subsector_t PointInSubsector(@fixed_t int x, @fixed_t int y) { // New code added to speed up calculation of internal blockmap // Algorithm is order of nlines*(ncols+nrows) not nlines*ncols*nrows // - /** * places to shift rel position for cell num */ - protected static final int BLOCK_SHIFT = 7; + protected static final int BLOCK_SHIFT = 7; /** * mask for rel position within cell @@ -238,9 +238,9 @@ public subsector_t PointInSubsector(@fixed_t int x, @fixed_t int y) { // jff 10/8/98 use guardband>0 // jff 10/12/98 0 ok with + 1 in rows,cols - protected class linelist_t // type used to list lines in each block { + public int num; public linelist_t next; @@ -257,11 +257,12 @@ protected class linelist_t // type used to list lines in each block * @param lineno */ private void AddBlockLine(linelist_t[] lists, int[] count, boolean[] done, int blockno, int lineno) { - long a=System.nanoTime(); + long a = System.nanoTime(); linelist_t l; - if (done[blockno]) + if (done[blockno]) { return; + } l = new linelist_t(); l.num = lineno; @@ -269,13 +270,13 @@ private void AddBlockLine(linelist_t[] lists, int[] count, boolean[] done, int b lists[blockno] = l; count[blockno]++; done[blockno] = true; - long b=System.nanoTime(); - - total+=(b-a); + long b = System.nanoTime(); + + total += (b - a); } - long total=0; - + long total = 0; + /** * Actually construct the blockmap lump from the level data This finds the * intersection of each linedef with the column and row lines at the left @@ -284,7 +285,6 @@ private void AddBlockLine(linelist_t[] lists, int[] count, boolean[] done, int b * important that LINEDEFS and VERTEXES are already read-in and defined, so * it is necessary to change map lump ordering for this to work. */ - protected final void CreateBlockMap() { int xorg, yorg; // blockmap origin (lower left) int nrows, ncols; // blockmap dimensions @@ -301,18 +301,19 @@ protected final void CreateBlockMap() { long a = System.nanoTime(); // scan for map limits, which the blockmap must enclose - for (int i = 0; i < numvertexes; i++) { int t; - if ((t = vertexes[i].x) < map_minx) + if ((t = vertexes[i].x) < map_minx) { map_minx = t; - else if (t > map_maxx) + } else if (t > map_maxx) { map_maxx = t; - if ((t = vertexes[i].y) < map_miny) + } + if ((t = vertexes[i].y) < map_miny) { map_miny = t; - else if (t > map_maxy) + } else if (t > map_maxy) { map_maxy = t; + } } map_minx >>= FRACBITS; // work in map coords, not fixed_t map_maxx >>= FRACBITS; @@ -320,20 +321,18 @@ else if (t > map_maxy) map_maxy >>= FRACBITS; // set up blockmap area to enclose level plus margin - xorg = map_minx - BLOCK_MARGIN; yorg = map_miny - BLOCK_MARGIN; ncols = (map_maxx + BLOCK_MARGIN - xorg + 1 + BLOCK_MASK) >> BLOCK_SHIFT; // jff - // 10/12/98 + // 10/12/98 nrows = (map_maxy + BLOCK_MARGIN - yorg + 1 + BLOCK_MASK) >> BLOCK_SHIFT; // +1 - // needed - // for + // needed + // for NBlocks = ncols * nrows; // map exactly 1 cell // create the array of pointers on NBlocks to blocklists // also create an array of linelist counts on NBlocks // finally make an array in which we can mark blocks done per line - // CPhipps - calloc's blocklists = new linelist_t[NBlocks]; blockcount = new int[NBlocks]; @@ -342,7 +341,6 @@ else if (t > map_maxy) // initialize each blocklist, and enter the trailing -1 in all // blocklists // note the linked list of lines grows backwards - for (int i = 0; i < NBlocks; i++) { blocklists[i] = new linelist_t(); blocklists[i].num = -1; @@ -353,7 +351,6 @@ else if (t > map_maxy) // For each linedef in the wad, determine all blockmap blocks it // touches, // and add the linedef number to the blocklists for those blocks - for (int i = 0; i < numlines; i++) { int x1 = lines[i].v1x >> FRACBITS; // lines[i] map coords int y1 = lines[i].v1y >> FRACBITS; @@ -372,11 +369,9 @@ else if (t > map_maxy) int maxy = y1 > y2 ? y1 : y2; // no blocks done for this linedef yet - C2JUtils.memset(blockdone, false, NBlocks); // The line always belongs to the blocks containing its endpoints - bx = (x1 - xorg) >> BLOCK_SHIFT; by = (y1 - yorg) >> BLOCK_SHIFT; AddBlockLine(blocklists, blockcount, blockdone, by * ncols + bx, i); @@ -388,7 +383,6 @@ else if (t > map_maxy) // it contains, intersects the Linedef i. Add i to each // corresponding // blocklist. - if (!vert) // don't interesect vertical lines with columns { for (int j = 0; j < ncols; j++) { @@ -402,14 +396,17 @@ else if (t > map_maxy) int yp = (y - yorg) & BLOCK_MASK; // y position within block if (yb < 0 || yb > nrows - 1) // outside blockmap, continue + { continue; + } if (x < minx || x > maxx) // line doesn't touch column + { continue; + } // The cell that contains the intersection point is always // added - AddBlockLine(blocklists, blockcount, blockdone, ncols * yb + j, i); @@ -418,31 +415,36 @@ else if (t > map_maxy) // (and whether the line extends past the intersection) // which // blocks are hit - if (yp == 0) // intersection at a corner { if (sneg) // \ - blocks x,y-, x-,y { - if (yb > 0 && miny < y) + if (yb > 0 && miny < y) { AddBlockLine(blocklists, blockcount, blockdone, - ncols * (yb - 1) + j, i); - if (j > 0 && minx < x) + ncols * (yb - 1) + j, i); + } + if (j > 0 && minx < x) { AddBlockLine(blocklists, blockcount, blockdone, - ncols * yb + j - 1, i); + ncols * yb + j - 1, i); + } } else if (spos) // / - block x-,y- { - if (yb > 0 && j > 0 && minx < x) + if (yb > 0 && j > 0 && minx < x) { AddBlockLine(blocklists, blockcount, blockdone, - ncols * (yb - 1) + j - 1, i); + ncols * (yb - 1) + j - 1, i); + } } else if (horiz) // - - block x-,y { - if (j > 0 && minx < x) + if (j > 0 && minx < x) { AddBlockLine(blocklists, blockcount, blockdone, - ncols * yb + j - 1, i); + ncols * yb + j - 1, i); + } } } else if (j > 0 && minx < x) // else not at corner: x-,y + { AddBlockLine(blocklists, blockcount, blockdone, ncols * yb + j - 1, i); + } } } @@ -450,7 +452,6 @@ else if (t > map_maxy) // it contains, intersects the Linedef i. Add i to all the // corresponding // blocklists. - if (!horiz) { for (int j = 0; j < nrows; j++) { // intersection of Linedef with y=yorg+(j< map_maxy) int xp = (x - xorg) & BLOCK_MASK; // x position within block if (xb < 0 || xb > ncols - 1) // outside blockmap, continue + { continue; + } if (y < miny || y > maxy) // line doesn't touch row + { continue; + } // The cell that contains the intersection point is always // added - AddBlockLine(blocklists, blockcount, blockdone, ncols * j + xb, i); @@ -479,38 +483,42 @@ else if (t > map_maxy) // (and whether the line extends past the intersection) // which // blocks are hit - if (xp == 0) // intersection at a corner { if (sneg) // \ - blocks x,y-, x-,y { - if (j > 0 && miny < y) + if (j > 0 && miny < y) { AddBlockLine(blocklists, blockcount, blockdone, - ncols * (j - 1) + xb, i); - if (xb > 0 && minx < x) + ncols * (j - 1) + xb, i); + } + if (xb > 0 && minx < x) { AddBlockLine(blocklists, blockcount, blockdone, - ncols * j + xb - 1, i); + ncols * j + xb - 1, i); + } } else if (vert) // | - block x,y- { - if (j > 0 && miny < y) + if (j > 0 && miny < y) { AddBlockLine(blocklists, blockcount, blockdone, - ncols * (j - 1) + xb, i); + ncols * (j - 1) + xb, i); + } } else if (spos) // / - block x-,y- { - if (xb > 0 && j > 0 && miny < y) + if (xb > 0 && j > 0 && miny < y) { AddBlockLine(blocklists, blockcount, blockdone, - ncols * (j - 1) + xb - 1, i); + ncols * (j - 1) + xb - 1, i); + } } } else if (j > 0 && miny < y) // else not on a corner: x,y- + { AddBlockLine(blocklists, blockcount, blockdone, ncols * (j - 1) + xb, i); + } } } } // Add initial 0 to all blocklists // count the total number of lines (and 0's and -1's) - C2JUtils.memset(blockdone, false, NBlocks); linetotal = 0; @@ -521,7 +529,6 @@ else if (t > map_maxy) } // Create the blockmap lump - // blockmaplump = malloc_IfSameLevel(blockmaplump, 4 + NBlocks + // linetotal); blockmaplump = new int[(4 + NBlocks + linetotal)]; @@ -533,17 +540,16 @@ else if (t > map_maxy) blockmaplump[3] = bmapheight = nrows; // offsets to lists and block lists - for (int i = 0; i < NBlocks; i++) { linelist_t bl = blocklists[i]; - int offs = - blockmaplump[4 + i] = // set offset to block's list + int offs + = blockmaplump[4 + i] + = // set offset to block's list (i != 0 ? blockmaplump[4 + i - 1] : 4 + NBlocks) - + (i != 0 ? blockcount[i - 1] : 0); + + (i != 0 ? blockcount[i - 1] : 0); // add the lines in each block's list to the blockmaplump // delete each list node as we go - while (bl != null) { linelist_t tmp = bl.next; blockmaplump[offs++] = bl.num; @@ -553,13 +559,12 @@ else if (t > map_maxy) long b = System.nanoTime(); - System.err.printf("Blockmap generated in %f sec\n", (b - a) / 1e9); - System.err.printf("Time spend in AddBlockLine : %f sec\n", total / 1e9); + LOGGER.log(Level.WARNING, String.format("Blockmap generated in %f sec", (b - a) / 1e9)); + LOGGER.log(Level.WARNING, String.format("Time spend in AddBlockLine : %f sec", total / 1e9)); } // jff 10/6/98 // End new code added to speed up calculation of internal blockmap - // // P_VerifyBlockMap // @@ -581,7 +586,7 @@ protected boolean VerifyBlockMap(int count) { // check that block offset is in bounds if (blockoffset >= p_maxoffs) { - System.err.printf("P_VerifyBlockMap: block offset overflow\n"); + LOGGER.log(Level.WARNING, String.format("P_VerifyBlockMap: block offset overflow")); return false; } @@ -589,7 +594,7 @@ protected boolean VerifyBlockMap(int count) { // check that list offset is in bounds if (offset < 4 || offset >= count) { - System.err.printf("P_VerifyBlockMap: list offset overflow\n"); + LOGGER.log(Level.WARNING, String.format("P_VerifyBlockMap: list offset overflow")); return false; } @@ -599,17 +604,19 @@ protected boolean VerifyBlockMap(int count) { for (tmplist = p_list;; tmplist++) { // we have overflowed the lump? if (tmplist >= p_maxoffs) { - System.err.printf("P_VerifyBlockMap: open blocklist\n"); + LOGGER.log(Level.WARNING, String.format("P_VerifyBlockMap: open blocklist")); return false; } if (blockmaplump[tmplist] == -1) // found -1 + { break; + } } // scan the list for out-of-range linedef indicies in list for (tmplist = p_list; blockmaplump[tmplist] != -1; tmplist++) { if (blockmaplump[tmplist] < 0 || blockmaplump[tmplist] >= numlines) { - System.err.printf("P_VerifyBlockMap: index >= numlines\n"); + LOGGER.log(Level.WARNING, String.format("P_VerifyBlockMap: index >= numlines")); return false; } } @@ -633,7 +640,6 @@ protected void AddLineToSector(line_t li, sector_t sector) { * * @return */ - protected float rejectDensity() { // float[] rowdensity=new float[numsectors]; float tabledensity; @@ -661,8 +667,8 @@ protected float rejectDensity() { } - protected static int[] POKE_REJECT = new int[] { 1, 2, 4, 8, 16, 32, 64, - 128 }; + protected static int[] POKE_REJECT = new int[]{1, 2, 4, 8, 16, 32, 64, + 128}; /** * Updates Reject table dynamically based on what expensive LOS checks say. @@ -675,7 +681,6 @@ protected float rejectDensity() { * @param x * @param y */ - protected void pokeIntoReject(int x, int y) { // Locate bit pointer e.g. for a 4x4 table, x=2 and y=3 give // 3*4+2=14 @@ -699,8 +704,7 @@ protected void pokeIntoReject(int x, int y) { // next time. rejectmatrix[bytenum] |= POKE_REJECT[bitnum]; - System.out.println(rejectDensity()); - + rejectDensity(); } protected void retrieveFromReject(int x, int y, boolean value) { @@ -726,7 +730,7 @@ protected void retrieveFromReject(int x, int y, boolean value) { // next time. rejectmatrix[bytenum] |= POKE_REJECT[bitnum]; - System.out.println(rejectDensity()); + rejectDensity(); } @@ -743,7 +747,6 @@ protected void retrieveFromReject(int x, int y, boolean value) { // Full 512x512 blockmaps get this value set to -1. // A 511x511 blockmap would still have a valid negative number // e.g. -1..510, so they would be set to -2 - public static final boolean FIX_BLOCKMAP_512 = Engine.getConfig().equals(Settings.fix_blockmap, Boolean.TRUE); public int blockmapxneg = -257; public int blockmapyneg = -257; @@ -754,7 +757,6 @@ protected void retrieveFromReject(int x, int y, boolean value) { * * @return */ - protected final int[] getMapBoundingBox(boolean playable) { int minx = Integer.MAX_VALUE; @@ -793,8 +795,8 @@ protected final int[] getMapBoundingBox(boolean playable) { } } - System.err.printf("Map bounding %d %d %d %d\n", minx >> FRACBITS, - miny >> FRACBITS, maxx >> FRACBITS, maxy >> FRACBITS); + LOGGER.log(Level.WARNING, String.format("Map bounding %d %d %d %d\n", minx >> FRACBITS, + miny >> FRACBITS, maxx >> FRACBITS, maxy >> FRACBITS)); // Blow up bounding to the closest 128-sized block, adding 8 units as // padding. @@ -804,10 +806,10 @@ protected final int[] getMapBoundingBox(boolean playable) { int bckx = ((BLOCKMAPPADDING + maxx) - orgx); int bcky = ((BLOCKMAPPADDING + maxy) - orgy); - System.err.printf("%d %d %d %d\n", orgx >> FRACBITS, orgy >> FRACBITS, - 1 + (bckx >> MAPBLOCKSHIFT), 1 + (bcky >> MAPBLOCKSHIFT)); + LOGGER.log(Level.WARNING, String.format("%d %d %d %d", orgx >> FRACBITS, orgy >> FRACBITS, + 1 + (bckx >> MAPBLOCKSHIFT), 1 + (bcky >> MAPBLOCKSHIFT))); - return new int[] { orgx, orgy, bckx, bcky }; + return new int[]{orgx, orgy, bckx, bcky}; } protected void LoadReject(int lumpnum) { @@ -831,24 +833,24 @@ protected void LoadReject(int lumpnum) { // zeroes. // Much better than overflowing. // TODO: build-in a REJECT-matrix rebuilder? - rejectmatrix = - new byte[(int) (Math - .ceil((this.numsectors * this.numsectors) / 8.0))]; + rejectmatrix + = new byte[(int) (Math + .ceil((this.numsectors * this.numsectors) / 8.0))]; System.arraycopy(tmpreject, 0, rejectmatrix, 0, - Math.min(tmpreject.length, rejectmatrix.length)); + Math.min(tmpreject.length, rejectmatrix.length)); // Do warn on atypical reject map lengths, but use either default // all-zeroes one, // or whatever you happened to read anyway. if (tmpreject.length < rejectmatrix.length) { - System.err.printf("BROKEN REJECT MAP! Length %d expected %d\n", - tmpreject.length, rejectmatrix.length); + LOGGER.log(Level.WARNING, String.format("BROKEN REJECT MAP! Length %d expected %d\n", + tmpreject.length, rejectmatrix.length)); } // Maes: purely academic. Most maps are well above 0.68 // System.out.printf("Reject table density: %f",rejectDensity()); } - + /** * Added config switch to turn on/off support * @@ -859,24 +861,22 @@ protected void LoadReject(int lumpnum) { * @return */ @SourceCode.Compatible("blockx >> MAPBLOCKSHIFT") - public final int getSafeBlockX(int blockx){ + public final int getSafeBlockX(int blockx) { blockx >>= MAPBLOCKSHIFT; return (FIX_BLOCKMAP_512 && blockx <= this.blockmapxneg) ? blockx & 0x1FF : blockx; } - + @SourceCode.Compatible("blockx >> MAPBLOCKSHIFT") public final int getSafeBlockX(long blockx) { blockx >>= MAPBLOCKSHIFT; return (int) ((FIX_BLOCKMAP_512 && blockx <= this.blockmapxneg) ? blockx & 0x1FF : blockx); } - + /** Gets the proper blockmap block for a given Y 16.16 Coordinate, sanitized * for 512-wide blockmaps. * * @param blocky * @return */ - - @SourceCode.Compatible("blocky >> MAPBLOCKSHIFT") public final int getSafeBlockY(int blocky) { blocky >>= MAPBLOCKSHIFT; @@ -890,34 +890,34 @@ public final int getSafeBlockY(long blocky) { } /// Sector tag stuff, lifted off Boom - - /** Hash the sector tags across the sectors and linedefs. - * Call in SpawnSpecials. - */ - - public void InitTagLists() - { - int i; + /** Hash the sector tags across the sectors and linedefs. + * Call in SpawnSpecials. + */ + public void InitTagLists() { + int i; - for (i=numsectors; --i>=0; ) // Initially make all slots empty. - sectors[i].firsttag = -1; - for (i=numsectors; --i>=0; ) // Proceed from last to first sector + for (i = numsectors; --i >= 0;) // Initially make all slots empty. + { + sectors[i].firsttag = -1; + } + for (i = numsectors; --i >= 0;) // Proceed from last to first sector { // so that lower sectors appear first - int j = sectors[i].tag % numsectors; // Hash func - sectors[i].nexttag = sectors[j].firsttag; // Prepend sector to chain - sectors[j].firsttag = i; + int j = sectors[i].tag % numsectors; // Hash func + sectors[i].nexttag = sectors[j].firsttag; // Prepend sector to chain + sectors[j].firsttag = i; } - // killough 4/17/98: same thing, only for linedefs - - for (i=numlines; --i>=0; ) // Initially make all slots empty. - lines[i].firsttag = -1; - for (i=numlines; --i>=0; ) // Proceed from last to first linedef + // killough 4/17/98: same thing, only for linedefs + for (i = numlines; --i >= 0;) // Initially make all slots empty. + { + lines[i].firsttag = -1; + } + for (i = numlines; --i >= 0;) // Proceed from last to first linedef { // so that lower linedefs appear first - int j = lines[i].tag % numlines; // Hash func - lines[i].nexttag = lines[j].firsttag; // Prepend linedef to chain - lines[j].firsttag = i; + int j = lines[i].tag % numlines; // Hash func + lines[i].nexttag = lines[j].firsttag; // Prepend linedef to chain + lines[j].firsttag = i; } } - + } diff --git a/src/p/ActionFunctions.java b/src/p/ActionFunctions.java index df8d2491..aadefa21 100644 --- a/src/p/ActionFunctions.java +++ b/src/p/ActionFunctions.java @@ -26,6 +26,7 @@ import i.IDoomSystem; import java.util.logging.Level; import java.util.logging.Logger; +import mochadoom.Loggers; import p.Actions.ActionsAttacks; import p.Actions.ActionsEnemies; import p.Actions.ActionsThinkers; @@ -40,24 +41,26 @@ import utils.TraitFactory.SharedContext; public class ActionFunctions extends UnifiedGameMap implements - ActionsThinkers, ActionsEnemies, ActionsAttacks, Ai, Attacks, Thinkers, Weapons -{ + ActionsThinkers, ActionsEnemies, ActionsAttacks, Ai, Attacks, Thinkers, Weapons { + + private static final Logger LOGGER = Loggers.getLogger(ActionFunctions.class.getName()); + private final SharedContext traitsSharedContext; - + public ActionFunctions(final DoomMain DOOM) { super(DOOM); this.traitsSharedContext = buildContext(); } - + private SharedContext buildContext() { try { return TraitFactory.build(this, ACTION_KEY_CHAIN); } catch (IllegalArgumentException | IllegalAccessException ex) { - Logger.getLogger(ActionFunctions.class.getName()).log(Level.SEVERE, null, ex); + LOGGER.log(Level.SEVERE, "buildContext failure", ex); throw new RuntimeException(ex); } } - + @Override public AbstractLevelLoader levelLoader() { return DOOM.levelLoader; diff --git a/src/p/Actions/ActionTrait.java b/src/p/Actions/ActionTrait.java index f304222a..f4fdc9b7 100644 --- a/src/p/Actions/ActionTrait.java +++ b/src/p/Actions/ActionTrait.java @@ -62,48 +62,75 @@ import utils.TraitFactory.Trait; public interface ActionTrait extends Trait, ThinkerList { + TraitFactory.KeyChain ACTION_KEY_CHAIN = new TraitFactory.KeyChain(); ContextKey KEY_SLIDEMOVE = ACTION_KEY_CHAIN.newKey(ActionTrait.class, SlideMove::new); ContextKey KEY_SPECHITS = ACTION_KEY_CHAIN.newKey(ActionTrait.class, Spechits::new); ContextKey KEY_MOVEMENT = ACTION_KEY_CHAIN.newKey(ActionTrait.class, Movement::new); - + AbstractLevelLoader levelLoader(); + IHeadsUp headsUp(); + IDoomSystem doomSystem(); + IDoomStatusBar statusBar(); + IAutoMap autoMap(); + SceneRenderer sceneRenderer(); UnifiedGameMap.Specials getSpecials(); + UnifiedGameMap.Switches getSwitches(); + ActionsThinkers getThinkers(); + ActionsEnemies getEnemies(); + ActionsAttacks getAttacks(); void StopSound(ISoundOrigin origin); // DOOM.doomSound.StopSound + void StartSound(ISoundOrigin origin, sounds.sfxenum_t s); // DOOM.doomSound.StartSound + void StartSound(ISoundOrigin origin, int s); // DOOM.doomSound.StartSound player_t getPlayer(int number); //DOOM.players[] + skill_t getGameSkill(); // DOOM.gameskill + mobj_t createMobj(); // mobj_t.from(DOOM); int LevelTime(); // DOOM.leveltime + int P_Random(); + int ConsolePlayerNumber(); // DOOM.consoleplayer + int MapNumber(); // DOOM.gamemap + boolean PlayerInGame(int number); // DOOM.palyeringame + boolean IsFastParm(); // DOOM.fastparm + boolean IsPaused(); // DOOM.paused + boolean IsNetGame(); // DOOM.netgame + boolean IsDemoPlayback(); // DOOM.demoplayback + boolean IsDeathMatch(); // DOOM.deathmatch + boolean IsAutoMapActive(); // DOOM.automapactive + boolean IsMenuActive(); // DOOM.menuactive + boolean CheckThing(mobj_t m); + boolean StompThing(mobj_t m); - + default void SetThingPosition(mobj_t mobj) { levelLoader().SetThingPosition(mobj); } @@ -112,68 +139,70 @@ default void SetThingPosition(mobj_t mobj) { * Try to avoid. */ DoomMain DOOM(); - + final class SlideMove { + // // SLIDE MOVE // Allows the player to slide along any angled walls. // mobj_t slidemo; - + @fixed_t int bestslidefrac, secondslidefrac; - + line_t bestslideline, secondslideline; - + @fixed_t int tmxmove, tmymove; } - + final class Spechits { + line_t[] spechit = new line_t[MAXSPECIALCROSS]; int numspechit; - + // // USE LINES // mobj_t usething; } - + ///////////////// MOVEMENT'S ACTIONS //////////////////////// final class Movement { + /** * If "floatok" true, move would be ok if within "tmfloorz - tmceilingz". */ public boolean floatok; - + @fixed_t public int tmfloorz, - tmceilingz, - tmdropoffz; - + tmceilingz, + tmdropoffz; + // keep track of the line that lowers the ceiling, // so missiles don't explode against sky hack walls public line_t ceilingline; @fixed_t int[] tmbbox = new int[4]; - + mobj_t tmthing; - + long tmflags; - + @fixed_t int tmx, tmy; - + ////////////////////// FROM p_maputl.c //////////////////// @fixed_t int opentop, openbottom, openrange, lowfloor; } - + /** * P_LineOpening Sets opentop and openbottom to the window through a two * sided line. OPTIMIZE: keep this precalculated */ - default void LineOpening(line_t linedef) { final Movement ma = contextRequire(KEY_MOVEMENT); sector_t front; @@ -239,7 +268,6 @@ default boolean BlockThingsIterator(int x, int y, Predicate func) { // the way it was and call P_ChangeSector again // to undo the changes. // - /** * P_BlockLinesIterator The validcount flags are used to avoid checking lines that are marked in multiple mapblocks, * so increment validcount before the first call to P_BlockLinesIterator, then make one or more calls to it. @@ -267,10 +295,7 @@ default boolean BlockLinesIterator(int x, int y, Predicate func) { final int validcount = sr.getValidCount(); // [SYNC ISSUE]: don't skip offset+1 :-/ - for ( - @SourceCode.Compatible("list = blockmaplump+offset ; *list != -1 ; list++") - int list = offset; (lineinblock = ll.blockmap[list]) != -1; list++ - ) { + for (@SourceCode.Compatible("list = blockmaplump+offset ; *list != -1 ; list++") int list = offset; (lineinblock = ll.blockmap[list]) != -1; list++) { ld = ll.lines[lineinblock]; //System.out.println(ld); if (ld.validcount == validcount) { @@ -290,20 +315,20 @@ default void ResizeSpechits() { final Spechits spechits = contextRequire(KEY_SPECHITS); spechits.spechit = C2JUtils.resize(spechits.spechit[0], spechits.spechit, spechits.spechit.length * 2); } - + /** * PIT_CheckLine Adjusts tmfloorz and tmceilingz as lines are contacted * */ - @P_Map.C(PIT_CheckLine) default boolean CheckLine(line_t ld) { + @P_Map.C(PIT_CheckLine) + default boolean CheckLine(line_t ld) { final Spechits spechits = contextRequire(KEY_SPECHITS); final Movement ma = contextRequire(KEY_MOVEMENT); - + if (ma.tmbbox[BOXRIGHT] <= ld.bbox[BOXLEFT] - || ma.tmbbox[BOXLEFT] >= ld.bbox[BOXRIGHT] - || ma.tmbbox[BOXTOP] <= ld.bbox[BOXBOTTOM] - || ma.tmbbox[BOXBOTTOM] >= ld.bbox[BOXTOP]) - { + || ma.tmbbox[BOXLEFT] >= ld.bbox[BOXRIGHT] + || ma.tmbbox[BOXTOP] <= ld.bbox[BOXBOTTOM] + || ma.tmbbox[BOXBOTTOM] >= ld.bbox[BOXTOP]) { return true; } @@ -360,7 +385,9 @@ default void ResizeSpechits() { } return true; - }; + } + + ; // // MOVEMENT CLIPPING @@ -404,7 +431,8 @@ default boolean CheckPosition(mobj_t thing, @fixed_t int x, @fixed_t int y) { ma.tmbbox[BOXRIGHT] = x + ma.tmthing.radius; ma.tmbbox[BOXLEFT] = x - ma.tmthing.radius; - R_PointInSubsector: { + R_PointInSubsector: + { newsubsec = levelLoader().PointInSubsector(x, y); } ma.ceilingline = null; @@ -435,7 +463,8 @@ default boolean CheckPosition(mobj_t thing, @fixed_t int x, @fixed_t int y) { for (bx = xl; bx <= xh; bx++) { for (by = yl; by <= yh; by++) { - P_BlockThingsIterator: { + P_BlockThingsIterator: + { if (!BlockThingsIterator(bx, by, this::CheckThing)) { return false; } @@ -468,7 +497,8 @@ default boolean CheckPosition(mobj_t thing, @fixed_t int x, @fixed_t int y) { } for (bx = xl; bx <= xh; bx++) { for (by = yl; by <= yh; by++) { - P_BlockLinesIterator: { + P_BlockLinesIterator: + { if (!this.BlockLinesIterator(bx, by, this::CheckLine)) { return false; } @@ -478,7 +508,7 @@ default boolean CheckPosition(mobj_t thing, @fixed_t int x, @fixed_t int y) { return true; } - + // // P_ThingHeightClip // Takes a valid thing and adjusts the thing.floorz, @@ -513,7 +543,7 @@ default boolean ThingHeightClip(mobj_t thing) { return thing.ceilingz - thing.floorz >= thing.height; } - + default boolean isblocking(intercept_t in, line_t li) { final SlideMove slideMove = contextRequire(KEY_SLIDEMOVE); // the line does block movement, diff --git a/src/p/Actions/ActionsAttacks.java b/src/p/Actions/ActionsAttacks.java index 94a96059..9226ccfc 100644 --- a/src/p/Actions/ActionsAttacks.java +++ b/src/p/Actions/ActionsAttacks.java @@ -172,7 +172,7 @@ default boolean VileCheck(mobj_t thing) { maxdist = thing.info.radius + mobjinfo[mobjtype_t.MT_VILE.ordinal()].radius; if (Math.abs(thing.x - att.vileTryX) > maxdist - || Math.abs(thing.y - att.vileTryY) > maxdist) { + || Math.abs(thing.y - att.vileTryY) > maxdist) { return true; // not actually touching } diff --git a/src/p/Actions/ActionsCeilings.java b/src/p/Actions/ActionsCeilings.java index a704ab8c..671e60e8 100644 --- a/src/p/Actions/ActionsCeilings.java +++ b/src/p/Actions/ActionsCeilings.java @@ -39,7 +39,9 @@ public interface ActionsCeilings extends ActionsMoveEvents, ActionsUseEvents { ContextKey KEY_CEILINGS = ACTION_KEY_CHAIN.newKey(ActionsCeilings.class, Ceilings::new); void RemoveThinker(thinker_t activeCeiling); + result_e MovePlane(sector_t sector, int speed, int bottomheight, boolean crush, int i, int direction); + int FindSectorFromLineTag(line_t line, int secnum); final class Ceilings { @@ -88,7 +90,7 @@ default void MoveCeiling(ceiling_t ceiling) { case crushAndRaise: ceiling.direction = -1; default: - break; + break; } } break; @@ -249,8 +251,8 @@ default void ActivateInStasisCeiling(line_t line) { final ceiling_t[] activeCeilings = getActiveCeilings(); for (int i = 0; i < activeCeilings.length; ++i) { if (activeCeilings[i] != null - && (activeCeilings[i].tag == line.tag) - && (activeCeilings[i].direction == 0)) { + && (activeCeilings[i].tag == line.tag) + && (activeCeilings[i].direction == 0)) { activeCeilings[i].direction = activeCeilings[i].olddirection; activeCeilings[i].thinkerFunction = ActiveStates.T_MoveCeiling; } @@ -270,8 +272,8 @@ default int CeilingCrushStop(line_t line) { final ceiling_t[] activeCeilings = getActiveCeilings(); for (i = 0; i < activeCeilings.length; ++i) { if (activeCeilings[i] != null - && (activeCeilings[i].tag == line.tag) - && (activeCeilings[i].direction != 0)) { + && (activeCeilings[i].tag == line.tag) + && (activeCeilings[i].direction != 0)) { activeCeilings[i].olddirection = activeCeilings[i].direction; activeCeilings[i].thinkerFunction = ActiveStates.NOP; activeCeilings[i].direction = 0; // in-stasis diff --git a/src/p/Actions/ActionsDoors.java b/src/p/Actions/ActionsDoors.java index e7d7e904..b742022e 100644 --- a/src/p/Actions/ActionsDoors.java +++ b/src/p/Actions/ActionsDoors.java @@ -48,7 +48,9 @@ public interface ActionsDoors extends ActionsMoveEvents, ActionsUseEvents { result_e MovePlane(sector_t sector, int speed, int floorheight, boolean b, int i, int direction); + void RemoveThinker(thinker_t door); + int FindSectorFromLineTag(line_t line, int secnum); // @@ -76,7 +78,7 @@ default void VerticalDoor(vldoor_t door) { StartSound(door.sector.soundorg, sounds.sfxenum_t.sfx_doropn); break; default: - break; + break; } } break; @@ -91,7 +93,7 @@ default void VerticalDoor(vldoor_t door) { StartSound(door.sector.soundorg, sounds.sfxenum_t.sfx_doropn); break; default: - break; + break; } } break; @@ -117,7 +119,7 @@ default void VerticalDoor(vldoor_t door) { door.topcountdown = 35 * 30; break; default: - break; + break; } } else if (res == result_e.crushed) { switch (door.type) { @@ -149,7 +151,7 @@ default void VerticalDoor(vldoor_t door) { RemoveThinker(door); // unlink and free break; default: - break; + break; } } break; @@ -198,7 +200,7 @@ default boolean DoLockedDoor(line_t line, vldoor_e type, mobj_t thing) { /* if ( p==null ) return false; */ if (!p.cards[card_t.it_yellowcard.ordinal()] - && !p.cards[card_t.it_yellowskull.ordinal()]) { + && !p.cards[card_t.it_yellowskull.ordinal()]) { p.message = PD_YELLOWO; StartSound(null, sounds.sfxenum_t.sfx_oof); return false; @@ -273,7 +275,7 @@ default boolean DoDoor(line_t line, vldoor_e type) { StartSound(door.sector.soundorg, sounds.sfxenum_t.sfx_doropn); } default: - break; + break; } } @@ -424,7 +426,7 @@ default void VerticalDoor(line_t line, mobj_t thing) { door.topheight = sec.FindLowestCeilingSurrounding(); door.topheight -= 4 * FRACUNIT; } - + // // Spawn a door that closes after 30 seconds // @@ -433,11 +435,13 @@ default void VerticalDoor(line_t line, mobj_t thing) { default void SpawnDoorCloseIn30(sector_t sector) { vldoor_t door; - Z_Malloc: { + Z_Malloc: + { door = new vldoor_t(); } - P_AddThinker: { + P_AddThinker: + { AddThinker(door); } @@ -460,23 +464,26 @@ default void SpawnDoorCloseIn30(sector_t sector) { default void SpawnDoorRaiseIn5Mins(sector_t sector, int secnum) { vldoor_t door; - Z_Malloc: { + Z_Malloc: + { door = new vldoor_t(); } - P_AddThinker: { + P_AddThinker: + { AddThinker(door); } - + sector.specialdata = door; sector.special = 0; - + door.thinkerFunction = T_VerticalDoor; door.sector = sector; door.direction = 2; door.type = vldoor_e.raiseIn5Mins; door.speed = VDOORSPEED; - P_FindLowestCeilingSurrounding: { + P_FindLowestCeilingSurrounding: + { door.topheight = sector.FindLowestCeilingSurrounding(); } door.topheight -= 4 * FRACUNIT; diff --git a/src/p/Actions/ActionsFloors.java b/src/p/Actions/ActionsFloors.java index c648a113..540a2864 100644 --- a/src/p/Actions/ActionsFloors.java +++ b/src/p/Actions/ActionsFloors.java @@ -38,8 +38,11 @@ public interface ActionsFloors extends ActionsPlats { result_e MovePlane(sector_t sector, int speed, int floordestheight, boolean crush, int i, int direction); + boolean twoSided(int secnum, int i); + side_t getSide(int secnum, int i, int s); + sector_t getSector(int secnum, int i, int i0); // @@ -78,7 +81,7 @@ default void MoveFloor(floormove_t floor) { floor.sector.special = (short) floor.newspecial; floor.sector.floorpic = floor.texture; default: - break; + break; } } @@ -150,7 +153,7 @@ default boolean DoFloor(line_t line, floor_e floortype) { floor.floordestheight = sec.ceilingheight; } floor.floordestheight -= (8 * FRACUNIT) - * eval(floortype == floor_e.raiseFloorCrush); + * eval(floortype == floor_e.raiseFloorCrush); break; case raiseFloorTurbo: @@ -239,7 +242,7 @@ default boolean DoFloor(line_t line, floor_e floortype) { } } default: - break; + break; } } return rtn; @@ -359,7 +362,7 @@ default void PlatRaise(plat_t plat) { res = MovePlane(plat.sector, plat.speed, plat.high, plat.crush, 0, 1); if (plat.type == plattype_e.raiseAndChange - || plat.type == plattype_e.raiseToNearestAndChange) { + || plat.type == plattype_e.raiseToNearestAndChange) { if (!eval(LevelTime() & 7)) { StartSound(plat.sector.soundorg, sounds.sfxenum_t.sfx_stnmov); } diff --git a/src/p/Actions/ActionsLights.java b/src/p/Actions/ActionsLights.java index 35ffe7f0..b3386b7d 100644 --- a/src/p/Actions/ActionsLights.java +++ b/src/p/Actions/ActionsLights.java @@ -44,11 +44,12 @@ public interface ActionsLights extends ActionsMoveEvents, ActionsUseEvents { int FindSectorFromLineTag(line_t line, int secnum); - + // // P_LIGHTS // public class fireflicker_t extends SectorAction { + public int count; public int maxlight; public int minlight; @@ -87,14 +88,13 @@ public void pack(ByteBuffer b) throws IOException { b.putInt(mintime);//36 } } - + public class glow_t extends SectorAction { public int minlight; public int maxlight; public int direction; - @Override public void read(DataInputStream f) throws IOException { @@ -114,7 +114,7 @@ public void pack(ByteBuffer b) throws IOException { b.putInt(direction);//38 } } - + // // Find minimum light from an adjacent sector // @@ -128,7 +128,8 @@ default int FindMinSurroundingLight(sector_t sector, int max) { min = max; for (int i = 0; i < sector.linecount; i++) { line = sector.lines[i]; - getNextSector: { + getNextSector: + { check = line.getNextSector(sector); } @@ -142,7 +143,7 @@ default int FindMinSurroundingLight(sector_t sector, int max) { } return min; } - + /** * P_SpawnLightFlash After the map has been loaded, scan each sector for * specials that spawn thinkers @@ -155,11 +156,13 @@ default void SpawnLightFlash(sector_t sector) { // nothing special about it during gameplay sector.special = 0; - Z_Malloc: { + Z_Malloc: + { flash = new lightflash_t(); } - P_AddThinker: { + P_AddThinker: + { AddThinker(flash); } @@ -183,11 +186,13 @@ default void SpawnLightFlash(sector_t sector) { default void SpawnStrobeFlash(sector_t sector, int fastOrSlow, int inSync) { strobe_t flash; - Z_Malloc: { + Z_Malloc: + { flash = new strobe_t(); } - P_AddThinker: { + P_AddThinker: + { AddThinker(flash); } @@ -217,16 +222,19 @@ default void SpawnStrobeFlash(sector_t sector, int fastOrSlow, int inSync) { default void SpawnGlowingLight(sector_t sector) { glow_t g; - Z_Malloc: { + Z_Malloc: + { g = new glow_t(); } - P_AddThinker: { + P_AddThinker: + { AddThinker(g); } g.sector = sector; - P_FindMinSurroundingLight: { + P_FindMinSurroundingLight: + { g.minlight = FindMinSurroundingLight(sector, sector.lightlevel); } g.maxlight = sector.lightlevel; @@ -269,14 +277,16 @@ default void SpawnFireFlicker(sector_t sector) { // Nothing special about it during gameplay. sector.special = 0; - Z_Malloc: { + Z_Malloc: + { flick = new fireflicker_t(); } - - P_AddThinker: { + + P_AddThinker: + { AddThinker(flick); } - + flick.thinkerFunction = T_FireFlicker; flick.sector = sector; flick.maxlight = sector.lightlevel; diff --git a/src/p/Actions/ActionsMobj.java b/src/p/Actions/ActionsMobj.java index 0679e920..955ee2ec 100644 --- a/src/p/Actions/ActionsMobj.java +++ b/src/p/Actions/ActionsMobj.java @@ -99,22 +99,22 @@ default void DamageMobj(mobj_t target, mobj_t inflictor, mobj_t source, int dama // inflict thrust and push the victim out of reach, // thus kick away unless using the chainsaw. if ((inflictor != null) - && !eval(target.flags & MF_NOCLIP) - && (source == null - || source.player == null - || source.player.readyweapon != weapontype_t.wp_chainsaw)) { + && !eval(target.flags & MF_NOCLIP) + && (source == null + || source.player == null + || source.player.readyweapon != weapontype_t.wp_chainsaw)) { ang = sceneRenderer().PointToAngle2(inflictor.x, - inflictor.y, - target.x, - target.y) & BITS32; + inflictor.y, + target.x, + target.y) & BITS32; thrust = damage * (MAPFRACUNIT >> 3) * 100 / target.info.mass; // make fall forwards sometimes if ((damage < 40) - && (damage > target.health) - && (target.z - inflictor.z > 64 * FRACUNIT) - && eval(P_Random() & 1)) { + && (damage > target.health) + && (target.z - inflictor.z > 64 * FRACUNIT) + && eval(P_Random() & 1)) { ang += ANG180; thrust *= 4; } @@ -128,15 +128,15 @@ && eval(P_Random() & 1)) { if (player != null) { // end of game hell hack if (target.subsector.sector.special == 11 - && damage >= target.health) { + && damage >= target.health) { damage = target.health - 1; } // Below certain threshold, // ignore damage in GOD mode, or with INVUL power. if (damage < 1000 - && (eval(player.cheats & player_t.CF_GODMODE)) - || player.powers[pw_invulnerability] != 0) { + && (eval(player.cheats & player_t.CF_GODMODE)) + || player.powers[pw_invulnerability] != 0) { return; } @@ -181,7 +181,7 @@ && eval(P_Random() & 1)) { } if ((P_Random() < target.info.painchance) - && !eval(target.flags & MF_SKULLFLY)) { + && !eval(target.flags & MF_SKULLFLY)) { target.flags |= MF_JUSTHIT; // fight back! target.SetMobjState(target.info.painstate); @@ -190,14 +190,14 @@ && eval(P_Random() & 1)) { target.reactiontime = 0; // we're awake now... if (((target.threshold == 0) || (target.type == mobjtype_t.MT_VILE)) - && (source != null) && (source != target) - && (source.type != mobjtype_t.MT_VILE)) { + && (source != null) && (source != target) + && (source.type != mobjtype_t.MT_VILE)) { // if not intent on another player, // chase after this one target.target = source; target.threshold = BASETHRESHOLD; if (target.mobj_state == states[target.info.spawnstate.ordinal()] - && target.info.seestate != statenum_t.S_NULL) { + && target.info.seestate != statenum_t.S_NULL) { target.SetMobjState(target.info.seestate); } } @@ -303,9 +303,9 @@ default void KillMobj(mobj_t source, mobj_t target) { @SourceCode.P_Mobj.C(P_RemoveMobj) default void RemoveMobj(mobj_t mobj) { if (eval(mobj.flags & MF_SPECIAL) - && !eval(mobj.flags & MF_DROPPED) - && (mobj.type != mobjtype_t.MT_INV) - && (mobj.type != mobjtype_t.MT_INS)) { + && !eval(mobj.flags & MF_DROPPED) + && (mobj.type != mobjtype_t.MT_INV) + && (mobj.type != mobjtype_t.MT_INS)) { final RespawnQueue resp = contextRequire(KEY_RESP_QUEUE); resp.itemrespawnque[resp.iquehead] = mobj.spawnpoint; resp.itemrespawntime[resp.iquehead] = LevelTime(); @@ -377,7 +377,7 @@ default void UnsetThingPosition(mobj_t thing) { blocky = ll.getSafeBlockY(thing.y - ll.bmaporgy); if (blockx >= 0 && blockx < ll.bmapwidth - && blocky >= 0 && blocky < ll.bmapheight) { + && blocky >= 0 && blocky < ll.bmapheight) { ll.blocklinks[blocky * ll.bmapwidth + blockx] = (mobj_t) thing.bnext; } } diff --git a/src/p/Actions/ActionsMoveEvents.java b/src/p/Actions/ActionsMoveEvents.java index b76e6950..6236fb4b 100644 --- a/src/p/Actions/ActionsMoveEvents.java +++ b/src/p/Actions/ActionsMoveEvents.java @@ -28,15 +28,25 @@ public interface ActionsMoveEvents extends ActionTrait { boolean DoDoor(line_t line, vldoor_e type); + boolean DoFloor(line_t line, floor_e floor_e); + boolean DoPlat(line_t line, plattype_e plattype_e, int i); + boolean BuildStairs(line_t line, stair_e stair_e); + boolean DoCeiling(line_t line, ceiling_e ceiling_e); + void StopPlat(line_t line); + void LightTurnOn(line_t line, int i); + void StartLightStrobing(line_t line); + void TurnTagLightsOff(line_t line); + int Teleport(line_t line, int side, mobj_t thing); + int CeilingCrushStop(line_t line); // diff --git a/src/p/Actions/ActionsMovement.java b/src/p/Actions/ActionsMovement.java index dcad8afc..50a25f7a 100644 --- a/src/p/Actions/ActionsMovement.java +++ b/src/p/Actions/ActionsMovement.java @@ -71,6 +71,7 @@ public interface ActionsMovement extends ActionsPathTraverse { int FUDGE = 2048; ///(FRACUNIT/MAPFRACUNIT); void UnsetThingPosition(mobj_t thing); + void ExplodeMissile(mobj_t mo); final class DirType { @@ -570,7 +571,7 @@ default void XYMovement(mobj_t mo) { } else if (eval(mo.flags & MF_MISSILE)) { // explode a missile if (mv.ceilingline != null && mv.ceilingline.backsector != null - && mv.ceilingline.backsector.ceilingpic == DOOM().textureManager.getSkyFlatNum()) { + && mv.ceilingline.backsector.ceilingpic == DOOM().textureManager.getSkyFlatNum()) { // Hack to prevent missiles exploding // against the sky. // Does not handle sky floors. @@ -601,9 +602,9 @@ default void XYMovement(mobj_t mo) { // do not stop sliding // if halfway off a step with some momentum if (mo.momx > FRACUNIT / 4 - || mo.momx < -FRACUNIT / 4 - || mo.momy > FRACUNIT / 4 - || mo.momy < -FRACUNIT / 4) { + || mo.momx < -FRACUNIT / 4 + || mo.momy > FRACUNIT / 4 + || mo.momy < -FRACUNIT / 4) { if (mo.floorz != mo.subsector.sector.floorheight) { return; } @@ -611,7 +612,7 @@ default void XYMovement(mobj_t mo) { } if (mo.momx > -STOPSPEED && mo.momx < STOPSPEED && mo.momy > -STOPSPEED && mo.momy < STOPSPEED - && (player == null || (player.cmd.forwardmove == 0 && player.cmd.sidemove == 0))) { + && (player == null || (player.cmd.forwardmove == 0 && player.cmd.sidemove == 0))) { // if in a walking frame, stop moving // TODO: we need a way to get state indexed inside of states[], to sim pointer arithmetic. // FIX: added an "id" field. @@ -659,10 +660,10 @@ default boolean SlideTraverse(intercept_t in) { LineOpening(li); if ((ma.openrange < slideMove.slidemo.height) - || // doesn't fit - (ma.opentop - slideMove.slidemo.z < slideMove.slidemo.height) - || // mobj is too high - (ma.openbottom - slideMove.slidemo.z > 24 * FRACUNIT)) // too big a step up + || // doesn't fit + (ma.opentop - slideMove.slidemo.z < slideMove.slidemo.height) + || // mobj is too high + (ma.openbottom - slideMove.slidemo.z > 24 * FRACUNIT)) // too big a step up { if (in.frac < slideMove.bestslidefrac) { slideMove.secondslidefrac = slideMove.bestslidefrac; diff --git a/src/p/Actions/ActionsPathTraverse.java b/src/p/Actions/ActionsPathTraverse.java index c6e30b77..03b6660c 100644 --- a/src/p/Actions/ActionsPathTraverse.java +++ b/src/p/Actions/ActionsPathTraverse.java @@ -201,7 +201,7 @@ default boolean PathTraverse(int x1, int y1, int x2, int y2, int flags, Predicat } if (mapx == xt2 - && mapy == yt2) { + && mapy == yt2) { break; } @@ -233,7 +233,7 @@ default boolean AddLineIntercepts(line_t ld) { // avoid precision problems with two routines if (sp.trace.dx > FRACUNIT * 16 || sp.trace.dy > FRACUNIT * 16 - || sp.trace.dx < -FRACUNIT * 16 || sp.trace.dy < -FRACUNIT * 16) { + || sp.trace.dx < -FRACUNIT * 16 || sp.trace.dy < -FRACUNIT * 16) { s1 = sp.trace.PointOnDivlineSide(ld.v1x, ld.v1y); s2 = sp.trace.PointOnDivlineSide(ld.v2x, ld.v2y); //s1 = obs.trace.DivlineSide(ld.v1x, ld.v1.y); diff --git a/src/p/Actions/ActionsPlats.java b/src/p/Actions/ActionsPlats.java index 4e30b992..feb7697d 100644 --- a/src/p/Actions/ActionsPlats.java +++ b/src/p/Actions/ActionsPlats.java @@ -44,6 +44,7 @@ public interface ActionsPlats extends ActionsMoveEvents, ActionsUseEvents { ContextKey KEY_PLATS = ACTION_KEY_CHAIN.newKey(ActionsPlats.class, Plats::new); int FindSectorFromLineTag(line_t line, int secnum); + void RemoveThinker(thinker_t activeplat); final class Plats { diff --git a/src/p/Actions/ActionsSectors.java b/src/p/Actions/ActionsSectors.java index eeed96b0..51fbcaa3 100644 --- a/src/p/Actions/ActionsSectors.java +++ b/src/p/Actions/ActionsSectors.java @@ -55,7 +55,9 @@ public interface ActionsSectors extends ActionsLights, ActionsFloors, ActionsDoo ContextKey KEY_CRUSHES = ACTION_KEY_CHAIN.newKey(ActionsSectors.class, Crushes::new); void RemoveMobj(mobj_t thing); + void DamageMobj(mobj_t thing, mobj_t tmthing, mobj_t tmthing0, int damage); + mobj_t SpawnMobj(@fixed_t int x, @fixed_t int y, @fixed_t int z, mobjtype_t type); final class Crushes { @@ -464,7 +466,7 @@ default sector_t getSector(int currentSector, int line, int side) { default boolean twoSided(int sector, int line) { return eval((levelLoader().sectors[sector].lines[line]).flags & ML_TWOSIDED); } - + default void ClearRespawnQueue() { // clear special respawning que final RespawnQueue rq = contextRequire(KEY_RESP_QUEUE); diff --git a/src/p/Actions/ActionsSight.java b/src/p/Actions/ActionsSight.java index df387abf..35f82db2 100644 --- a/src/p/Actions/ActionsSight.java +++ b/src/p/Actions/ActionsSight.java @@ -184,7 +184,7 @@ default boolean CrossSubsector(int num) { // no wall to block sight with? if (front.floorheight == back.floorheight - && front.ceilingheight == back.ceilingheight) { + && front.ceilingheight == back.ceilingheight) { continue; } diff --git a/src/p/Actions/ActionsSlideDoors.java b/src/p/Actions/ActionsSlideDoors.java index 62f502ac..d1ede476 100644 --- a/src/p/Actions/ActionsSlideDoors.java +++ b/src/p/Actions/ActionsSlideDoors.java @@ -2,6 +2,7 @@ import doom.thinker_t; import java.util.logging.Level; +import java.util.logging.Logger; import mochadoom.Loggers; import p.AbstractLevelLoader; import static p.ActiveStates.T_SlidingDoor; @@ -20,6 +21,8 @@ public interface ActionsSlideDoors extends ActionTrait { + static final Logger LOGGER = Loggers.getLogger(ActionsSlideDoors.class.getName()); + ContextKey KEY_SLIDEDOORS = ACTION_KEY_CHAIN.newKey(ActionsSlideDoors.class, SlideDoors::new); void RemoveThinker(thinker_t t); @@ -47,6 +50,7 @@ public interface ActionsSlideDoors extends ActionTrait { }; final class SlideDoors { + slideframe_t[] slideFrames = malloc(slideframe_t::new, slideframe_t[]::new, MAXSLIDEDOORS); } @@ -85,7 +89,7 @@ default void SlidingDoor(slidedoor_t door) { if (door.timer-- == 0) { // CAN DOOR CLOSE? if (door.frontsector.thinglist != null - || door.backsector.thinglist != null) { + || door.backsector.thinglist != null) { door.timer = ActionsSlideDoors.SDOORWAIT; break; } @@ -185,7 +189,7 @@ default void EV_SlidingDoor(line_t line, mobj_t thing) { return; } - Loggers.getLogger(ActionsSlideDoors.class.getName()).log(Level.WARNING, "EV_SlidingDoor"); + LOGGER.log(Level.WARNING, "EV_SlidingDoor"); // Make sure door isn't already being animated sec = line.frontsector; diff --git a/src/p/Actions/ActionsSpawns.java b/src/p/Actions/ActionsSpawns.java index 00c65904..dc86ca2e 100644 --- a/src/p/Actions/ActionsSpawns.java +++ b/src/p/Actions/ActionsSpawns.java @@ -212,7 +212,8 @@ default void SpawnPlayer(mapthing_t mthing) { p = getPlayer(mthing.type - 1); if (p.playerstate == PST_REBORN) { - G_PlayerReborn: { + G_PlayerReborn: + { p.PlayerReborn(); } } @@ -221,7 +222,8 @@ default void SpawnPlayer(mapthing_t mthing) { x = mthing.x << FRACBITS; y = mthing.y << FRACBITS; z = ONFLOORZ; - P_SpawnMobj: { + P_SpawnMobj: + { mobj = this.SpawnMobj(x, y, z, mobjtype_t.MT_PLAYER); } @@ -245,7 +247,8 @@ default void SpawnPlayer(mapthing_t mthing) { p.viewheight = VIEWHEIGHT; // setup gun psprite - P_SetupPsprites: { + P_SetupPsprites: + { p.SetupPsprites(); } @@ -258,11 +261,13 @@ default void SpawnPlayer(mapthing_t mthing) { if (mthing.type - 1 == ConsolePlayerNumber()) { // wake up the status bar - ST_Start: { + ST_Start: + { statusBar().Start(); } // wake up the heads up text - HU_Start: { + HU_Start: + { headsUp().Start(); } } @@ -317,9 +322,11 @@ default mobj_t SpawnMapThing(mapthing_t mthing) { } switch (getGameSkill()) { - case sk_baby: bit = 1; + case sk_baby: + bit = 1; break; - case sk_nightmare: bit = 4; + case sk_nightmare: + bit = 4; break; default: bit = 1 << (getGameSkill().ordinal() - 1); @@ -342,7 +349,7 @@ default mobj_t SpawnMapThing(mapthing_t mthing) { // warning message for the player. if (i == NUMMOBJTYPES) { Spawn.LOGGER.log(Level.WARNING, - String.format("P_SpawnMapThing: Unknown type %d at (%d, %d)", mthing.type, mthing.x, mthing.y)); + String.format("P_SpawnMapThing: Unknown type %d at (%d, %d)", mthing.type, mthing.x, mthing.y)); return null; } diff --git a/src/p/Actions/ActionsThings.java b/src/p/Actions/ActionsThings.java index 4e41e263..7ba6c597 100644 --- a/src/p/Actions/ActionsThings.java +++ b/src/p/Actions/ActionsThings.java @@ -17,7 +17,13 @@ */ package p.Actions; -import static data.Defines.*; +import static data.Defines.NUMAMMO; +import static data.Defines.pw_allmap; +import static data.Defines.pw_infrared; +import static data.Defines.pw_invisibility; +import static data.Defines.pw_invulnerability; +import static data.Defines.pw_ironfeet; +import static data.Defines.pw_strength; import data.mobjtype_t; import data.sounds.sfxenum_t; import defines.ammotype_t; @@ -33,12 +39,20 @@ import m.Settings; import static m.fixed_t.FRACUNIT; import p.mobj_t; -import static p.mobj_t.*; +import static p.mobj_t.MF_COUNTITEM; +import static p.mobj_t.MF_DROPPED; +import static p.mobj_t.MF_MISSILE; +import static p.mobj_t.MF_PICKUP; +import static p.mobj_t.MF_SHOOTABLE; +import static p.mobj_t.MF_SKULLFLY; +import static p.mobj_t.MF_SOLID; +import static p.mobj_t.MF_SPECIAL; import static utils.C2JUtils.eval; public interface ActionsThings extends ActionTrait { void DamageMobj(mobj_t thing, mobj_t tmthing, mobj_t tmthing0, int damage); + void RemoveMobj(mobj_t special); /** @@ -60,7 +74,7 @@ default boolean CheckThing(mobj_t thing) { blockdist = thing.radius + movm.tmthing.radius; if (Math.abs(thing.x - movm.tmx) >= blockdist - || Math.abs(thing.y - movm.tmy) >= blockdist) { + || Math.abs(thing.y - movm.tmy) >= blockdist) { // didn't hit it return true; } @@ -94,8 +108,8 @@ default boolean CheckThing(mobj_t thing) { return true; // underneath } if (movm.tmthing.target != null && (movm.tmthing.target.type == thing.type - || (movm.tmthing.target.type == mobjtype_t.MT_KNIGHT && thing.type == mobjtype_t.MT_BRUISER) - || (movm.tmthing.target.type == mobjtype_t.MT_BRUISER && thing.type == mobjtype_t.MT_KNIGHT))) { + || (movm.tmthing.target.type == mobjtype_t.MT_KNIGHT && thing.type == mobjtype_t.MT_BRUISER) + || (movm.tmthing.target.type == mobjtype_t.MT_BRUISER && thing.type == mobjtype_t.MT_KNIGHT))) { // Don't hit same species as originator. if (thing == movm.tmthing.target) { return true; @@ -452,7 +466,7 @@ default void TouchSpecialThing(mobj_t special, mobj_t toucher) { case SPR_MGUN: if (!player.GiveWeapon(weapontype_t.wp_chaingun, - (special.flags & MF_DROPPED) != 0)) { + (special.flags & MF_DROPPED) != 0)) { return; } player.message = GOTCHAINGUN; @@ -485,7 +499,7 @@ default void TouchSpecialThing(mobj_t special, mobj_t toucher) { case SPR_SHOT: if (!player.GiveWeapon(weapontype_t.wp_shotgun, - (special.flags & MF_DROPPED) != 0)) { + (special.flags & MF_DROPPED) != 0)) { return; } player.message = GOTSHOTGUN; @@ -494,7 +508,7 @@ default void TouchSpecialThing(mobj_t special, mobj_t toucher) { case SPR_SGN2: if (!player.GiveWeapon(weapontype_t.wp_supershotgun, - (special.flags & MF_DROPPED) != 0)) { + (special.flags & MF_DROPPED) != 0)) { return; } player.message = GOTSHOTGUN2; diff --git a/src/p/Actions/ActionsThinkers.java b/src/p/Actions/ActionsThinkers.java index 8e37578b..5baa4e6b 100644 --- a/src/p/Actions/ActionsThinkers.java +++ b/src/p/Actions/ActionsThinkers.java @@ -35,13 +35,16 @@ import static doom.SourceCode.P_Tick.P_RemoveThinker; import doom.thinker_t; import static m.fixed_t.FRACBITS; - -import p.*; +import p.AbstractLevelLoader; +import p.ActiveStates; import p.ActiveStates.MobjConsumer; -import static p.ActiveStates.NOP; import p.ActiveStates.ThinkerConsumer; import static p.DoorDefines.FASTDARK; import static p.DoorDefines.SLOWDARK; +import p.RemoveState; +import p.ThinkerList; +import p.UnifiedGameMap; +import p.mobj_t; import static p.mobj_t.MF_SPAWNCEILING; import rr.sector_t; import rr.subsector_t; @@ -111,28 +114,32 @@ default void SpawnSpecials() { switch (sector.special) { case 1: // FLICKERING LIGHTS - P_SpawnLightFlash: { + P_SpawnLightFlash: + { SpawnLightFlash(sector); } break; case 2: // STROBE FAST - P_SpawnStrobeFlash: { + P_SpawnStrobeFlash: + { SpawnStrobeFlash(sector, FASTDARK, 0); } break; case 3: // STROBE SLOW - P_SpawnStrobeFlash: { + P_SpawnStrobeFlash: + { SpawnStrobeFlash(sector, SLOWDARK, 0); } break; case 4: // STROBE FAST/DEATH SLIME - P_SpawnStrobeFlash: { + P_SpawnStrobeFlash: + { SpawnStrobeFlash(sector, FASTDARK, 0); } sector.special = 4; @@ -140,7 +147,8 @@ default void SpawnSpecials() { case 8: // GLOWING LIGHT - P_SpawnGlowingLight: { + P_SpawnGlowingLight: + { SpawnGlowingLight(sector); } break; @@ -151,34 +159,39 @@ default void SpawnSpecials() { case 10: // DOOR CLOSE IN 30 SECONDS - SpawnDoorCloseIn30: { + SpawnDoorCloseIn30: + { SpawnDoorCloseIn30(sector); } break; case 12: // SYNC STROBE SLOW - P_SpawnStrobeFlash: { + P_SpawnStrobeFlash: + { SpawnStrobeFlash(sector, SLOWDARK, 1); } break; case 13: // SYNC STROBE FAST - P_SpawnStrobeFlash: { + P_SpawnStrobeFlash: + { SpawnStrobeFlash(sector, FASTDARK, 1); } break; case 14: // DOOR RAISE IN 5 MINUTES - P_SpawnDoorRaiseIn5Mins: { + P_SpawnDoorRaiseIn5Mins: + { SpawnDoorRaiseIn5Mins(sector, i); } break; case 17: - P_SpawnFireFlicker: { + P_SpawnFireFlicker: + { SpawnFireFlicker(sector); } break; @@ -205,7 +218,7 @@ default void SpawnSpecials() { for (int i = 0; i < this.getMaxCeilings(); i++) { this.getActiveCeilings()[i] = null; } - + getSwitches().initButtonList(); // UNUSED: no horizonal sliders. @@ -293,7 +306,7 @@ default void RunThinkers() { thinker.prev.next = thinker.next; // Z_Free (currentthinker); } else { - ActiveStates thinkerFunction = (ActiveStates)thinker.thinkerFunction; + ActiveStates thinkerFunction = (ActiveStates) thinker.thinkerFunction; if (thinkerFunction.isParamType(MobjConsumer.class)) { thinkerFunction.fun(MobjConsumer.class).accept(DOOM().actions, (mobj_t) thinker); } else if (thinkerFunction.isParamType(ThinkerConsumer.class)) { diff --git a/src/p/Actions/ActionsUseEvents.java b/src/p/Actions/ActionsUseEvents.java index c3e1f674..c65553ed 100644 --- a/src/p/Actions/ActionsUseEvents.java +++ b/src/p/Actions/ActionsUseEvents.java @@ -42,14 +42,23 @@ public interface ActionsUseEvents extends ActionTrait { void VerticalDoor(line_t line, mobj_t thing); + void LightTurnOn(line_t line, int i); + boolean BuildStairs(line_t line, stair_e stair_e); + boolean DoDonut(line_t line); + boolean DoFloor(line_t line, floor_e floor_e); + boolean DoDoor(line_t line, vldoor_e vldoor_e); + boolean DoPlat(line_t line, plattype_e plattype_e, int i); + boolean DoCeiling(line_t line, ceiling_e ceiling_e); + boolean DoLockedDoor(line_t line, vldoor_e vldoor_e, mobj_t thing); + boolean PathTraverse(int x1, int y1, int x2, int y2, int flags, Predicate trav); /** diff --git a/src/p/Actions/ActiveStates/Ai.java b/src/p/Actions/ActiveStates/Ai.java index 35f679f0..0606b91f 100644 --- a/src/p/Actions/ActiveStates/Ai.java +++ b/src/p/Actions/ActiveStates/Ai.java @@ -23,7 +23,6 @@ import data.sounds; import defines.skill_t; import defines.statenum_t; -import p.ActiveStates; import p.mobj_t; import static p.mobj_t.MF_AMBUSH; import static p.mobj_t.MF_COUNTKILL; @@ -35,6 +34,7 @@ import static utils.C2JUtils.eval; public interface Ai extends Monsters, Sounds { + // // A_Look // Stay in state until a player is sighted. @@ -47,7 +47,7 @@ default void A_Look(mobj_t actor) { targ = actor.subsector.sector.soundtarget; if (targ != null - && eval(targ.flags & MF_SHOOTABLE)) { + && eval(targ.flags & MF_SHOOTABLE)) { actor.target = targ; if (eval(actor.flags & MF_AMBUSH)) { @@ -270,7 +270,7 @@ default void P_MobjThinker(mobj_t mobj) { getEnemies().NightmareRespawn(mobj); } } - + // // A_FaceTarget // @@ -283,9 +283,9 @@ default void A_FaceTarget(mobj_t actor) { actor.flags &= ~MF_AMBUSH; actor.angle = sceneRenderer().PointToAngle2(actor.x, - actor.y, - actor.target.x, - actor.target.y) & BITS32; + actor.y, + actor.target.x, + actor.target.y) & BITS32; if (eval(actor.target.flags & MF_SHADOW)) { actor.angle += (P_Random() - P_Random()) << 21; diff --git a/src/p/Actions/ActiveStates/Attacks.java b/src/p/Actions/ActiveStates/Attacks.java index 2c4927f8..9e014b2b 100644 --- a/src/p/Actions/ActiveStates/Attacks.java +++ b/src/p/Actions/ActiveStates/Attacks.java @@ -39,14 +39,14 @@ import static utils.C2JUtils.eval; public interface Attacks extends Monsters { + // plasma cells for a bfg attack // IDEA: make action functions partially parametrizable? int BFGCELLS = 40; - + // // A_FirePistol // - default void A_FirePistol(player_t player, pspdef_t psp) { StartSound(player.mo, sounds.sfxenum_t.sfx_pistol); @@ -54,8 +54,8 @@ default void A_FirePistol(player_t player, pspdef_t psp) { player.ammo[weaponinfo[player.readyweapon.ordinal()].ammo.ordinal()]--; player.SetPsprite( - ps_flash, - weaponinfo[player.readyweapon.ordinal()].flashstate); + ps_flash, + weaponinfo[player.readyweapon.ordinal()].flashstate); getAttacks().P_BulletSlope(player.mo); getAttacks().P_GunShot(player.mo, !eval(player.refire)); @@ -73,8 +73,8 @@ default void A_FireShotgun(player_t player, pspdef_t psp) { player.ammo[weaponinfo[player.readyweapon.ordinal()].ammo.ordinal()]--; player.SetPsprite( - ps_flash, - weaponinfo[player.readyweapon.ordinal()].flashstate); + ps_flash, + weaponinfo[player.readyweapon.ordinal()].flashstate); getAttacks().P_BulletSlope(player.mo); @@ -97,8 +97,8 @@ default void A_FireShotgun2(player_t player, pspdef_t psp) { player.ammo[weaponinfo[player.readyweapon.ordinal()].ammo.ordinal()] -= 2; player.SetPsprite( - ps_flash, - weaponinfo[player.readyweapon.ordinal()].flashstate); + ps_flash, + weaponinfo[player.readyweapon.ordinal()].flashstate); getAttacks().P_BulletSlope(player.mo); @@ -115,7 +115,8 @@ default void A_FireShotgun2(player_t player, pspdef_t psp) { // default void A_Punch(player_t player, pspdef_t psp) { final Spawn sp = contextRequire(KEY_SPAWN); - @angle_t long angle; + @angle_t + long angle; int damage; int slope; @@ -137,10 +138,10 @@ default void A_Punch(player_t player, pspdef_t psp) { if (eval(sp.linetarget)) { StartSound(player.mo, sounds.sfxenum_t.sfx_punch); player.mo.angle = sceneRenderer().PointToAngle2( - player.mo.x, - player.mo.y, - sp.linetarget.x, - sp.linetarget.y + player.mo.x, + player.mo.y, + sp.linetarget.x, + sp.linetarget.y ) & BITS32; } } @@ -150,7 +151,8 @@ default void A_Punch(player_t player, pspdef_t psp) { // default void A_Saw(player_t player, pspdef_t psp) { final Spawn sp = contextRequire(KEY_SPAWN); - @angle_t long angle; + @angle_t + long angle; int damage; int slope; @@ -171,7 +173,7 @@ default void A_Saw(player_t player, pspdef_t psp) { // turn to face target angle = sceneRenderer().PointToAngle2(player.mo.x, player.mo.y, - sp.linetarget.x, sp.linetarget.y) & BITS32; + sp.linetarget.x, sp.linetarget.y) & BITS32; /* FIXME: this comparison is going to fail.... or not? If e.g. angle = 359 degrees (which will be mapped to a small negative number), and player.mo.angle = 160 degrees (a large, positive value), the result will be a @@ -253,8 +255,8 @@ default void A_FirePlasma(player_t player, pspdef_t psp) { player.ammo[weaponinfo[player.readyweapon.ordinal()].ammo.ordinal()]--; player.SetPsprite( - ps_flash, - weaponinfo[player.readyweapon.ordinal()].flashstate); + ps_flash, + weaponinfo[player.readyweapon.ordinal()].flashstate); getAttacks().SpawnPlayerMissile(player.mo, mobjtype_t.MT_PLASMA); } @@ -275,7 +277,7 @@ default void A_Pain(mobj_t actor) { default void A_Explode(mobj_t thingy) { getAttacks().RadiusAttack(thingy, thingy.target, 128); } - + // // A_BFGSpray // Spawn a BFG explosion on every monster in view diff --git a/src/p/Actions/ActiveStates/MonsterStates/Bosses.java b/src/p/Actions/ActiveStates/MonsterStates/Bosses.java index c885dec8..a538da43 100644 --- a/src/p/Actions/ActiveStates/MonsterStates/Bosses.java +++ b/src/p/Actions/ActiveStates/MonsterStates/Bosses.java @@ -29,8 +29,9 @@ import rr.line_t; public interface Bosses extends ActionTrait { + void A_Fall(mobj_t mo); - + /** * A_BossDeath * Possibly trigger special effects @@ -53,7 +54,7 @@ default void A_BossDeath(mobj_t mo) { } if ((mo.type != mobjtype_t.MT_FATSO) - && (mo.type != mobjtype_t.MT_BABY)) { + && (mo.type != mobjtype_t.MT_BABY)) { return; } } else { @@ -136,8 +137,8 @@ default void A_BossDeath(mobj_t mo) { mo2 = (mobj_t) th; if (mo2 != mo - && mo2.type == mo.type - && mo2.health > 0) { + && mo2.type == mo.type + && mo2.health > 0) { // other boss not dead return; } @@ -182,7 +183,7 @@ default void A_BossDeath(mobj_t mo) { D.ExitLevel(); } - + default void A_KeenDie(mobj_t mo) { thinker_t th; mobj_t mo2; @@ -199,8 +200,8 @@ default void A_KeenDie(mobj_t mo) { mo2 = (mobj_t) th; if (mo2 != mo - && mo2.type == mo.type - && mo2.health > 0) { + && mo2.type == mo.type + && mo2.health > 0) { // other Keen not dead return; } diff --git a/src/p/Actions/ActiveStates/MonsterStates/Demonspawns.java b/src/p/Actions/ActiveStates/MonsterStates/Demonspawns.java index 45992032..a5cb2e7f 100644 --- a/src/p/Actions/ActiveStates/MonsterStates/Demonspawns.java +++ b/src/p/Actions/ActiveStates/MonsterStates/Demonspawns.java @@ -23,6 +23,7 @@ import p.mobj_t; public interface Demonspawns extends ActionTrait { + void A_FaceTarget(mobj_t actor); // diff --git a/src/p/Actions/ActiveStates/MonsterStates/HorrendousVisages.java b/src/p/Actions/ActiveStates/MonsterStates/HorrendousVisages.java index d067c592..995f5c3b 100644 --- a/src/p/Actions/ActiveStates/MonsterStates/HorrendousVisages.java +++ b/src/p/Actions/ActiveStates/MonsterStates/HorrendousVisages.java @@ -30,16 +30,18 @@ import utils.TraitFactory.ContextKey; public interface HorrendousVisages extends Sounds { + ContextKey KEY_BRAIN = ACTION_KEY_CHAIN.newKey(HorrendousVisages.class, Brain::new); final class Brain { + // Brain status mobj_t[] braintargets = new mobj_t[Limits.NUMBRAINTARGETS]; int numbraintargets; int braintargeton; int easy = 0; } - + default void A_BrainAwake(mobj_t mo) { final Brain brain = contextRequire(KEY_BRAIN); thinker_t thinker; diff --git a/src/p/Actions/ActiveStates/MonsterStates/Mancubi.java b/src/p/Actions/ActiveStates/MonsterStates/Mancubi.java index 843b4063..50eea286 100644 --- a/src/p/Actions/ActiveStates/MonsterStates/Mancubi.java +++ b/src/p/Actions/ActiveStates/MonsterStates/Mancubi.java @@ -27,8 +27,9 @@ import p.mobj_t; public interface Mancubi extends ActionTrait { + static final long FATSPREAD = Tables.ANG90 / 8; - + void A_FaceTarget(mobj_t actor); // diff --git a/src/p/Actions/ActiveStates/MonsterStates/PainsSouls.java b/src/p/Actions/ActiveStates/MonsterStates/PainsSouls.java index f15876af..436fb46d 100644 --- a/src/p/Actions/ActiveStates/MonsterStates/PainsSouls.java +++ b/src/p/Actions/ActiveStates/MonsterStates/PainsSouls.java @@ -38,11 +38,13 @@ import static p.mobj_t.MF_SKULLFLY; public interface PainsSouls extends ActionTrait { + static final int SKULLSPEED = 20 * m.fixed_t.MAPFRACUNIT; - + void A_FaceTarget(mobj_t actor); + void A_Fall(mobj_t actor); - + /** * SkullAttack * Fly at the player like a missile. @@ -82,10 +84,12 @@ default void A_SkullAttack(mobj_t actor) { * */ default void A_PainShootSkull(mobj_t actor, Long angle) { - @fixed_t int x, y, z; + @fixed_t + int x, y, z; mobj_t newmobj; - @angle_t int an; + @angle_t + int an; int prestep; int count; thinker_t currentthinker; @@ -96,7 +100,7 @@ default void A_PainShootSkull(mobj_t actor, Long angle) { currentthinker = getThinkerCap().next; while (currentthinker != getThinkerCap()) { if ((currentthinker.thinkerFunction == ActiveStates.P_MobjThinker) - && ((mobj_t) currentthinker).type == mobjtype_t.MT_SKULL) { + && ((mobj_t) currentthinker).type == mobjtype_t.MT_SKULL) { count++; } currentthinker = currentthinker.next; @@ -112,8 +116,8 @@ default void A_PainShootSkull(mobj_t actor, Long angle) { an = Tables.toBAMIndex(angle); prestep - = 4 * FRACUNIT - + 3 * (actor.info.radius + mobjinfo[mobjtype_t.MT_SKULL.ordinal()].radius) / 2; + = 4 * FRACUNIT + + 3 * (actor.info.radius + mobjinfo[mobjtype_t.MT_SKULL.ordinal()].radius) / 2; x = actor.x + FixedMul(prestep, finecosine[an]); y = actor.y + FixedMul(prestep, finesine[an]); diff --git a/src/p/Actions/ActiveStates/MonsterStates/Skels.java b/src/p/Actions/ActiveStates/MonsterStates/Skels.java index c77c6b13..73127f24 100644 --- a/src/p/Actions/ActiveStates/MonsterStates/Skels.java +++ b/src/p/Actions/ActiveStates/MonsterStates/Skels.java @@ -33,8 +33,9 @@ import static utils.C2JUtils.eval; public interface Skels extends ActionTrait { + int TRACEANGLE = 0xC_00_00_00; - + // // A_SkelMissile // @@ -78,7 +79,7 @@ default void A_SkelFist(mobj_t actor) { getAttacks().DamageMobj(actor.target, actor, actor, damage); } } - + default void A_Tracer(mobj_t actor) { long exact; //angle_t int dist, slope; // fixed @@ -95,16 +96,16 @@ default void A_Tracer(mobj_t actor) { if (th.mobj_tics < 1) { th.mobj_tics = 1; } - + // adjust direction dest = actor.tracer; if (dest == null || dest.health <= 0) { return; } - + // change angle exact = sceneRenderer().PointToAngle2(actor.x, actor.y, dest.x, dest.y) & BITS32; - + // MAES: let's analyze the logic here... // So exact is the angle between the missile and its target. if (exact != actor.angle) { // missile is already headed there dead-on. diff --git a/src/p/Actions/ActiveStates/MonsterStates/Spiders.java b/src/p/Actions/ActiveStates/MonsterStates/Spiders.java index b5e03fd3..faae8438 100644 --- a/src/p/Actions/ActiveStates/MonsterStates/Spiders.java +++ b/src/p/Actions/ActiveStates/MonsterStates/Spiders.java @@ -22,8 +22,9 @@ import p.mobj_t; public interface Spiders extends ActionTrait { + void A_FaceTarget(mobj_t actor); - + default void A_SpidRefire(mobj_t actor) { // keep firing unless target got out of sight A_FaceTarget(actor); diff --git a/src/p/Actions/ActiveStates/MonsterStates/Viles.java b/src/p/Actions/ActiveStates/MonsterStates/Viles.java index 9e0548dc..dbb3814f 100644 --- a/src/p/Actions/ActiveStates/MonsterStates/Viles.java +++ b/src/p/Actions/ActiveStates/MonsterStates/Viles.java @@ -38,7 +38,9 @@ import p.mobj_t; public interface Viles extends ActionTrait { + void A_FaceTarget(mobj_t actor); + void A_Chase(mobj_t actor); // @@ -49,7 +51,7 @@ default void A_VileChase(mobj_t actor) { final AbstractLevelLoader ll = levelLoader(); final ActionsAttacks actionsAttacks = getAttacks(); final Attacks att = actionsAttacks.contextRequire(KEY_ATTACKS); - + int xl; int xh; int yl; @@ -110,7 +112,7 @@ default void A_VileChase(mobj_t actor) { default void A_VileStart(mobj_t actor) { StartSound(actor, sounds.sfxenum_t.sfx_vilatk); } - + // // A_Fire // Keep fire in front of player unless out of sight @@ -146,7 +148,7 @@ default void A_Fire(mobj_t actor) { actor.z = dest.z; SetThingPosition(actor); } - + // // A_VileTarget // Spawn the hellfire diff --git a/src/p/Actions/ActiveStates/MonsterStates/Zombies.java b/src/p/Actions/ActiveStates/MonsterStates/Zombies.java index 25ac356e..0dae0f24 100644 --- a/src/p/Actions/ActiveStates/MonsterStates/Zombies.java +++ b/src/p/Actions/ActiveStates/MonsterStates/Zombies.java @@ -23,6 +23,7 @@ import p.mobj_t; public interface Zombies extends ActionTrait { + void A_FaceTarget(mobj_t actor); // diff --git a/src/p/Actions/ActiveStates/Monsters.java b/src/p/Actions/ActiveStates/Monsters.java index cd865559..bee46241 100644 --- a/src/p/Actions/ActiveStates/Monsters.java +++ b/src/p/Actions/ActiveStates/Monsters.java @@ -32,15 +32,14 @@ * @author Good Sign */ public interface Monsters extends - Bosses, - Demonspawns, - HorrendousVisages, - Mancubi, - PainsSouls, - Skels, - Spiders, - Viles, - Zombies -{ - + Bosses, + Demonspawns, + HorrendousVisages, + Mancubi, + PainsSouls, + Skels, + Spiders, + Viles, + Zombies { + } diff --git a/src/p/Actions/ActiveStates/Sounds.java b/src/p/Actions/ActiveStates/Sounds.java index 6dbf4f50..af7d08f3 100644 --- a/src/p/Actions/ActiveStates/Sounds.java +++ b/src/p/Actions/ActiveStates/Sounds.java @@ -25,8 +25,11 @@ import p.pspdef_t; public interface Sounds extends ActionTrait { + void A_Chase(mobj_t mo); + void A_ReFire(player_t player, pspdef_t psp); + void A_SpawnFly(mobj_t mo); default void A_Scream(mobj_t actor) { @@ -54,13 +57,14 @@ default void A_Scream(mobj_t actor) { // Check for bosses. if (actor.type == mobjtype_t.MT_SPIDER - || actor.type == mobjtype_t.MT_CYBORG) { + || actor.type == mobjtype_t.MT_CYBORG) { // full volume StartSound(null, sound); } else { StartSound(actor, sound); } } + default void A_Hoof(mobj_t mo) { StartSound(mo, sounds.sfxenum_t.sfx_hoof); A_Chase(mo); @@ -89,7 +93,7 @@ default void A_CloseShotgun2(player_t player, pspdef_t psp) { default void A_BrainPain(mobj_t mo) { StartSound(null, sounds.sfxenum_t.sfx_bospn); } - + default void A_Metal(mobj_t mo) { StartSound(mo, sounds.sfxenum_t.sfx_metal); A_Chase(mo); @@ -99,13 +103,13 @@ default void A_BabyMetal(mobj_t mo) { StartSound(mo, sounds.sfxenum_t.sfx_bspwlk); A_Chase(mo); } - + // travelling cube sound default void A_SpawnSound(mobj_t mo) { StartSound(mo, sounds.sfxenum_t.sfx_boscub); A_SpawnFly(mo); } - + default void A_PlayerScream(mobj_t actor) { // Default death sound. sounds.sfxenum_t sound = sounds.sfxenum_t.sfx_pldeth; diff --git a/src/p/Actions/ActiveStates/Thinkers.java b/src/p/Actions/ActiveStates/Thinkers.java index f21a50d8..da9aafcc 100644 --- a/src/p/Actions/ActiveStates/Thinkers.java +++ b/src/p/Actions/ActiveStates/Thinkers.java @@ -36,6 +36,7 @@ import p.vldoor_t; public interface Thinkers extends ActionTrait { + // // T_FireFlicker // @@ -59,7 +60,7 @@ default void T_FireFlicker(thinker_t f) { flick.count = 4; } - + /** * T_LightFlash * Do flashing lights. @@ -110,7 +111,7 @@ default void T_Glow(thinker_t t) { g.direction = -1; } break; - + default: break; } @@ -127,11 +128,11 @@ default void T_MoveFloor(thinker_t f) { default void T_VerticalDoor(thinker_t v) { getThinkers().VerticalDoor((vldoor_t) v); } - + default void T_SlidingDoor(thinker_t door) { getThinkers().SlidingDoor((slidedoor_t) door); } - + default void T_PlatRaise(thinker_t p) { getThinkers().PlatRaise((plat_t) p); } diff --git a/src/p/Actions/ActiveStates/Weapons.java b/src/p/Actions/ActiveStates/Weapons.java index 544fab4f..ec7892d8 100644 --- a/src/p/Actions/ActiveStates/Weapons.java +++ b/src/p/Actions/ActiveStates/Weapons.java @@ -41,6 +41,7 @@ import static utils.C2JUtils.eval; public interface Weapons extends Sounds { + /** * A_WeaponReady * The player can fire the weapon @@ -54,13 +55,12 @@ default void A_WeaponReady(player_t player, pspdef_t psp) { // get out of attack state if (player.mo.mobj_state == states[statenum_t.S_PLAY_ATK1.ordinal()] - || player.mo.mobj_state == states[statenum_t.S_PLAY_ATK2.ordinal()]) { + || player.mo.mobj_state == states[statenum_t.S_PLAY_ATK2.ordinal()]) { player.mo.SetMobjState(statenum_t.S_PLAY); } if (player.readyweapon == weapontype_t.wp_chainsaw - && psp.state == states[statenum_t.S_SAW.ordinal()]) - { + && psp.state == states[statenum_t.S_SAW.ordinal()]) { StartSound(player.mo, sounds.sfxenum_t.sfx_sawidl); } @@ -78,9 +78,8 @@ default void A_WeaponReady(player_t player, pspdef_t psp) { // the missile launcher and bfg do not auto fire if (eval(player.cmd.buttons & BT_ATTACK)) { if (!player.attackdown - || (player.readyweapon != weapontype_t.wp_missile - && player.readyweapon != weapontype_t.wp_bfg)) - { + || (player.readyweapon != weapontype_t.wp_missile + && player.readyweapon != weapontype_t.wp_bfg)) { player.attackdown = true; getEnemies().FireWeapon(player); return; @@ -131,8 +130,8 @@ default void A_ReFire(player_t player, pspdef_t psp) { // check for fire // (if a weaponchange is pending, let it go through instead) if (eval(player.cmd.buttons & BT_ATTACK) - && player.pendingweapon == weapontype_t.wp_nochange - && eval(player.health[0])) { + && player.pendingweapon == weapontype_t.wp_nochange + && eval(player.health[0])) { player.refire++; getEnemies().FireWeapon(player); } else { @@ -148,7 +147,7 @@ default void A_GunFlash(player_t player, pspdef_t psp) { player.mo.SetMobjState(statenum_t.S_PLAY_ATK2); player.SetPsprite(ps_flash, weaponinfo[player.readyweapon.ordinal()].flashstate); } - + // // ? // diff --git a/src/p/ActiveStates.java b/src/p/ActiveStates.java index a98edb69..9cf5af20 100644 --- a/src/p/ActiveStates.java +++ b/src/p/ActiveStates.java @@ -15,7 +15,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package p; import doom.SourceCode.D_Think; @@ -85,7 +84,7 @@ * Or otherwise be sector specials, flickering lights etc. * Those are atypical and need special handling. */ -public enum ActiveStates implements ThinkerStates{ +public enum ActiveStates implements ThinkerStates { NOP(ActiveStates::nop, ThinkerConsumer.class), A_Light0(ActionFunctions::A_Light0, PlayerSpriteConsumer.class), A_WeaponReady(ActionFunctions::A_WeaponReady, PlayerSpriteConsumer.class), @@ -171,9 +170,9 @@ public enum ActiveStates implements ThinkerStates{ T_VerticalDoor(ActionFunctions::T_VerticalDoor, ThinkerConsumer.class), T_PlatRaise(ActionFunctions::T_PlatRaise, ThinkerConsumer.class), T_SlidingDoor(ActionFunctions::T_SlidingDoor, ThinkerConsumer.class); - + private final static Logger LOGGER = Loggers.getLogger(ActiveStates.class.getName()); - + private final ParamClass actionFunction; private final Class> paramType; @@ -181,40 +180,45 @@ private > ActiveStates(final T actionFunction, final Cla this.actionFunction = actionFunction; this.paramType = paramType; } - - private static void nop(Object... o) {} + + private static void nop(Object... o) { + } @actionf_p1 @D_Think.C(actionf_t.acp1) public interface MobjConsumer extends ParamClass { - void accept(ActionFunctions a, mobj_t m); + + void accept(ActionFunctions a, mobj_t m); } - + @actionf_v @D_Think.C(actionf_t.acv) public interface ThinkerConsumer extends ParamClass { - void accept(ActionFunctions a, thinker_t t); + + void accept(ActionFunctions a, thinker_t t); } - + @actionf_p2 @D_Think.C(actionf_t.acp2) public interface PlayerSpriteConsumer extends ParamClass { - void accept(ActionFunctions a, player_t p, pspdef_t s); + + void accept(ActionFunctions a, player_t p, pspdef_t s); + } + + private interface ParamClass> { } - private interface ParamClass> {} - public boolean isParamType(final Class paramType) { return this.paramType == paramType; } - + @SuppressWarnings("unchecked") public > T fun(final Class paramType) { if (this.paramType != paramType) { LOGGER.log(Level.WARNING, "Wrong paramType for state: {0}", this); return null; } - + // don't believe, it's checked return (T) this.actionFunction; } diff --git a/src/p/BoomLevelLoader.java b/src/p/BoomLevelLoader.java index a8b83343..b353d3b0 100644 --- a/src/p/BoomLevelLoader.java +++ b/src/p/BoomLevelLoader.java @@ -1,6 +1,6 @@ package p; -import static boom.Compatibility.*; +import static boom.Compatibility.prboom_2_compatibility; import boom.DeepBSPNodesV4; import static boom.E6Y.NO_INDEX; import boom.mapglvertex_t; @@ -10,7 +10,9 @@ import boom.mapseg_znod_t; import boom.mapsubsector_v4_t; import boom.mapsubsector_znod_t; -import static data.Defines.*; +import static data.Defines.NF_SUBSECTOR; +import static data.Defines.NF_SUBSECTOR_CLASSIC; +import static data.Defines.PU_LEVEL; import data.Limits; import data.maplinedef_t; import data.mapnode_t; @@ -35,11 +37,17 @@ import java.nio.ByteOrder; import java.util.Arrays; import java.util.function.IntFunction; +import java.util.logging.Level; +import java.util.logging.Logger; import m.BBox; -import static m.BBox.*; +import static m.BBox.BOXBOTTOM; +import static m.BBox.BOXLEFT; +import static m.BBox.BOXRIGHT; +import static m.BBox.BOXTOP; import m.fixed_t; import static m.fixed_t.FRACBITS; import static m.fixed_t.FRACUNIT; +import mochadoom.Loggers; import rr.RendererState; import rr.line_t; import static rr.line_t.ML_TWOSIDED; @@ -86,10 +94,11 @@ * * ----------------------------------------------------------------------------- */ - public class BoomLevelLoader extends AbstractLevelLoader { - public BoomLevelLoader(DoomMain DM) { + private static final Logger LOGGER = Loggers.getLogger(BoomLevelLoader.class.getName()); + + public BoomLevelLoader(DoomMain DM) { super(DM); // TODO Auto-generated constructor stub } @@ -100,7 +109,7 @@ public BoomLevelLoader(DoomMain DM) { // ////////////////////////////////////////////////////////////////////////////////////////// // figgi 08/21/00 -- finalants and globals for glBsp support public static final int gNd2 = 0x32644E67; // figgi -- suppport for new - // GL_VERT format v2.0 + // GL_VERT format v2.0 public static final int gNd3 = 0x33644E67; @@ -122,6 +131,7 @@ public BoomLevelLoader(DoomMain DM) { // figgi 08/21/00 -- glSegs class glseg_t { + char v1; // start vertex (16 bit) char v2; // end vertex (16 bit) @@ -134,7 +144,7 @@ class glseg_t { } public static final int ML_GL_LABEL = 0; // A separator name, GL_ExMx or - // GL_MAPxx + // GL_MAPxx public static final int ML_GL_VERTS = 1; // Extra Vertices @@ -145,7 +155,6 @@ class glseg_t { public static final int ML_GL_NODES = 4; // GL BSP nodes // ////////////////////////////////////////////////////////////////////////////////////////// - // // REJECT // For fast sight rejection. @@ -154,7 +163,6 @@ class glseg_t { // Without the special effect, this could // be used as a PVS lookup as well. // - private int rejectlump = -1;// cph - store reject lump num if cached private int current_episode = -1; @@ -174,7 +182,6 @@ class glseg_t { * @param numstuff * elements to realloc */ - private T[] malloc_IfSameLevel(T[] p, int numstuff, ArraySupplier supplier, IntFunction generator) { if (!samelevel || (p == null)) { return malloc(supplier, generator, numstuff); @@ -198,20 +205,20 @@ private T[] calloc_IfSameLevel(T[] p, int numstuff, Array // // P_CheckForZDoomNodes // - private boolean P_CheckForZDoomNodes(int lumpnum, int gl_lumpnum) { byte[] data; int check; - + data = DOOM.wadLoader.CacheLumpNumAsRawBytes(lumpnum + ML_NODES, 0); check = ByteBuffer.wrap(data).getInt(); - - if (check == ZNOD) + + if (check == ZNOD) { DOOM.doomSystem.Error("P_CheckForZDoomNodes: ZDoom nodes not supported yet"); + } data = DOOM.wadLoader.CacheLumpNumAsRawBytes(lumpnum + ML_SSECTORS, 0); check = ByteBuffer.wrap(data).getInt(); - + if (check == ZGLN) { DOOM.doomSystem.Error("P_CheckForZDoomNodes: ZDoom GL nodes not supported yet"); } @@ -227,7 +234,6 @@ private boolean P_CheckForZDoomNodes(int lumpnum, int gl_lumpnum) { // P_CheckForDeePBSPv4Nodes // http://www.sbsoftware.com/files/DeePBSPV4specs.txt // - private boolean P_CheckForDeePBSPv4Nodes(int lumpnum, int gl_lumpnum) { byte[] data; boolean result = false; @@ -236,7 +242,7 @@ private boolean P_CheckForDeePBSPv4Nodes(int lumpnum, int gl_lumpnum) { byte[] compare = Arrays.copyOfRange(data, 0, 7); if (Arrays.equals(compare, DeepBSPNodesV4.DeepBSPHeader)) { - System.out.println("P_CheckForDeePBSPv4Nodes: DeePBSP v4 Extended nodes are detected"); + LOGGER.log(Level.INFO, "P_CheckForDeePBSPv4Nodes: DeePBSP v4 Extended nodes are detected"); result = true; } @@ -249,7 +255,6 @@ private boolean P_CheckForDeePBSPv4Nodes(int lumpnum, int gl_lumpnum) { // P_CheckForZDoomUncompressedNodes // http://zdoom.org/wiki/ZDBSP#Compressed_Nodes // - private static final int XNOD = 0x584e4f44; private boolean P_CheckForZDoomUncompressedNodes(int lumpnum, int gl_lumpnum) { @@ -258,10 +263,10 @@ private boolean P_CheckForZDoomUncompressedNodes(int lumpnum, int gl_lumpnum) { boolean result = false; data = DOOM.wadLoader.CacheLumpNumAsRawBytes(lumpnum + ML_NODES, 0); - wrapper=ByteBuffer.wrap(data).getInt(); + wrapper = ByteBuffer.wrap(data).getInt(); - if (wrapper==XNOD) { - System.out.println("P_CheckForZDoomUncompressedNodes: ZDoom uncompressed normal nodes are detected"); + if (wrapper == XNOD) { + LOGGER.log(Level.INFO, "P_CheckForZDoomUncompressedNodes: ZDoom uncompressed normal nodes are detected"); result = true; } @@ -273,14 +278,12 @@ private boolean P_CheckForZDoomUncompressedNodes(int lumpnum, int gl_lumpnum) { // // P_GetNodesVersion // - public void P_GetNodesVersion(int lumpnum, int gl_lumpnum) { int ver = -1; nodesVersion = 0; if ((gl_lumpnum > lumpnum) && (forceOldBsp == false) - &&(DoomStatus.compatibility_level>=prboom_2_compatibility) - ) { + && (DoomStatus.compatibility_level >= prboom_2_compatibility)) { byte[] data = DOOM.wadLoader.CacheLumpNumAsRawBytes(gl_lumpnum + ML_GL_VERTS, 0); int wrapper = ByteBuffer.wrap(data).getInt(); @@ -291,7 +294,7 @@ public void P_GetNodesVersion(int lumpnum, int gl_lumpnum) { ver = 3; } else { nodesVersion = gNd2; - System.out.println("P_GetNodesVersion: found version 2 nodes"); + LOGGER.log(Level.INFO, "P_GetNodesVersion: found version 2 nodes"); } } if (wrapper == gNd4) { @@ -302,12 +305,12 @@ public void P_GetNodesVersion(int lumpnum, int gl_lumpnum) { } // e6y: unknown gl nodes will be ignored if (nodesVersion == 0 && ver != -1) { - System.out.printf("P_GetNodesVersion: found version %d nodes\n", ver); - System.out.printf("P_GetNodesVersion: version %d nodes not supported\n", ver); + LOGGER.log(Level.INFO, String.format("P_GetNodesVersion: found version %d nodes", ver)); + LOGGER.log(Level.INFO, String.format("P_GetNodesVersion: version %d nodes not supported", ver)); } } else { nodesVersion = 0; - System.out.println("P_GetNodesVersion: using normal BSP nodes"); + LOGGER.log(Level.INFO, "P_GetNodesVersion: using normal BSP nodes"); if (P_CheckForZDoomNodes(lumpnum, gl_lumpnum)) { DOOM.doomSystem.Error("P_GetNodesVersion: ZDoom nodes not supported yet"); } @@ -352,10 +355,8 @@ private void P_LoadVertexes(int lump) { * @throws IOException * * *******************************************/ - // figgi -- FIXME: Automap showes wrong zoom boundaries when starting game // when P_LoadVertexes2 is used with classic BSP nodes. - private void P_LoadVertexes2(int lump, int gllump) throws IOException { final ByteBuffer gldata; mapvertex_t[] ml; @@ -432,10 +433,10 @@ private void P_LoadVertexes2(int lump, int gllump) throws IOException { * created : 08/13/00 * modified : 09/18/00, adapted for PrBoom * author : * figgi * what : basic functions needed for * computing gl nodes * *******************************************/ - public int checkGLVertex(int num) { - if ((num & 0x8000) != 0) + if ((num & 0x8000) != 0) { num = (num & 0x7FFF) + firstglvertex; + } return num; } @@ -463,7 +464,6 @@ public static int GetOffset(vertex_t v1, vertex_t v2) { // P_LoadSegs // // killough 5/3/98: reformatted, cleaned up - private void P_LoadSegs(int lump) { final mapseg_t[] data; // cph - final @@ -471,13 +471,14 @@ private void P_LoadSegs(int lump) { segs = calloc_IfSameLevel(segs, numsegs, seg_t::new, seg_t[]::new); data = DOOM.wadLoader.CacheLumpNumIntoArray(lump, numsegs, mapseg_t::new, mapseg_t[]::new); // cph - - // wad - // lump - // handling - // updated + // wad + // lump + // handling + // updated - if ((data == null) || (numsegs == 0)) + if ((data == null) || (numsegs == 0)) { DOOM.doomSystem.Error("P_LoadSegs: no segs in level"); + } for (int i = 0; i < numsegs; i++) { seg_t li = segs[i]; @@ -498,20 +499,18 @@ private void P_LoadSegs(int lump) { // see below for more detailed information // li.v1 = &vertexes[v1]; // li.v2 = &vertexes[v2]; - li.miniseg = false; // figgi -- there are no minisegs in classic BSP - // nodes + // nodes // e6y: moved down, see below // li.length = GetDistance(li.v2.x - li.v1.x, li.v2.y - li.v1.y); - li.angle = ml.angle << 16; li.offset = ml.offset << 16; linedef = ml.linedef; // e6y: check for wrong indexes if (linedef >= numlines) { - DOOM.doomSystem.Error( "P_LoadSegs: seg %d references a non-existent linedef %d", i, linedef); + DOOM.doomSystem.Error("P_LoadSegs: seg %d references a non-existent linedef %d", i, linedef); } ldef = lines[linedef]; @@ -520,15 +519,15 @@ private void P_LoadSegs(int lump) { // e6y: fix wrong side index if (side != 0 && side != 1) { - System.err.printf("P_LoadSegs: seg %d contains wrong side index %d. Replaced with 1.\n", i, side); + LOGGER.log(Level.WARNING, String.format("P_LoadSegs: seg %d contains wrong side index %d. Replaced with 1.", i, side)); side = 1; } // e6y: check for wrong indexes if (ldef.sidenum[side] >= (char) numsides) { DOOM.doomSystem.Error( - "P_LoadSegs: linedef %d for seg %d references a non-existent sidedef %d", - linedef, i, ldef.sidenum[side] + "P_LoadSegs: linedef %d for seg %d references a non-existent sidedef %d", + linedef, i, ldef.sidenum[side] ); } @@ -539,11 +538,11 @@ private void P_LoadSegs(int lump) { * linedef, so must check for NO_INDEX in case we are incorrectly * referencing the back of a 1S line */ - if (ldef.sidenum[side] != NO_INDEX) + if (ldef.sidenum[side] != NO_INDEX) { li.frontsector = sides[ldef.sidenum[side]].sector; - else { + } else { li.frontsector = null; - System.err.printf("P_LoadSegs: front of seg %i has no sidedef\n", i); + LOGGER.log(Level.INFO, String.format("P_LoadSegs: front of seg %d has no sidedef", i)); } if (flags(ldef.flags, ML_TWOSIDED) && ldef.sidenum[side ^ 1] != NO_INDEX) { @@ -561,16 +560,16 @@ private void P_LoadSegs(int lump) { if (DOOM.demorecording) { DOOM.doomSystem.Error( - str + "Demo recording on levels with invalid nodes is not allowed", - i, (v1 >= numvertexes ? v1 : v2) + str + "Demo recording on levels with invalid nodes is not allowed", + i, (v1 >= numvertexes ? v1 : v2) ); } if (v1 >= numvertexes) { - System.err.printf(str, i, v1); + LOGGER.log(Level.WARNING, String.format(str, i, v1)); } if (v2 >= numvertexes) { - System.err.printf(str, i, v2); + LOGGER.log(Level.WARNING, String.format(str, i, v2)); } if (li.sidedef == sides[li.linedef.sidenum[0]]) { @@ -607,8 +606,9 @@ private void P_LoadSegs_V4(int lump) { segs = calloc_IfSameLevel(segs, numsegs, seg_t::new, seg_t[]::new); data = DOOM.wadLoader.CacheLumpNumIntoArray(lump, numsegs, mapseg_v4_t::new, mapseg_v4_t[]::new); - if ((data == null) || (numsegs == 0)) + if ((data == null) || (numsegs == 0)) { DOOM.doomSystem.Error("P_LoadSegs_V4: no segs in level"); + } for (i = 0; i < numsegs; i++) { seg_t li = segs[i]; @@ -624,7 +624,7 @@ private void P_LoadSegs_V4(int lump) { v2 = ml.v2; li.miniseg = false; // figgi -- there are no minisegs in classic BSP - // nodes + // nodes li.angle = ml.angle << 16; li.offset = ml.offset << 16; @@ -633,8 +633,8 @@ private void P_LoadSegs_V4(int lump) { // e6y: check for wrong indexes if (unsigned(linedef) >= unsigned(numlines)) { DOOM.doomSystem.Error( - "P_LoadSegs_V4: seg %d references a non-existent linedef %d", - i, unsigned(linedef)); + "P_LoadSegs_V4: seg %d references a non-existent linedef %d", + i, unsigned(linedef)); } ldef = lines[linedef]; @@ -643,15 +643,15 @@ private void P_LoadSegs_V4(int lump) { // e6y: fix wrong side index if (side != 0 && side != 1) { - System.err.printf("P_LoadSegs_V4: seg %d contains wrong side index %d. Replaced with 1.\n", i, side); + LOGGER.log(Level.WARNING, String.format("P_LoadSegs_V4: seg %d contains wrong side index %d. Replaced with 1.", i, side)); side = 1; } // e6y: check for wrong indexes if (unsigned(ldef.sidenum[side]) >= unsigned(numsides)) { DOOM.doomSystem.Error( - "P_LoadSegs_V4: linedef %d for seg %d references a non-existent sidedef %d", - linedef, i, unsigned(ldef.sidenum[side]) + "P_LoadSegs_V4: linedef %d for seg %d references a non-existent sidedef %d", + linedef, i, unsigned(ldef.sidenum[side]) ); } @@ -666,11 +666,11 @@ linedef, i, unsigned(ldef.sidenum[side]) li.frontsector = sides[ldef.sidenum[side]].sector; } else { li.frontsector = null; - System.err.printf("P_LoadSegs_V4: front of seg %i has no sidedef\n", i); + LOGGER.log(Level.WARNING, String.format("P_LoadSegs_V4: front of seg %d has no sidedef", i)); } if (flags(ldef.flags, ML_TWOSIDED) - && ldef.sidenum[side ^ 1] != NO_INDEX) { + && ldef.sidenum[side ^ 1] != NO_INDEX) { li.backsector = sides[ldef.sidenum[side ^ 1]].sector; } else { li.backsector = null; @@ -685,16 +685,16 @@ linedef, i, unsigned(ldef.sidenum[side]) if (DOOM.demorecording) { DOOM.doomSystem.Error( - (str + "Demo recording on levels with invalid nodes is not allowed"), - i, (v1 >= numvertexes ? v1 : v2) + (str + "Demo recording on levels with invalid nodes is not allowed"), + i, (v1 >= numvertexes ? v1 : v2) ); } if (v1 >= numvertexes) { - System.err.printf(str, i, v1); + LOGGER.log(Level.WARNING, String.format(str, i, v1)); } if (v2 >= numvertexes) { - System.err.printf(str, i, v2); + LOGGER.log(Level.WARNING, String.format(str, i, v2)); } if (li.sidedef == sides[li.linedef.sidenum[0]]) { @@ -749,12 +749,10 @@ linedef, i, unsigned(ldef.sidenum[side]) * segs[i].linedef = NULL; segs[i].sidedef = NULL; segs[i].frontsector = * NULL; segs[i].backsector = NULL; } ml++; } W.UnlockLumpNum(lump); } */ - // // P_LoadSubsectors // // killough 5/3/98: reformatted, cleaned up - private void P_LoadSubsectors(int lump) { /* * cph 2006/07/29 - make data a final mapsubsector_t *, so the loop @@ -790,8 +788,9 @@ private void P_LoadSubsectors_V4(int lump) { subsectors = calloc_IfSameLevel(subsectors, numsubsectors, subsector_t::new, subsector_t[]::new); data = DOOM.wadLoader.CacheLumpNumIntoArray(lump, numsubsectors, mapsubsector_v4_t::new, mapsubsector_v4_t[]::new); - if ((data == null) || (numsubsectors == 0)) + if ((data == null) || (numsubsectors == 0)) { DOOM.doomSystem.Error("P_LoadSubsectors_V4: no subsectors in level"); + } for (int i = 0; i < numsubsectors; i++) { subsectors[i].numlines = data[i].numsegs; @@ -805,18 +804,17 @@ private void P_LoadSubsectors_V4(int lump) { // P_LoadSectors // // killough 5/3/98: reformatted, cleaned up - private void P_LoadSectors(int lump) { final mapsector_t[] data; // cph - final* numsectors = DOOM.wadLoader.LumpLength(lump) / mapsector_t.sizeOf(); sectors = calloc_IfSameLevel(sectors, numsectors, sector_t::new, sector_t[]::new); data = DOOM.wadLoader.CacheLumpNumIntoArray(lump, numsectors, mapsector_t::new, mapsector_t[]::new); // cph - // - - // wad - // lump - // handling - // updated + // - + // wad + // lump + // handling + // updated for (int i = 0; i < numsectors; i++) { sector_t ss = sectors[i]; @@ -837,10 +835,8 @@ private void P_LoadSectors(int lump) { ss.RND = this.DOOM.random; // ss.touching_thinglist = null; // phares 3/14/98 - // ss.nextsec = -1; //jff 2/26/98 add fields to support locking out // ss.prevsec = -1; // stair retriggering until build completes - // killough 3/7/98: // ss.floor_xoffs = 0; // ss.floor_yoffs = 0; // floor and ceiling flats offsets @@ -849,13 +845,10 @@ private void P_LoadSectors(int lump) { // ss.heightsec = -1; // sector used to get floor and ceiling height // ss.floorlightsec = -1; // sector used to get floor lighting // killough 3/7/98: end changes - // killough 4/11/98 sector used to get ceiling lighting: // ss.ceilinglightsec = -1; - // killough 4/4/98: colormaps: // ss.bottommap = ss.midmap = ss.topmap = 0; - // killough 10/98: sky textures coming from sidedefs: // ss.sky = 0; } @@ -867,26 +860,25 @@ private void P_LoadSectors(int lump) { // P_LoadNodes // // killough 5/3/98: reformatted, cleaned up - private void P_LoadNodes(int lump) { final mapnode_t[] data; // cph - final* numnodes = DOOM.wadLoader.LumpLength(lump) / mapnode_t.sizeOf(); nodes = malloc_IfSameLevel(nodes, numnodes, node_t::new, node_t[]::new); data = DOOM.wadLoader.CacheLumpNumIntoArray(lump, numnodes, mapnode_t::new, mapnode_t[]::new); // cph - // - - // wad - // lump - // handling - // updated + // - + // wad + // lump + // handling + // updated if ((data == null) || (numnodes == 0)) { // allow trivial maps - if (numsubsectors == 1) - System.out - .print("P_LoadNodes: trivial map (no nodes, one subsector)\n"); - else + if (numsubsectors == 1) { + LOGGER.log(Level.INFO, "P_LoadNodes: trivial map (no nodes, one subsector)"); + } else { DOOM.doomSystem.Error("P_LoadNodes: no nodes in level"); + } } for (int i = 0; i < numnodes; i++) { @@ -911,7 +903,7 @@ private void P_LoadNodes(int lump) { // haleyjd 11/06/10: check for invalid subsector reference if (no.children[j] >= numsubsectors) { - System.err.printf("P_LoadNodes: BSP tree references invalid subsector %d.\n", no.children[j]); + LOGGER.log(Level.WARNING, String.format("P_LoadNodes: BSP tree references invalid subsector %d.", no.children[j])); no.children[j] = 0; } @@ -933,16 +925,16 @@ private void P_LoadNodes_V4(int lump) { numnodes = (DOOM.wadLoader.LumpLength(lump) - 8) / mapnode_v4_t.sizeOf(); nodes = malloc_IfSameLevel(nodes, numnodes, node_t::new, node_t[]::new); data = DOOM.wadLoader.CacheLumpNum(lump, 0, DeepBSPNodesV4.class); // cph - // - - // wad - // lump - // handling - // updated + // - + // wad + // lump + // handling + // updated if ((data == null) || (numnodes == 0)) { // allow trivial maps if (numsubsectors == 1) { - System.out.print("P_LoadNodes_V4: trivial map (no nodes, one subsector)\n"); + LOGGER.log(Level.INFO, "P_LoadNodes_V4: trivial map (no nodes, one subsector)\n"); } else { DOOM.doomSystem.Error("P_LoadNodes_V4: no nodes in level"); } @@ -969,9 +961,9 @@ private void P_LoadNodes_V4(int lump) { DOOM.wadLoader.UnlockLumpNum(lump); // cph - release the data } - private void P_LoadZSegs(ByteBuffer data) throws IOException { + private void P_LoadZSegs(ByteBuffer data) throws IOException { final mapseg_znod_t nodes[] = malloc(mapseg_znod_t::new, mapseg_znod_t[]::new, numsegs); - CacheableDoomObjectContainer.unpack(data,nodes); + CacheableDoomObjectContainer.unpack(data, nodes); for (int i = 0; i < numsegs; i++) { line_t ldef; @@ -992,8 +984,8 @@ private void P_LoadZSegs(ByteBuffer data) throws IOException { // e6y: check for wrong indexes if (unsigned(linedef) >= unsigned(numlines)) { DOOM.doomSystem.Error( - "P_LoadZSegs: seg %d references a non-existent linedef %d", - i, unsigned(linedef) + "P_LoadZSegs: seg %d references a non-existent linedef %d", + i, unsigned(linedef) ); } @@ -1003,15 +995,15 @@ i, unsigned(linedef) // e6y: fix wrong side index if (side != 0 && side != 1) { - System.err.printf("P_LoadZSegs: seg %d contains wrong side index %d. Replaced with 1.\n", i, side); + LOGGER.log(Level.WARNING, String.format("P_LoadZSegs: seg %d contains wrong side index %d. Replaced with 1.", i, (int) side)); side = 1; } // e6y: check for wrong indexes if (unsigned(ldef.sidenum[side]) >= unsigned(numsides)) { DOOM.doomSystem.Error( - "P_LoadZSegs: linedef %d for seg %d references a non-existent sidedef %d", - linedef, i, unsigned(ldef.sidenum[side]) + "P_LoadZSegs: linedef %d for seg %d references a non-existent sidedef %d", + linedef, i, unsigned(ldef.sidenum[side]) ); } @@ -1026,7 +1018,7 @@ linedef, i, unsigned(ldef.sidenum[side]) li.frontsector = sides[ldef.sidenum[side]].sector; } else { li.frontsector = null; - System.err.printf("P_LoadZSegs: front of seg %i has no sidedef\n", i); + LOGGER.log(Level.WARNING, String.format("P_LoadZSegs: front of seg %d has no sidedef", i)); } if (flags(ldef.flags, ML_TWOSIDED) && (ldef.sidenum[side ^ 1] != NO_INDEX)) { @@ -1055,7 +1047,7 @@ private int CheckZNodesOverflow(int size, int count) { return size; } - + private void P_LoadZNodes(int lump, int glnodes) throws IOException { ByteBuffer data; int len; @@ -1197,7 +1189,7 @@ private void P_LoadZNodes(int lump, int glnodes) throws IOException { DOOM.wadLoader.UnlockLumpNum(lump); // cph - release the data } - + private boolean no_overlapped_sprites; private int GETXY(mobj_t mobj) { @@ -1218,7 +1210,6 @@ private int dicmp_sprite_by_pos(final Object a, final Object b) { * don't write into the lump cache, especially non-idepotent changes like * byte order reversals. Take a copy to edit. */ - @SourceCode.Suspicious(CauseOfDesyncProbability.LOW) @P_Setup.C(P_LoadThings) private void P_LoadThings(int lump) { @@ -1243,7 +1234,6 @@ private void P_LoadThings(int lump) { * LittleShort(mt.angle); mt.type = LittleShort(mt.type); mt.options * = LittleShort(mt.options); */ - if (!P_IsDoomnumAllowed(mt.type)) { continue; } @@ -1274,23 +1264,23 @@ private void P_LoadThings(int lump) { * src/p_setup.c Return TRUE if the thing in question is expected to be * available in the gamemode used. */ - boolean P_IsDoomnumAllowed(int doomnum) { // Do not spawn cool, new monsters if !commercial - if (!DOOM.isCommercial()) + if (!DOOM.isCommercial()) { switch (doomnum) { - case 64: // Archvile - case 65: // Former Human Commando - case 66: // Revenant - case 67: // Mancubus - case 68: // Arachnotron - case 69: // Hell Knight - case 71: // Pain Elemental - case 84: // Wolf SS - case 88: // Boss Brain - case 89: // Boss Shooter - return false; + case 64: // Archvile + case 65: // Former Human Commando + case 66: // Revenant + case 67: // Mancubus + case 68: // Arachnotron + case 69: // Hell Knight + case 71: // Pain Elemental + case 84: // Wolf SS + case 88: // Boss Brain + case 89: // Boss Shooter + return false; } + } return true; } @@ -1306,18 +1296,17 @@ boolean P_IsDoomnumAllowed(int doomnum) { // killough 4/4/98: split into two functions, to allow sidedef overloading // // killough 5/3/98: reformatted, cleaned up - private void P_LoadLineDefs(int lump) { final maplinedef_t[] data; // cph - final* numlines = DOOM.wadLoader.LumpLength(lump) / maplinedef_t.sizeOf(); lines = calloc_IfSameLevel(lines, numlines, line_t::new, line_t[]::new); data = DOOM.wadLoader.CacheLumpNumIntoArray(lump, numlines, maplinedef_t::new, maplinedef_t[]::new); // cph - // - - // wad - // lump - // handling - // updated + // - + // wad + // lump + // handling + // updated for (int i = 0; i < numlines; i++) { final maplinedef_t mld = data[i]; @@ -1345,10 +1334,10 @@ private void P_LoadLineDefs(int lump) { ld.tranlump = -1; // killough 4/11/98: no translucency by default ld.slopetype = (ld.dx == 0) - ? slopetype_t.ST_VERTICAL - : (ld.dy == 0) - ? slopetype_t.ST_HORIZONTAL - : fixed_t.FixedDiv(ld.dy, ld.dx) > 0 + ? slopetype_t.ST_VERTICAL + : (ld.dy == 0) + ? slopetype_t.ST_HORIZONTAL + : fixed_t.FixedDiv(ld.dy, ld.dx) > 0 ? slopetype_t.ST_POSITIVE : slopetype_t.ST_NEGATIVE; @@ -1372,9 +1361,9 @@ private void P_LoadLineDefs(int lump) { // no need for comp_sound test, these are only used when comp_sound // = 0 ld.soundorg = new degenmobj_t( - ld.bbox[BBox.BOXLEFT] / 2 - + ld.bbox[BBox.BOXRIGHT] / 2, ld.bbox[BBox.BOXTOP] / 2 - + ld.bbox[BBox.BOXBOTTOM] / 2, 0 + ld.bbox[BBox.BOXLEFT] / 2 + + ld.bbox[BBox.BOXRIGHT] / 2, ld.bbox[BBox.BOXTOP] / 2 + + ld.bbox[BBox.BOXBOTTOM] / 2, 0 ); // TODO @@ -1391,9 +1380,9 @@ private void P_LoadLineDefs(int lump) { for (int j = 0; j < 2; j++) { if (ld.sidenum[j] != NO_INDEX && ld.sidenum[j] >= numsides) { ld.sidenum[j] = NO_INDEX; - System.err.printf( - "P_LoadLineDefs: linedef %d has out-of-range sidedef number\n", - numlines - i - 1 + LOGGER.log(Level.WARNING, String.format( + "P_LoadLineDefs: linedef %d has out-of-range sidedef number", + numlines - i - 1) ); } } @@ -1403,7 +1392,7 @@ private void P_LoadLineDefs(int lump) { ld.sidenum[0] = 0; // Substitute dummy sidedef for missing // right side // cph - print a warning about the bug - System.err.printf("P_LoadLineDefs: linedef %d missing first sidedef\n", numlines - i - 1); + LOGGER.log(Level.WARNING, String.format("P_LoadLineDefs: linedef %d missing first sidedef\n", numlines - i - 1)); } if ((ld.sidenum[1] == NO_INDEX) && flags(ld.flags, ML_TWOSIDED)) { @@ -1426,9 +1415,9 @@ private void P_LoadLineDefs(int lump) { // TODO ehhh? // ld.r_flags = RF_IGNORE_COMPAT; // cph - print a warning about the bug - System.err.printf( - "P_LoadLineDefs: linedef %d has two-sided flag set, but no second sidedef\n", - numlines - i - 1 + LOGGER.log(Level.WARNING, String.format( + "P_LoadLineDefs: linedef %d has two-sided flag set, but no second sidedef\n", + numlines - i - 1) ); } } @@ -1445,18 +1434,17 @@ private void P_LoadLineDefs(int lump) { // killough 4/4/98: delay using sidedefs until they are loaded // killough 5/3/98: reformatted, cleaned up - private void P_LoadLineDefs2(int lump) { line_t ld; for (int i = 0; i < numlines; i++) { ld = lines[i]; ld.frontsector = sides[ld.sidenum[0]].sector; // e6y: Can't be - // NO_INDEX here - ld.backsector = - ld.sidenum[1] != NO_INDEX ? sides[ld.sidenum[1]].sector : null; + // NO_INDEX here + ld.backsector + = ld.sidenum[1] != NO_INDEX ? sides[ld.sidenum[1]].sector : null; switch (ld.special) { // killough 4/11/98: handle special types - case 260: // killough 4/11/98: translucent 2s textures + case 260: // killough 4/11/98: translucent 2s textures // TODO: transparentpresent = true;//e6y // int lmp = sides[ld.getSpecialSidenum()].special; // // translucency from sidedef @@ -1475,7 +1463,6 @@ private void P_LoadLineDefs2(int lump) { // P_LoadSideDefs // // killough 4/4/98: split into two functions - private void P_LoadSideDefs(int lump) { numsides = DOOM.wadLoader.LumpLength(lump) / mapsidedef_t.sizeOf(); sides = calloc_IfSameLevel(sides, numsides, side_t::new, side_t[]::new); @@ -1484,11 +1471,10 @@ private void P_LoadSideDefs(int lump) { // killough 4/4/98: delay using texture names until // after linedefs are loaded, to allow overloading. // killough 5/3/98: reformatted, cleaned up - private void P_LoadSideDefs2(int lump) { // cph - final*, wad lump handling updated final mapsidedef_t[] data = DOOM.wadLoader.CacheLumpNumIntoArray(lump, numsides, mapsidedef_t::new, mapsidedef_t[]::new); - + for (int i = 0; i < numsides; i++) { final mapsidedef_t msd = data[i]; side_t sd = sides[i]; @@ -1497,13 +1483,14 @@ private void P_LoadSideDefs2(int lump) { sd.textureoffset = msd.textureoffset << FRACBITS; sd.rowoffset = msd.rowoffset << FRACBITS; - { /* + { + /* * cph 2006/09/30 - catch out-of-range sector numbers; use sector * 0 instead - */ + */ char sector_num = (char) msd.sector; if (sector_num >= numsectors) { - System.err.printf("P_LoadSideDefs2: sidedef %i has out-of-range sector num %u\n", i, sector_num); + LOGGER.log(Level.WARNING, String.format("P_LoadSideDefs2: sidedef %d has out-of-range sector num %d", i, (int) sector_num)); sector_num = 0; } sd.sector = sec = sectors[sector_num]; @@ -1513,8 +1500,8 @@ private void P_LoadSideDefs2(int lump) { // killough 4/11/98: refined to allow colormaps to work as wall // textures if invalid as colormaps but valid as textures. switch (sd.special) { - case 242: // variable colormap via 242 linedef - /* + case 242: // variable colormap via 242 linedef + /* * sd.bottomtexture = (sec.bottommap = * R.ColormapNumForName(msd.bottomtexture)) < 0 ? sec.bottommap * = 0, R.TextureNumForName(msd.bottomtexture): 0 ; @@ -1523,41 +1510,39 @@ private void P_LoadSideDefs2(int lump) { * R.TextureNumForName(msd.midtexture) : 0 ; sd.toptexture = * (sec.topmap = R.ColormapNumForName(msd.toptexture)) < 0 ? * sec.topmap = 0, R.TextureNumForName(msd.toptexture) : 0 ; - */ + */ - break; + break; - case 260: // killough 4/11/98: apply translucency to 2s normal texture - if (msd.midtexture.compareToIgnoreCase("TRANMAP") == 0) { - if ((sd.special = DOOM.wadLoader.CheckNumForName(msd.midtexture)) < 0 - || DOOM.wadLoader.LumpLength(sd.special) != 65536) - { - sd.special = 0; - sd.midtexture = (short) DOOM.textureManager.TextureNumForName(msd.midtexture); + case 260: // killough 4/11/98: apply translucency to 2s normal texture + if (msd.midtexture.compareToIgnoreCase("TRANMAP") == 0) { + if ((sd.special = DOOM.wadLoader.CheckNumForName(msd.midtexture)) < 0 + || DOOM.wadLoader.LumpLength(sd.special) != 65536) { + sd.special = 0; + sd.midtexture = (short) DOOM.textureManager.TextureNumForName(msd.midtexture); + } else { + sd.special++; + sd.midtexture = 0; + } } else { - sd.special++; - sd.midtexture = 0; + sd.midtexture = (short) (sd.special = 0); } - } else { - sd.midtexture = (short) (sd.special = 0); - } - sd.toptexture = (short) DOOM.textureManager.TextureNumForName(msd.toptexture); - sd.bottomtexture = (short) DOOM.textureManager.TextureNumForName(msd.bottomtexture); - break; + sd.toptexture = (short) DOOM.textureManager.TextureNumForName(msd.toptexture); + sd.bottomtexture = (short) DOOM.textureManager.TextureNumForName(msd.bottomtexture); + break; - /* + /* * #ifdef GL_DOOM case 271: case 272: if * (R_CheckTextureNumForName(msd.toptexture) == -1) { * sd.skybox_index = R_BoxSkyboxNumForName(msd.toptexture); } #endif - */ - - default: // normal cases - // TODO: Boom uses "SafeTextureNumForName" here. Find out what - // it does. - sd.midtexture = (short) DOOM.textureManager.CheckTextureNumForName(msd.midtexture); - sd.toptexture = (short) DOOM.textureManager.CheckTextureNumForName(msd.toptexture); - sd.bottomtexture = (short) DOOM.textureManager.CheckTextureNumForName(msd.bottomtexture); - break; + */ + default: // normal cases + // TODO: Boom uses "SafeTextureNumForName" here. Find out what + // it does. + sd.midtexture = (short) DOOM.textureManager.CheckTextureNumForName(msd.midtexture); + sd.toptexture = (short) DOOM.textureManager.CheckTextureNumForName(msd.toptexture); + sd.bottomtexture = (short) DOOM.textureManager.CheckTextureNumForName(msd.bottomtexture); + break; } } @@ -1577,8 +1562,8 @@ private void P_LoadBlockMap(int lump) throws IOException { int count = 0; if (DOOM.cVarManager.bool(CommandVariable.BLOCKMAP) - || DOOM.wadLoader.LumpLength(lump) < 8 - || (count = DOOM.wadLoader.LumpLength(lump) / 2) >= 0x10000) // e6y + || DOOM.wadLoader.LumpLength(lump) < 8 + || (count = DOOM.wadLoader.LumpLength(lump) / 2) >= 0x10000) // e6y { CreateBlockMap(); } else { @@ -1594,13 +1579,14 @@ private void P_LoadBlockMap(int lump) throws IOException { data.readCharArray(wadblockmaplump, count); if (!samelevel) // Reallocate if required. + { blockmaplump = new int[count]; + } // killough 3/1/98: Expand wad blockmap into larger internal one, // by treating all offsets except -1 as unsigned and zero-extending // them. This potentially doubles the size of blockmaps allowed, // because Doom originally considered the offsets as always signed. - blockmaplump[0] = wadblockmaplump[0]; blockmaplump[1] = wadblockmaplump[1]; blockmaplump[2] = wadblockmaplump[2] & 0xffff; @@ -1621,8 +1607,8 @@ private void P_LoadBlockMap(int lump) throws IOException { // haleyjd 03/04/10: check for blockmap problems // http://www.doomworld.com/idgames/index.php?id=12935 if (!VerifyBlockMap(count)) { - System.err.printf("P_LoadBlockMap: erroneous BLOCKMAP lump may cause crashes.\n"); - System.err.printf("P_LoadBlockMap: use \"-blockmap\" command line switch for rebuilding\n"); + LOGGER.log(Level.WARNING, String.format("P_LoadBlockMap: erroneous BLOCKMAP lump may cause crashes.")); + LOGGER.log(Level.WARNING, String.format("P_LoadBlockMap: use \"-blockmap\" command line switch for rebuilding")); } } @@ -1641,7 +1627,6 @@ private void P_LoadBlockMap(int lump) throws IOException { // re-instantiated. // Probably caused other bugs as well, as an extra object would appear // in iterators. - if (blocklinks != null && samelevel) { for (int i = 0; i < bmapwidth * bmapheight; i++) { blocklinks[i] = null; @@ -1655,7 +1640,6 @@ private void P_LoadBlockMap(int lump) throws IOException { // If the offsets in the lump are OK, then we can modify them (remove 4) // and copy the rest of the data in one single data array. This avoids // reserving memory for two arrays (we can't simply alias one in Java) - blockmap = new int[blockmaplump.length - 4]; count = bmapwidth * bmapheight; // Offsets are relative to START OF BLOCKMAP, and IN SHORTS, not bytes. @@ -1671,7 +1655,6 @@ private void P_LoadBlockMap(int lump) throws IOException { } } - // MAES: set blockmapxneg and blockmapyneg // E.g. for a full 512x512 map, they should be both // -1. For a 257*257, they should be both -255 etc. @@ -1681,7 +1664,7 @@ private void P_LoadBlockMap(int lump) throws IOException { if (bmapheight > 255) { blockmapyneg = bmapheight - 512; } - + blockmap = blockmaplump; } @@ -1689,7 +1672,6 @@ private void P_LoadBlockMap(int lump) throws IOException { // // P_LoadReject - load the reject table // - private void P_LoadReject(int lumpnum, int totallines) { // dump any old cached reject lump, then cache the new one if (rejectlump != -1) { @@ -1712,8 +1694,6 @@ private void P_LoadReject(int lumpnum, int totallines) { // cph 18/8/99: rewritten to avoid O(numlines * numsectors) section // It makes things more complicated, but saves seconds on big levels // figgi 09/18/00 -- adapted for gl-nodes - - // modified to return totallines (needed by P_LoadReject) private int P_GroupLines() { line_t li; @@ -1860,13 +1840,11 @@ private int P_GroupLines() { // // Firelines (TM) is a Rezistered Trademark of MBF Productions // - private void P_RemoveSlimeTrails() { // killough 10/98 // Hitlist for vertices boolean[] hit = new boolean[numvertexes]; // Searchlist for - for (int i = 0; i < numsegs; i++) { // Go through each seg final line_t l; @@ -1904,14 +1882,12 @@ private void P_RemoveSlimeTrails() { // killough 10/98 // // Are these lumps in the same wad file? // - boolean P_CheckLumpsForSameSource(int lump1, int lump2) { int wad1_index, wad2_index; wadfile_info_t wad1, wad2; if ((unsigned(lump1) >= unsigned(DOOM.wadLoader.NumLumps())) - || (unsigned(lump2) >= unsigned(DOOM.wadLoader.NumLumps()))) - { + || (unsigned(lump2) >= unsigned(DOOM.wadLoader.NumLumps()))) { return false; } @@ -1974,8 +1950,8 @@ void P_CheckLevelWadStructure(final String mapname) { for (i = ML_THINGS + 1; i <= ML_SECTORS; i++) { if (!P_CheckLumpsForSameSource(lumpnum, lumpnum + i)) { DOOM.doomSystem.Error( - "P_SetupLevel: Level wad structure is incomplete. There is no %s lump. (%s)", - ml_labels[i], DOOM.wadLoader.GetNameForLump(lumpnum)); + "P_SetupLevel: Level wad structure is incomplete. There is no %s lump. (%s)", + ml_labels[i], DOOM.wadLoader.GetNameForLump(lumpnum)); } } @@ -1992,7 +1968,6 @@ void P_CheckLevelWadStructure(final String mapname) { // P_SetupLevel // // killough 5/3/98: reformatted, cleaned up - @Override @SourceCode.Suspicious(CauseOfDesyncProbability.LOW) @P_Setup.C(P_SetupLevel) @@ -2008,7 +1983,6 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro // TODO: transparentpresent = false; // R_StopAllInterpolations(); - DOOM.totallive = DOOM.totalkills = DOOM.totalitems = DOOM.totalsecret = DOOM.wminfo.maxfrags = 0; DOOM.wminfo.partime = 180; @@ -2022,37 +1996,42 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro DOOM.players[DOOM.consoleplayer].viewz = 1; // Make sure all sounds are stopped before Z_FreeTags. - S_Start: { + S_Start: + { DOOM.doomSound.Start(); } - Z_FreeTags:; // Z_FreeTags(PU_LEVEL, PU_PURGELEVEL-1); - + Z_FreeTags: + ; // Z_FreeTags(PU_LEVEL, PU_PURGELEVEL-1); + if (rejectlump != -1) { // cph - unlock the reject table DOOM.wadLoader.UnlockLumpNum(rejectlump); rejectlump = -1; } - P_InitThinkers: { + P_InitThinkers: + { DOOM.actions.InitThinkers(); } // if working with a devlopment map, reload it - W_Reload:; // killough 1/31/98: W.Reload obsolete + W_Reload: + ; // killough 1/31/98: W.Reload obsolete // find map name if (DOOM.isCommercial()) { lumpname = String.format("map%02d", map); // killough 1/24/98: - // simplify + // simplify gl_lumpname = String.format("gl_map%02d", map); // figgi } else { lumpname = String.format("E%dM%d", episode, map); // killough - // 1/24/98: - // simplify + // 1/24/98: + // simplify gl_lumpname = String.format("GL_E%dM%d", episode, map); // figgi } - W_GetNumForName: { + W_GetNumForName: + { lumpnum = DOOM.wadLoader.GetNumForName(lumpname); gl_lumpnum = DOOM.wadLoader.CheckNumForName(gl_lumpname); // figgi } @@ -2066,11 +2045,9 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro DOOM.totallive = 0; // note: most of this ordering is important - // killough 3/1/98: P_LoadBlockMap call moved down to below // killough 4/4/98: split load of sidedefs into two parts, // to allow texture names to be used in special linedefs - // figgi 10/19/00 -- check for gl lumps and load them P_GetNodesVersion(lumpnum, gl_lumpnum); @@ -2080,7 +2057,6 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro // It is important for OpenGL, because in case of the same data in // memory // we can skip recalculation of much stuff - samelevel = (map == current_map) && (episode == current_episode) && (nodesVersion == current_nodesVersion); current_episode = episode; @@ -2093,17 +2069,14 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro * if (GL_DOOM){ // proff 11/99: clean the memory from textures etc. * gld_CleanMemory(); } */ - // free(segs); // free(nodes); // free(subsectors); /* * #ifdef GL_DOOM free(map_subsectors); #endif */ - // free(blocklinks); // free(blockmaplump); - // free(lines); // free(sides); // free(sectors); @@ -2115,7 +2088,7 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro } else { P_LoadVertexes(lumpnum + ML_VERTEXES); } - + P_LoadSectors(lumpnum + ML_SECTORS); P_LoadSideDefs(lumpnum + ML_SIDEDEFS); P_LoadLineDefs(lumpnum + ML_LINEDEFS); @@ -2161,18 +2134,16 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro * if (GL_DOOM){ map_subsectors = calloc_IfSameLevel(map_subsectors, * numsubsectors); } */ - // reject loading and underflow padding separated out into new function // P_GroupLines modified to return a number the underflow padding needs // P_LoadReject(lumpnum, P_GroupLines()); P_GroupLines(); - super.LoadReject(lumpnum+ML_REJECT); + super.LoadReject(lumpnum + ML_REJECT); /** * TODO: try to fix, since it seems it doesn't work * - Good Sign 2017/05/07 */ - // e6y // Correction of desync on dv04-423.lmp/dv.wad // http://www.doomworld.com/vb/showthread.php?s=&postid=627257#post627257 @@ -2182,11 +2153,9 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro // Note: you don't need to clear player queue slots -- // a much simpler fix is in g_game.c -- killough 10/98 - DOOM.bodyqueslot = 0; /* cph - reset all multiplayer starts */ - for (int i = 0; i < playerstarts.length; i++) { DOOM.playerstarts[i] = null; } @@ -2199,8 +2168,8 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro // TODO: TracerClearStarts(); // Hmm? P_MapStart(); - - P_LoadThings: { + P_LoadThings: + { P_LoadThings(lumpnum + ML_THINGS); } @@ -2209,7 +2178,8 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro for (int i = 0; i < Limits.MAXPLAYERS; i++) { if (DOOM.playeringame[i]) { DOOM.players[i].mo = null; // not needed? - done before P_LoadThings - G_DeathMatchSpawnPlayer: { + G_DeathMatchSpawnPlayer: + { DOOM.DeathMatchSpawnPlayer(i); } } @@ -2225,7 +2195,6 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro // killough 3/26/98: Spawn icon landings: // TODO: if (DM.isCommercial()) // P.SpawnBrainTargets(); - if (!DOOM.isShareware()) { // TODO: S.ParseMusInfo(lumpname); } @@ -2234,16 +2203,17 @@ public void SetupLevel(int episode, int map, int playermask, skill_t skill) thro DOOM.actions.ClearRespawnQueue(); // set up world state - P_SpawnSpecials: { + P_SpawnSpecials: + { DOOM.actions.SpawnSpecials(); } // TODO: P.MapEnd(); - // preload graphics if (DOOM.precache) { /* @SourceCode.Compatible if together */ - R_PrecacheLevel: { + R_PrecacheLevel: + { DOOM.textureManager.PrecacheLevel(); // MAES: thinkers are separate than texture management. Maybe split diff --git a/src/p/ChaseDirections.java b/src/p/ChaseDirections.java index 72b60b83..d461f7dd 100644 --- a/src/p/ChaseDirections.java +++ b/src/p/ChaseDirections.java @@ -1,7 +1,7 @@ package p; -import static m.fixed_t.MAPFRACUNIT; import static data.Defines.TIC_MUL; +import static m.fixed_t.MAPFRACUNIT; public final class ChaseDirections { @@ -24,23 +24,23 @@ public final class ChaseDirections { public static final int DI_NODIR = 8; public static final int NUMDIR = 9; - + // // P_NewChaseDir related LUT. // - public final static int opposite[] = - { DI_WEST, DI_SOUTHWEST, DI_SOUTH, DI_SOUTHEAST, DI_EAST, DI_NORTHEAST, - DI_NORTH, DI_NORTHWEST, DI_NODIR }; + public final static int opposite[] + = {DI_WEST, DI_SOUTHWEST, DI_SOUTH, DI_SOUTHEAST, DI_EAST, DI_NORTHEAST, + DI_NORTH, DI_NORTHWEST, DI_NODIR}; + + public final static int diags[] + = {DI_NORTHWEST, DI_NORTHEAST, DI_SOUTHWEST, DI_SOUTHEAST}; - public final static int diags[] = - { DI_NORTHWEST, DI_NORTHEAST, DI_SOUTHWEST, DI_SOUTHEAST }; + public final static int[] xspeed + = {MAPFRACUNIT, 47000 / TIC_MUL, 0, -47000 / TIC_MUL, -MAPFRACUNIT, -47000 / TIC_MUL, 0, 47000 / TIC_MUL}; // all + // fixed - public final static int[] xspeed = - { MAPFRACUNIT, 47000/TIC_MUL, 0, -47000/TIC_MUL, -MAPFRACUNIT, -47000/TIC_MUL, 0, 47000/TIC_MUL }; // all - // fixed + public final static int[] yspeed + = {0, 47000 / TIC_MUL, MAPFRACUNIT, 47000 / TIC_MUL, 0, -47000 / TIC_MUL, -MAPFRACUNIT, -47000 / TIC_MUL}; // all + // fixed - public final static int[] yspeed = - { 0, 47000/TIC_MUL, MAPFRACUNIT, 47000/TIC_MUL, 0, -47000/TIC_MUL, -MAPFRACUNIT, -47000/TIC_MUL }; // all - // fixed - } diff --git a/src/p/DoomPlayer.java b/src/p/DoomPlayer.java index b57e5ed6..9c616288 100644 --- a/src/p/DoomPlayer.java +++ b/src/p/DoomPlayer.java @@ -3,36 +3,31 @@ import m.fixed_t; public interface DoomPlayer { - - public fixed_t - AimLineAttack - ( mobj_t t1, - int angle, - fixed_t distance ); - public void - LineAttack - ( mobj_t t1, - int angle, - fixed_t distance, - fixed_t slope, - int damage ); + public fixed_t + AimLineAttack(mobj_t t1, + int angle, + fixed_t distance); - void - RadiusAttack - ( mobj_t spot, - mobj_t source, - int damage ); - - void - TouchSpecialThing - ( mobj_t special, - mobj_t toucher ); + public void + LineAttack(mobj_t t1, + int angle, + fixed_t distance, + fixed_t slope, + int damage); - void - DamageMobj - ( mobj_t target, - mobj_t inflictor, - mobj_t source, - int damage ); - } + void + RadiusAttack(mobj_t spot, + mobj_t source, + int damage); + + void + TouchSpecialThing(mobj_t special, + mobj_t toucher); + + void + DamageMobj(mobj_t target, + mobj_t inflictor, + mobj_t source, + int damage); +} diff --git a/src/p/DoorDefines.java b/src/p/DoorDefines.java index 48b98a83..7e0bc718 100644 --- a/src/p/DoorDefines.java +++ b/src/p/DoorDefines.java @@ -3,12 +3,11 @@ import static m.fixed_t.MAPFRACUNIT; public final class DoorDefines { - + // Doors public static final int VDOORSPEED = MAPFRACUNIT * 2; public static final int VDOORWAIT = 150; - - + // Lights public static final int GLOWSPEED = 5; @@ -17,6 +16,5 @@ public final class DoorDefines { public static final int FASTDARK = 15; public static final int SLOWDARK = 35; - - + } diff --git a/src/p/ILevelLoader.java b/src/p/ILevelLoader.java index ebcbffb6..d3b96b48 100644 --- a/src/p/ILevelLoader.java +++ b/src/p/ILevelLoader.java @@ -8,9 +8,8 @@ public interface ILevelLoader { - // Lump order in a map WAD: each map needs a couple of lumps + // Lump order in a map WAD: each map needs a couple of lumps // to provide a complete scene geometry description. - public static final int ML_LABEL = 0; /** A separator, name, ExMx or MAPxx */ @@ -42,14 +41,14 @@ public interface ILevelLoader { /** LUT, sector-sector visibility */ public static final int ML_BLOCKMAP = 10; - + // Maintain single and multi player starting spots. - public static final int MAX_DEATHMATCH_STARTS = 10; + public static final int MAX_DEATHMATCH_STARTS = 10; /** Expected lump names for verification */ - public static final String[] LABELS={"MAPNAME","THINGS","LINEDEFS","SIDEDEFS", - "VERTEXES","SEGS","SSECTORS","NODES", - "SECTORS","REJECT","BLOCKMAP"}; + public static final String[] LABELS = {"MAPNAME", "THINGS", "LINEDEFS", "SIDEDEFS", + "VERTEXES", "SEGS", "SSECTORS", "NODES", + "SECTORS", "REJECT", "BLOCKMAP"}; /** P_SetupLevel * @@ -60,28 +59,26 @@ public interface ILevelLoader { * @throws IOException */ @P_Setup.C(P_SetupLevel) - void SetupLevel(int episode, int map, int playermask, skill_t skill) throws IOException; - - /** - * P_SetThingPosition Links a thing into both a block and a subsector based - * on it's x y. Sets thing.subsector properly - * - * - * @param thing - */ - void SetThingPosition(mobj_t thing); - - /** - * R_PointInSubsector - * - * MAES: it makes more sense to have this here. - * - * @param x fixed - * @param y fixed - * - */ - - subsector_t PointInSubsector(int x, int y); - - + void SetupLevel(int episode, int map, int playermask, skill_t skill) throws IOException; + + /** + * P_SetThingPosition Links a thing into both a block and a subsector based + * on it's x y. Sets thing.subsector properly + * + * + * @param thing + */ + void SetThingPosition(mobj_t thing); + + /** + * R_PointInSubsector + * + * MAES: it makes more sense to have this here. + * + * @param x fixed + * @param y fixed + * + */ + subsector_t PointInSubsector(int x, int y); + } diff --git a/src/p/ISightChecker.java b/src/p/ISightChecker.java index 82e20192..c81e4770 100644 --- a/src/p/ISightChecker.java +++ b/src/p/ISightChecker.java @@ -3,7 +3,9 @@ public interface ISightChecker { public void setZStartTopBOttom(int zstart, int top, int bottom); + public void setSTrace(mobj_t t1, mobj_t t2); + public boolean CrossBSPNode(int bspnum); - + } diff --git a/src/p/LevelLoader.java b/src/p/LevelLoader.java index af9b179a..9564d3d3 100644 --- a/src/p/LevelLoader.java +++ b/src/p/LevelLoader.java @@ -1,6 +1,9 @@ package p; -import static data.Defines.*; +import static data.Defines.MAPBLOCKSHIFT; +import static data.Defines.NF_SUBSECTOR; +import static data.Defines.NF_SUBSECTOR_CLASSIC; +import static data.Defines.PU_LEVEL; import static data.Limits.MAXPLAYERS; import static data.Limits.MAXRADIUS; import data.maplinedef_t; @@ -11,11 +14,14 @@ import data.mapsubsector_t; import data.mapthing_t; import data.mapvertex_t; -import defines.*; +import defines.skill_t; +import defines.slopetype_t; import doom.CommandVariable; import doom.DoomMain; import java.io.IOException; import java.nio.ByteOrder; +import java.util.logging.Level; +import java.util.logging.Logger; import m.BBox; import static m.BBox.BOXBOTTOM; import static m.BBox.BOXLEFT; @@ -23,6 +29,7 @@ import static m.BBox.BOXTOP; import static m.fixed_t.FRACBITS; import static m.fixed_t.FixedDiv; +import mochadoom.Loggers; import rr.line_t; import static rr.line_t.ML_TWOSIDED; import rr.node_t; @@ -60,6 +67,8 @@ //----------------------------------------------------------------------------- public class LevelLoader extends AbstractLevelLoader { + private static final Logger LOGGER = Loggers.getLogger(LevelLoader.class.getName()); + public static final String rcsid = "$Id: LevelLoader.java,v 1.44 2012/09/24 17:16:23 velktron Exp $"; public LevelLoader(DoomMain DM) { @@ -239,10 +248,9 @@ public void LoadNodes(int lump) throws IOException { // haleyjd 11/06/10: check for invalid subsector reference if (no.children[j] >= numsubsectors) { - System.err - .printf( - "P_LoadNodes: BSP tree references invalid subsector %d.\n", - no.children[j]); + LOGGER.log(Level.WARNING, String.format( + "P_LoadNodes: BSP tree references invalid subsector %d.", + no.children[j])); no.children[j] = 0; } @@ -469,7 +477,7 @@ public void LoadBlockMap(int lump) throws IOException { int count = 0; if (DOOM.cVarManager.bool(CommandVariable.BLOCKMAP) || DOOM.wadLoader.LumpLength(lump) < 8 - || (count = DOOM.wadLoader.LumpLength(lump) / 2) >= 0x10000) // e6y + || (count = DOOM.wadLoader.LumpLength(lump) / 2) >= 0x10000) // e6y { CreateBlockMap(); } else { @@ -497,10 +505,8 @@ public void LoadBlockMap(int lump) throws IOException { // haleyjd 03/04/10: check for blockmap problems // http://www.doomworld.com/idgames/index.php?id=12935 if (!VerifyBlockMap(count)) { - System.err - .printf("P_LoadBlockMap: erroneous BLOCKMAP lump may cause crashes.\n"); - System.err - .printf("P_LoadBlockMap: use \"-blockmap\" command line switch for rebuilding\n"); + LOGGER.log(Level.WARNING, "P_LoadBlockMap: erroneous BLOCKMAP lump may cause crashes.\n"); + LOGGER.log(Level.WARNING, "P_LoadBlockMap: use \"-blockmap\" command line switch for rebuilding\n"); } } @@ -631,7 +637,7 @@ public void GroupLines() { // set the degenmobj_t to the middle of the bounding box sector.soundorg = new degenmobj_t(((bbox[BOXRIGHT] + bbox[BOXLEFT]) / 2), - ((bbox[BOXTOP] + bbox[BOXBOTTOM]) / 2), (sector.ceilingheight - sector.floorheight) / 2); + ((bbox[BOXTOP] + bbox[BOXBOTTOM]) / 2), (sector.ceilingheight - sector.floorheight) / 2); // adjust bounding box to map blocks block = (bbox[BOXTOP] - bmaporgy + MAXRADIUS) >> MAPBLOCKSHIFT; @@ -655,10 +661,10 @@ public void GroupLines() { @Override public void - SetupLevel(int episode, - int map, - int playermask, - skill_t skill) { + SetupLevel(int episode, + int map, + int playermask, + skill_t skill) { int i; String lumpname; int lumpnum; @@ -668,7 +674,7 @@ public void GroupLines() { DOOM.wminfo.partime = 180; for (i = 0; i < MAXPLAYERS; i++) { DOOM.players[i].killcount = DOOM.players[i].secretcount - = DOOM.players[i].itemcount = 0; + = DOOM.players[i].itemcount = 0; } // Initial height of PointOfView @@ -704,9 +710,9 @@ public void GroupLines() { } } else { lumpname = ("E" - + (char) ('0' + episode) - + "M" - + (char) ('0' + map)); + + (char) ('0' + episode) + + "M" + + (char) ('0' + map)); } lumpnum = DOOM.wadLoader.GetNumForName(lumpname); @@ -714,7 +720,7 @@ public void GroupLines() { DOOM.leveltime = 0; if (!DOOM.wadLoader.verifyLumpName(lumpnum + ML_BLOCKMAP, LABELS[ML_BLOCKMAP])) { - System.err.println("Blockmap missing!"); + LOGGER.log(Level.WARNING, "Blockmap missing!"); } // note: most of this ordering is important @@ -768,8 +774,7 @@ public void GroupLines() { } } catch (Exception e) { - System.err.println("Error while loading level"); - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Error while loading level", e); } } diff --git a/src/p/MapUtils.java b/src/p/MapUtils.java index 32f66e90..5a367231 100644 --- a/src/p/MapUtils.java +++ b/src/p/MapUtils.java @@ -6,59 +6,55 @@ public class MapUtils { + /** + * AproxDistance + * Gives an estimation of distance (not exact) + * + * @param dx fixed_t + * @param dy fixed_t + * @return fixed_t + */ + // + public static int + AproxDistance(int dx, + int dy) { + dx = Math.abs(dx); + dy = Math.abs(dy); + if (dx < dy) { + return dx + dy - (dx >> 1); + } + return dx + dy - (dy >> 1); + } - /** - * AproxDistance - * Gives an estimation of distance (not exact) - * - * @param dx fixed_t - * @param dy fixed_t - * @return fixed_t - */ - // - public static int - AproxDistance - ( int dx, - int dy ) - { - dx = Math.abs(dx); - dy = Math.abs(dy); - if (dx < dy) - return dx+dy-(dx>>1); - return dx+dy-(dy>>1); - } - - /** - * P_InterceptVector - * Returns the fractional intercept point - * along the first divline. - * This is only called by the addthings - * and addlines traversers. - * - * @return int to be treated as fixed_t - */ - - public static int - InterceptVector - ( divline_t v2, - divline_t v1 ) - { - int frac, num,den; // fixed_t - - den = FixedMul (v1.dy>>8,v2.dx) - FixedMul(v1.dx>>8,v2.dy); - - if (den == 0) - return 0; - // I_Error ("P_InterceptVector: parallel"); - - num = - FixedMul ( (v1.x - v2.x)>>8 ,v1.dy ) - +FixedMul ( (v2.y - v1.y)>>8, v1.dx ); - - frac = FixedDiv (num , den); - - return frac; - /* + /** + * P_InterceptVector + * Returns the fractional intercept point + * along the first divline. + * This is only called by the addthings + * and addlines traversers. + * + * @return int to be treated as fixed_t + */ + public static int + InterceptVector(divline_t v2, + divline_t v1) { + int frac, num, den; // fixed_t + + den = FixedMul(v1.dy >> 8, v2.dx) - FixedMul(v1.dx >> 8, v2.dy); + + if (den == 0) { + return 0; + } + // I_Error ("P_InterceptVector: parallel"); + + num + = FixedMul((v1.x - v2.x) >> 8, v1.dy) + + FixedMul((v2.y - v1.y) >> 8, v1.dx); + + frac = FixedDiv(num, den); + + return frac; + /* #else // UNUSED, float debug. float frac; float num; @@ -91,68 +87,66 @@ public class MapUtils { return frac*FRACUNIT; #endif */ - } - + } + - /* cph - this is killough's 4/19/98 version of P_InterceptVector and + /* cph - this is killough's 4/19/98 version of P_InterceptVector and * P_InterceptVector2 (which were interchangeable). We still use this * in compatibility mode. */ - private static final int P_InterceptVector2(final divline_t v2, final divline_t v1) - { - int den; - return eval(den = FixedMul(v1.dy>>8, v2.dx) - FixedMul(v1.dx>>8, v2.dy)) ? - FixedDiv(FixedMul((v1.x - v2.x)>>8, v1.dy) + - FixedMul((v2.y - v1.y)>>8, v1.dx), den) : 0; - } - - - /** Used by CrossSubSector - * - * @param v2 - * @param v1 - * @return - */ - public static final int P_InterceptVector(final divline_t v2, final divline_t v1) - { - if (false/*compatibility_level < prboom_4_compatibility*/) - return P_InterceptVector2(v2, v1); - else { - /* cph - This was introduced at prboom_4_compatibility - no precision/overflow problems */ - long den = (long)v1.dy * v2.dx - (long)v1.dx * v2.dy; - den >>= 16; - if (!eval(den)) - return 0; - return (int)(((long)(v1.x - v2.x) * v1.dy - (long)(v1.y - v2.y) * v1.dx) / den); + private static final int P_InterceptVector2(final divline_t v2, final divline_t v1) { + int den; + return eval(den = FixedMul(v1.dy >> 8, v2.dx) - FixedMul(v1.dx >> 8, v2.dy)) + ? FixedDiv(FixedMul((v1.x - v2.x) >> 8, v1.dy) + + FixedMul((v2.y - v1.y) >> 8, v1.dx), den) : 0; + } + + /** Used by CrossSubSector + * + * @param v2 + * @param v1 + * @return + */ + public static final int P_InterceptVector(final divline_t v2, final divline_t v1) { + if (false/*compatibility_level < prboom_4_compatibility*/) { + return P_InterceptVector2(v2, v1); + } else { + /* cph - This was introduced at prboom_4_compatibility - no precision/overflow problems */ + long den = (long) v1.dy * v2.dx - (long) v1.dx * v2.dy; + den >>= 16; + if (!eval(den)) { + return 0; + } + return (int) (((long) (v1.x - v2.x) * v1.dy - (long) (v1.y - v2.y) * v1.dx) / den); + } } - } - - /** - * P_InterceptVector2 Returns the fractional intercept point along the - * first divline. This is only called by the addthings and addlines - * traversers. - * - * @param v2 - * @param v1 - * @returnP_InterceptVector2 - */ - - public static final int InterceptVector2(divline_t v2, divline_t v1) { - int frac; // fixed_t - int num; // fixed_t - int den; // fixed_t - - den = FixedMul(v1.dy >> 8, v2.dx) - FixedMul(v1.dx >> 8, v2.dy); - - if (den == 0) - return 0; - // I_Error ("P_InterceptVector: parallel"); - - num = - FixedMul((v1.x - v2.x) >> 8, v1.dy) - + FixedMul((v2.y - v1.y) >> 8, v1.dx); - frac = FixedDiv(num, den); - - return frac; - } - + + /** + * P_InterceptVector2 Returns the fractional intercept point along the + * first divline. This is only called by the addthings and addlines + * traversers. + * + * @param v2 + * @param v1 + * @returnP_InterceptVector2 + */ + public static final int InterceptVector2(divline_t v2, divline_t v1) { + int frac; // fixed_t + int num; // fixed_t + int den; // fixed_t + + den = FixedMul(v1.dy >> 8, v2.dx) - FixedMul(v1.dx >> 8, v2.dy); + + if (den == 0) { + return 0; + } + // I_Error ("P_InterceptVector: parallel"); + + num + = FixedMul((v1.x - v2.x) >> 8, v1.dy) + + FixedMul((v2.y - v1.y) >> 8, v1.dx); + frac = FixedDiv(num, den); + + return frac; + } + } diff --git a/src/p/MobjFlags.java b/src/p/MobjFlags.java index 333ce043..59df55d9 100644 --- a/src/p/MobjFlags.java +++ b/src/p/MobjFlags.java @@ -1,9 +1,8 @@ package p; /** YEAH, I'M USING THE CONSTANTS INTERFACE PATTERN. DEAL WITH IT */ - public interface MobjFlags { - // // MF_ flags for mobjs. + // // MF_ flags for mobjs. // Call P_SpecialThing when touched. public static final long MF_SPECIAL = 1; @@ -89,22 +88,20 @@ public interface MobjFlags { // Hmm ???. public static final long MF_TRANSSHIFT = 26; - public static final long MF_UNUSED2 =(0x0000000010000000); - public static final long MF_UNUSED3 =(0x0000000020000000); + public static final long MF_UNUSED2 = (0x0000000010000000); + public static final long MF_UNUSED3 = (0x0000000020000000); - // Translucent sprite? // phares - public static final long MF_TRANSLUCENT =(0x0000000040000000); + // Translucent sprite? // phares + public static final long MF_TRANSLUCENT = (0x0000000040000000); // this is free LONGLONG(0x0000000100000000) - // these are greater than an int. That's why the flags below are now uint_64_t + public static final long MF_TOUCHY = (0x0000000100000000L); + public static final long MF_BOUNCES = (0x0000000200000000L); + public static final long MF_FRIEND = (0x0000000400000000L); - public static final long MF_TOUCHY = (0x0000000100000000L); - public static final long MF_BOUNCES =(0x0000000200000000L); - public static final long MF_FRIEND = (0x0000000400000000L); + public static final long MF_RESSURECTED = (0x0000001000000000L); + public static final long MF_NO_DEPTH_TEST = (0x0000002000000000L); + public static final long MF_FOREGROUND = (0x0000004000000000L); - public static final long MF_RESSURECTED =(0x0000001000000000L); - public static final long MF_NO_DEPTH_TEST =(0x0000002000000000L); - public static final long MF_FOREGROUND = (0x0000004000000000L); - } diff --git a/src/p/RemoveState.java b/src/p/RemoveState.java index cd0824f3..d50afbf1 100644 --- a/src/p/RemoveState.java +++ b/src/p/RemoveState.java @@ -2,4 +2,4 @@ public enum RemoveState implements ThinkerStates { REMOVE; -} \ No newline at end of file +} diff --git a/src/p/Resettable.java b/src/p/Resettable.java index 0eec71d7..aea1478d 100644 --- a/src/p/Resettable.java +++ b/src/p/Resettable.java @@ -2,7 +2,7 @@ /** For objects that needed to be memset to 0 in C, * rather than being reallocated. */ - public interface Resettable { + public void reset(); } diff --git a/src/p/Specials.java b/src/p/Specials.java index fbac2cc3..bf20491a 100644 --- a/src/p/Specials.java +++ b/src/p/Specials.java @@ -2,7 +2,7 @@ import doom.player_t; import m.fixed_t; -import static m.fixed_t.*; +import static m.fixed_t.FRACUNIT; import p.Actions.ActionsLights.glow_t; import p.Actions.ActionsLights.lightflash_t; import rr.line_t; @@ -33,7 +33,6 @@ // utility functions, etc. // //----------------------------------------------------------------------------- - public interface Specials { // @@ -41,187 +40,169 @@ public interface Specials { // //extern boolean levelTimer; //extern int levelTimeCount; - - // Define values for map objects -public static final int MO_TELEPORTMAN =14; - + public static final int MO_TELEPORTMAN = 14; // at game start -public void P_InitPicAnims (); + public void P_InitPicAnims(); // at map load -public void P_SpawnSpecials (); + public void P_SpawnSpecials(); // every tic -public void P_UpdateSpecials (); + public void P_UpdateSpecials(); // when needed -public boolean -P_UseSpecialLine -( mobj_t thing, - line_t line, - int side ); - -public void -P_ShootSpecialLine -( mobj_t thing, - line_t line ); - -public -void -P_CrossSpecialLine -( int linenum, - int side, - mobj_t thing ); + public boolean + P_UseSpecialLine(mobj_t thing, + line_t line, + int side); -public void P_PlayerInSpecialSector (player_t player); + public void + P_ShootSpecialLine(mobj_t thing, + line_t line); -public int -twoSided -( int sector, - int line ); + public void + P_CrossSpecialLine(int linenum, + int side, + mobj_t thing); -public sector_t -getSector -( int currentSector, - int line, - int side ); + public void P_PlayerInSpecialSector(player_t player); -side_t -getSide -( int currentSector, - int line, - int side ); + public int + twoSided(int sector, + int line); -public fixed_t P_FindLowestFloorSurrounding(sector_t sec); -public fixed_t P_FindHighestFloorSurrounding(sector_t sec); + public sector_t + getSector(int currentSector, + int line, + int side); -public fixed_t -P_FindNextHighestFloor -( sector_t sec, - int currentheight ); + side_t + getSide(int currentSector, + int line, + int side); -public fixed_t P_FindLowestCeilingSurrounding(sector_t sec); -public fixed_t P_FindHighestCeilingSurrounding(sector_t sec); + public fixed_t P_FindLowestFloorSurrounding(sector_t sec); -public int -P_FindSectorFromLineTag -( line_t line, - int start ); + public fixed_t P_FindHighestFloorSurrounding(sector_t sec); -public int -P_FindMinSurroundingLight -( sector_t sector, - int max ); + public fixed_t + P_FindNextHighestFloor(sector_t sec, + int currentheight); -public sector_t -getNextSector -( line_t line, - sector_t sec ); + public fixed_t P_FindLowestCeilingSurrounding(sector_t sec); + public fixed_t P_FindHighestCeilingSurrounding(sector_t sec); + + public int + P_FindSectorFromLineTag(line_t line, + int start); + + public int + P_FindMinSurroundingLight(sector_t sector, + int max); + + public sector_t + getNextSector(line_t line, + sector_t sec); // // SPECIAL // -int EV_DoDonut(line_t line); + int EV_DoDonut(line_t line); + public static final int GLOWSPEED = 8; + public static final int STROBEBRIGHT = 5; + public static final int FASTDARK = 15; + public static final int SLOWDARK = 35; -public static final int GLOWSPEED = 8; -public static final int STROBEBRIGHT= 5; -public static final int FASTDARK = 15; -public static final int SLOWDARK = 35; + public void P_SpawnFireFlicker(sector_t sector); + public void T_LightFlash(lightflash_t flash); -public void P_SpawnFireFlicker (sector_t sector); -public void T_LightFlash (lightflash_t flash); -public void P_SpawnLightFlash (sector_t sector); -public void T_StrobeFlash (strobe_t flash); + public void P_SpawnLightFlash(sector_t sector); -public void -P_SpawnStrobeFlash -( sector_t sector, - int fastOrSlow, - int inSync ); + public void T_StrobeFlash(strobe_t flash); -public void EV_StartLightStrobing(line_t line); -public void EV_TurnTagLightsOff(line_t line); + public void + P_SpawnStrobeFlash(sector_t sector, + int fastOrSlow, + int inSync); -public void -EV_LightTurnOn -( line_t line, - int bright ); + public void EV_StartLightStrobing(line_t line); -public void T_Glow(glow_t g); -public void P_SpawnGlowingLight(sector_t sector); + public void EV_TurnTagLightsOff(line_t line); - // max # of wall switches in a level -public static final int MAXSWITCHES = 50; + public void + EV_LightTurnOn(line_t line, + int bright); - // 4 players, 4 buttons each at once, max. -public static final int MAXBUTTONS =16; + public void T_Glow(glow_t g); - // 1 second, in ticks. -public static final int BUTTONTIME = 35 ; + public void P_SpawnGlowingLight(sector_t sector); -//extern button_t buttonlist[MAXBUTTONS]; + // max # of wall switches in a level + public static final int MAXSWITCHES = 50; + + // 4 players, 4 buttons each at once, max. + public static final int MAXBUTTONS = 16; -public void -P_ChangeSwitchTexture -( line_t line, - int useAgain ); + // 1 second, in ticks. + public static final int BUTTONTIME = 35; -public void P_InitSwitchList(); +//extern button_t buttonlist[MAXBUTTONS]; + public void + P_ChangeSwitchTexture(line_t line, + int useAgain); -public static final int PLATWAIT = 3; -public static final int PLATSPEED = FRACUNIT; -public static final int MAXPLATS = 30; + public void P_InitSwitchList(); + public static final int PLATWAIT = 3; + public static final int PLATSPEED = FRACUNIT; + public static final int MAXPLATS = 30; //extern plat_t* activeplats[MAXPLATS]; + public void T_PlatRaise(plat_t plat); -public void T_PlatRaise(plat_t plat); + public int + EV_DoPlat(line_t line, + plattype_e type, + int amount); -public int -EV_DoPlat -( line_t line, - plattype_e type, - int amount ); + void P_AddActivePlat(plat_t plat); -void P_AddActivePlat(plat_t plat); -void P_RemoveActivePlat(plat_t plat); -void EV_StopPlat(line_t line); -void P_ActivateInStasis(int tag); + void P_RemoveActivePlat(plat_t plat); -public static final int VDOORSPEED = FRACUNIT*2; -public static final int VDOORWAIT = 150; + void EV_StopPlat(line_t line); -void -EV_VerticalDoor -( line_t line, - mobj_t thing ); + void P_ActivateInStasis(int tag); -int -EV_DoDoor -( line_t line, - vldoor_e type ); + public static final int VDOORSPEED = FRACUNIT * 2; + public static final int VDOORWAIT = 150; -int -EV_DoLockedDoor -( line_t line, - vldoor_e type, - mobj_t thing ); + void + EV_VerticalDoor(line_t line, + mobj_t thing); -public void T_VerticalDoor (vldoor_t door); -public void P_SpawnDoorCloseIn30 (sector_t sec); + int + EV_DoDoor(line_t line, + vldoor_e type); -void -P_SpawnDoorRaiseIn5Mins -( sector_t sec, - int secnum ); + int + EV_DoLockedDoor(line_t line, + vldoor_e type, + mobj_t thing); -} + public void T_VerticalDoor(vldoor_t door); + + public void P_SpawnDoorCloseIn30(sector_t sec); + void + P_SpawnDoorRaiseIn5Mins(sector_t sec, + int secnum); + +} // UNUSED // @@ -246,9 +227,9 @@ public interface Specials { sdt_openAndClose } sdt_e; -*/ + */ -/* + /* typedef struct { @@ -263,9 +244,9 @@ public interface Specials { sd_e status; } slidedoor_t; -*/ + */ -/* + /* typedef struct { @@ -279,9 +260,9 @@ public interface Specials { char backFrame4[9]; } slidename_t; -*/ + */ -/* + /* typedef struct { @@ -290,9 +271,9 @@ public interface Specials { } slideframe_t; -*/ + */ -/* + /* // how many frames of animation #define SNUMFRAMES 4 @@ -358,4 +339,4 @@ public interface Specials { ( line_t* line, int side, mobj_t* thing ); -*/ \ No newline at end of file + */ diff --git a/src/p/ThinkerList.java b/src/p/ThinkerList.java index 2e772962..7cee6413 100644 --- a/src/p/ThinkerList.java +++ b/src/p/ThinkerList.java @@ -1,18 +1,23 @@ package p; import doom.SourceCode.P_Tick; -import static doom.SourceCode.P_Tick.*; +import static doom.SourceCode.P_Tick.P_AddThinker; +import static doom.SourceCode.P_Tick.P_InitThinkers; +import static doom.SourceCode.P_Tick.P_RemoveThinker; import doom.thinker_t; public interface ThinkerList { @P_Tick.C(P_AddThinker) void AddThinker(thinker_t thinker); + @P_Tick.C(P_RemoveThinker) void RemoveThinker(thinker_t thinker); + @P_Tick.C(P_InitThinkers) void InitThinkers(); - + thinker_t getRandomThinker(); + thinker_t getThinkerCap(); } diff --git a/src/p/ThinkerStates.java b/src/p/ThinkerStates.java index 15d922af..5cb01a97 100644 --- a/src/p/ThinkerStates.java +++ b/src/p/ThinkerStates.java @@ -1,5 +1,6 @@ package p; public interface ThinkerStates { + int ordinal(); -} \ No newline at end of file +} diff --git a/src/p/UnifiedGameMap.java b/src/p/UnifiedGameMap.java index 32ce3589..8fc6847e 100644 --- a/src/p/UnifiedGameMap.java +++ b/src/p/UnifiedGameMap.java @@ -10,7 +10,8 @@ import doom.SourceCode; import doom.SourceCode.CauseOfDesyncProbability; import doom.SourceCode.P_Tick; -import static doom.SourceCode.P_Tick.*; +import static doom.SourceCode.P_Tick.P_AddThinker; +import static doom.SourceCode.P_Tick.P_InitThinkers; import doom.thinker_t; import java.util.Arrays; import java.util.logging.Level; @@ -26,17 +27,17 @@ import static utils.GenericCopy.malloc; // // FROM SIGHT - public abstract class UnifiedGameMap implements ThinkerList { + private static final Logger LOGGER = Loggers.getLogger(UnifiedGameMap.class.getName()); - + /** * killough's code for thinkers seems to be totally broken in M.D, * so commented it out and will not probably restore, but may invent * something new in future * - Good Sign 2017/05/1 */ - public UnifiedGameMap(DoomMain DOOM){ + public UnifiedGameMap(DoomMain DOOM) { this.SW = new Switches(); this.SPECS = new Specials(); this.thinkercap = new thinker_t(); @@ -54,12 +55,10 @@ public UnifiedGameMap(DoomMain DOOM){ FUNS.doWireState(state); }*/ } - - /////////////////// STATUS /////////////////// + /////////////////// STATUS /////////////////// final DoomMain DOOM; - // //////////// Internal singletons ////////////// public ActionFunctions A; @@ -68,12 +67,9 @@ public UnifiedGameMap(DoomMain DOOM){ Switches SW; // //////////////////////////////////////////// - // // THING POSITION SETTING // - - // // BLOCK MAP ITERATORS // For each line/thing in the given mapblock, @@ -81,9 +77,8 @@ public UnifiedGameMap(DoomMain DOOM){ // If the function returns false, // exit with false without checking anything else. // - int ptflags; - + /** * killough's code for thinkers seems to be totally broken in M.D, * this method is unused @@ -107,7 +102,7 @@ public UnifiedGameMap(DoomMain DOOM){ { /* Remove from current thread, if in one */ - /*if ((th = thinker.cnext) != null) { + /*if ((th = thinker.cnext) != null) { (th.cprev = thinker.cprev).cnext = th; } } @@ -121,15 +116,11 @@ public UnifiedGameMap(DoomMain DOOM){ } protected final thinker_t[] thinkerclasscap=new thinker_t[th_class.NUMTHCLASS];*/ - public boolean sight_debug; - - // // P_InitPicAnims // - /** * Floor/ceiling animation sequences, defined by first and last frame, i.e. * the flat (64x64 tile) name to be used. The full animation sequence is @@ -142,16 +133,13 @@ public UnifiedGameMap(DoomMain DOOM){ new animdef_t(false, "SWATER4", "SWATER1", 8), new animdef_t(false, "LAVA4", "LAVA1", 8), new animdef_t(false, "BLOOD3", "BLOOD1", 8), - // DOOM II flat animations. new animdef_t(false, "RROCK08", "RROCK05", 8), new animdef_t(false, "SLIME04", "SLIME01", 8), new animdef_t(false, "SLIME08", "SLIME05", 8), new animdef_t(false, "SLIME12", "SLIME09", 8), - new animdef_t(true, "BLODGR4", "BLODGR1", 8), new animdef_t(true, "SLADRIP3", "SLADRIP1", 8), - new animdef_t(true, "BLODRIP4", "BLODRIP1", 8), new animdef_t(true, "FIREWALL", "FIREWALA", 8), new animdef_t(true, "GSTFONT3", "GSTFONT1", 8), @@ -159,27 +147,26 @@ public UnifiedGameMap(DoomMain DOOM){ new animdef_t(true, "FIREMAG3", "FIREMAG1", 8), new animdef_t(true, "FIREBLU2", "FIREBLU1", 8), new animdef_t(true, "ROCKRED3", "ROCKRED1", 8), - new animdef_t(true, "BFALL4", "BFALL1", 8), new animdef_t(true, "SFALL4", "SFALL1", 8), new animdef_t(true, "WFALL4", "WFALL1", 8), new animdef_t(true, "DBRAIN4", "DBRAIN1", 8) }; - + // MAES: this was a cheap trick to mark the end of the sequence // with a value of "-1". // It won't work in Java, so just use animdefs.length-1 // new animdef_t(false, "", "", 0) }; - // // SPECIAL SPAWNING // public class Specials { + public static final int OK = 0, CRUSHED = 1, PASTDEST = 2; public line_t[] linespeciallist = new line_t[Limits.MAXLINEANIMS]; public short numlinespecials; - + /** * These are NOT the same anims found in defines. Dunno why they fucked up * this one so badly. Even the type has the same name, but is entirely @@ -198,9 +185,9 @@ public class Specials { public boolean levelTimer; public int levelTimeCount; - + private Specials() { - + } public void UpdateSpecials() { @@ -211,23 +198,24 @@ public void UpdateSpecials() { // LEVEL TIMER if (levelTimer == true) { levelTimeCount--; - if (levelTimeCount == 0) + if (levelTimeCount == 0) { DOOM.ExitLevel(); + } } // ANIMATE FLATS AND TEXTURES GLOBALLY - for (int j = 0; j < lastanim; j++) { anim = anims[j]; - + for (int i = anim.basepic; i < anim.basepic + anim.numpics; i++) { - pic = - anim.basepic - + ((DOOM.leveltime / anim.speed + i) % anim.numpics); - if (anim.istexture) - DOOM.textureManager.setTextureTranslation(i,pic); - else - DOOM.textureManager.setFlatTranslation(i,pic); + pic + = anim.basepic + + ((DOOM.leveltime / anim.speed + i) % anim.numpics); + if (anim.istexture) { + DOOM.textureManager.setTextureTranslation(i, pic); + } else { + DOOM.textureManager.setFlatTranslation(i, pic); + } } } @@ -235,10 +223,10 @@ public void UpdateSpecials() { for (int i = 0; i < numlinespecials; i++) { line = linespeciallist[i]; switch (line.special) { - case 48: - // EFFECT FIRSTCOL SCROLL + - DOOM.levelLoader.sides[line.sidenum[0]].textureoffset += MAPFRACUNIT; - break; + case 48: + // EFFECT FIRSTCOL SCROLL + + DOOM.levelLoader.sides[line.sidenum[0]].textureoffset += MAPFRACUNIT; + break; } } @@ -248,7 +236,7 @@ public void UpdateSpecials() { public void InitPicAnims() { Arrays.setAll(anims, i -> new anim_t()); - anim_t lstanim; + anim_t lstanim; // Init animation. MAES: sneaky base pointer conversion ;-) this.lastanim = 0; // MAES: for (i=0 ; animdefs[i].istexture != -1 ; i++) @@ -277,7 +265,7 @@ public void InitPicAnims() { if (lstanim.numpics < 2) { DOOM.doomSystem.Error("P_InitPicAnims: bad cycle from %s to %s", - animdefs[i].startname, animdefs[i].endname); + animdefs[i].startname, animdefs[i].endname); } lstanim.speed = animdefs[i].speed; @@ -288,16 +276,16 @@ public void InitPicAnims() { public final void resizeLinesSpecialList() { linespeciallist = C2JUtils.resize(linespeciallist[0], linespeciallist, linespeciallist.length * 2); } - + } public class Switches { - private Switches() { - switchlist= new int[MAXSWITCHES]; - initButtonList(); - } - + private Switches() { + switchlist = new int[MAXSWITCHES]; + initButtonList(); + } + public void doButtons() { for (final button_t buttonlist1 : buttonlist) { if (eval(buttonlist1.btimer)) { @@ -319,7 +307,7 @@ public void doButtons() { } } } - } + } // // CHANGE THE TEXTURE OF A WALL SWITCH TO ITS OPPOSITE @@ -345,7 +333,6 @@ public void doButtons() { new switchlist_t("SW1STON2", "SW2STON2", 1), new switchlist_t("SW1STONE", "SW2STONE", 1), new switchlist_t("SW1STRTN", "SW2STRTN", 1), - // Doom registered episodes 2&3 switches new switchlist_t("SW1BLUE", "SW2BLUE", 2), new switchlist_t("SW1CMT", "SW2CMT", 2), @@ -357,7 +344,6 @@ public void doButtons() { new switchlist_t("SW1SKIN", "SW2SKIN", 2), new switchlist_t("SW1VINE", "SW2VINE", 2), new switchlist_t("SW1WOOD", "SW2WOOD", 2), - // Doom II switches new switchlist_t("SW1PANEL", "SW2PANEL", 3), new switchlist_t("SW1ROCK", "SW2ROCK", 3), @@ -370,7 +356,6 @@ public void doButtons() { new switchlist_t("SW1TEK", "SW2TEK", 3), new switchlist_t("SW1MARB", "SW2MARB", 3), new switchlist_t("SW1SKULL", "SW2SKULL", 3), - new switchlist_t("\0", "\0", 0) }; @@ -378,7 +363,7 @@ public void doButtons() { int[] switchlist; int numswitches; button_t[] buttonlist; - + // // P_InitSwitchList // Only called at game initialization. @@ -399,14 +384,14 @@ public void InitSwitchList() { } for (index = 0, i = 0; i < MAXSWITCHES; i++) { - if (index>=switchlist.length) { - // Remove limit - switchlist = Arrays.copyOf(switchlist, switchlist.length > 0 ? switchlist.length * 2 : 8); + if (index >= switchlist.length) { + // Remove limit + switchlist = Arrays.copyOf(switchlist, switchlist.length > 0 ? switchlist.length * 2 : 8); } - - // Trickery. Looks for "end of list" marker - // Since the list has pairs of switches, the - // actual number of distinct switches is index/2 + + // Trickery. Looks for "end of list" marker + // Since the list has pairs of switches, the + // actual number of distinct switches is index/2 if (alphSwitchList[i].episode == 0) { numswitches = index / 2; switchlist[index] = -1; @@ -437,7 +422,7 @@ public final void StartButton(line_t line, bwhere_e w, int texture, int time) { return; } } - + // At this point, it may mean that THE button of that particular // line was not active, or simply that there were not enough // buttons in buttonlist to support an additional entry. @@ -452,7 +437,7 @@ public final void StartButton(line_t line, bwhere_e w, int texture, int time) { return; } } - + /** * Added config option to disable resize * - Good Sign 2017/04/26 @@ -480,8 +465,9 @@ public void ChangeSwitchTexture(line_t line, boolean useAgain) { int texBot; int sound; - if (!useAgain) + if (!useAgain) { line.special = 0; + } texTop = DOOM.levelLoader.sides[line.sidenum[0]].toptexture; texMid = DOOM.levelLoader.sides[line.sidenum[0]].midtexture; @@ -529,29 +515,25 @@ public void ChangeSwitchTexture(line_t line, boolean useAgain) { } } } - - public final void initButtonList() { - // Unlike plats, buttonlist needs statically allocated and reusable - // objects. The MAXBUTTONS limit actually applied to buttons PRESSED - // or ACTIVE at once, not how many there can actually be in a map. - + + public final void initButtonList() { + // Unlike plats, buttonlist needs statically allocated and reusable + // objects. The MAXBUTTONS limit actually applied to buttons PRESSED + // or ACTIVE at once, not how many there can actually be in a map. + buttonlist = malloc(button_t::new, button_t[]::new, MAXBUTTONS); } } - /* enum PTR { + /* enum PTR { SlideTraverse, AimTraverse, ShootTraverse, UseTraverse } */ - - /////////// BEGIN MAP OBJECT CODE, USE AS BASIC - // //////////////////////////////// THINKER CODE, GLOBALLY VISIBLE // ///////////////// - // // THINKERS // All thinkers should be allocated by Z_Malloc @@ -559,7 +541,6 @@ public final void initButtonList() { // The actual structures will vary in size, // but the first element must be thinker_t. // - /** Both the head and the tail of the thinkers list */ public thinker_t thinkercap; @@ -575,10 +556,9 @@ public final void initButtonList() { @SourceCode.Suspicious(CauseOfDesyncProbability.MEDIUM) @P_Tick.C(P_InitThinkers) public void InitThinkers() { - + /*for (int i=0; i{ - //@Override //public void accept(thinker_t thinker) { - - /* + /* try { System.err.printf("Delete: %s %d<= %s %d => %s %d\n", ((mobj_t)thinker.prev).type,((mobj_t)thinker.prev).thingnum, @@ -700,34 +673,30 @@ public thinker_t getThinkerCap() { } catch (ClassCastException e){ } */ - - // Unlike Boom, if we reach here it gets zapped anyway - //if (!thinker->references) - //{ - //{ /* Remove from main thinker list */ - //thinker_t next = thinker.next; - /* Note that currentthinker is guaranteed to point to us, + // Unlike Boom, if we reach here it gets zapped anyway + //if (!thinker->references) + //{ + //{ /* Remove from main thinker list */ + //thinker_t next = thinker.next; + /* Note that currentthinker is guaranteed to point to us, * and since we're freeing our memory, we had better change that. So * point it to thinker->prev, so the iterator will correctly move on to * thinker->prev->next = thinker->next */ - //(next.prev = currentthinker = thinker.prev).next = next; - //thinker.next=thinker.prev=null; - //try { - // System.err.printf("Delete: %s %d <==> %s %d\n", - // ((mobj_t)currentthinker.prev).type,((mobj_t)currentthinker.prev).thingnum, - // ((mobj_t)currentthinker.next).type,((mobj_t)currentthinker.next).thingnum); - //} catch (ClassCastException e){ - - //} - - //} - //{ - /* Remove from current thinker class list */ - //thinker_t th = thinker.cnext; - //(th.cprev = thinker.cprev).cnext = th; - //thinker.cnext=thinker.cprev=null; - //} - //} + //(next.prev = currentthinker = thinker.prev).next = next; + //thinker.next=thinker.prev=null; + //try { + // System.err.printf("Delete: %s %d <==> %s %d\n", + // ((mobj_t)currentthinker.prev).type,((mobj_t)currentthinker.prev).thingnum, + // ((mobj_t)currentthinker.next).type,((mobj_t)currentthinker.next).thingnum); + //} catch (ClassCastException e){ + //} + //} + //{ + /* Remove from current thinker class list */ + //thinker_t th = thinker.cnext; + //(th.cprev = thinker.cprev).cnext = th; + //thinker.cnext=thinker.cprev=null; + //} + //} //} - -} // End unified map \ No newline at end of file +} // End unified map diff --git a/src/p/anim_t.java b/src/p/anim_t.java index c400b6d6..106fa652 100644 --- a/src/p/anim_t.java +++ b/src/p/anim_t.java @@ -6,16 +6,13 @@ * @author admin * */ +public class anim_t { + public anim_t() { + } -public class anim_t { - - public anim_t(){ - - } - - public anim_t(boolean istexture, int picnum, int basepic, int numpics, + public anim_t(boolean istexture, int picnum, int basepic, int numpics, int speed) { super(); this.istexture = istexture; @@ -24,10 +21,10 @@ public anim_t(boolean istexture, int picnum, int basepic, int numpics, this.numpics = numpics; this.speed = speed; } - public boolean istexture; - public int picnum; - public int basepic; - public int numpics; - public int speed; - - } + public boolean istexture; + public int picnum; + public int basepic; + public int numpics; + public int speed; + +} diff --git a/src/p/animdef_t.java b/src/p/animdef_t.java index 53bfaba2..b65ca7af 100644 --- a/src/p/animdef_t.java +++ b/src/p/animdef_t.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; - import w.CacheableDoomObject; import w.DoomBuffer; @@ -29,7 +28,6 @@ public animdef_t(boolean istexture, String endname, String startname, this.speed = speed; } - /** if false, it is a flat, and will NOT be used as a texture. Unless you * use "flats on walls functionality of course. */ public boolean istexture; @@ -40,14 +38,13 @@ public animdef_t(boolean istexture, String endname, String startname, * counts the actual number of existing textures during initialization time. * */ - - public String endname,startname; + public String endname, startname; public int speed; public String toString() { return String.format("%s %s %s %d", istexture, startname, endname, - speed); + speed); } @Override diff --git a/src/p/button_t.java b/src/p/button_t.java index 7c60a750..1da91ece 100644 --- a/src/p/button_t.java +++ b/src/p/button_t.java @@ -3,27 +3,27 @@ import rr.line_t; import s.degenmobj_t; -public class button_t implements Resettable{ +public class button_t implements Resettable { - public line_t line; - public bwhere_e where; - public int btexture; - public int btimer; - public degenmobj_t soundorg; - - public button_t(){ - this.btexture=0; - this.btimer=0; - this.where=bwhere_e.top; - } - - public void reset(){ - this.line=null; - this.where=bwhere_e.top; - this.btexture=0; - this.btimer=0; - this.soundorg=null; - - } + public line_t line; + public bwhere_e where; + public int btexture; + public int btimer; + public degenmobj_t soundorg; - } \ No newline at end of file + public button_t() { + this.btexture = 0; + this.btimer = 0; + this.where = bwhere_e.top; + } + + public void reset() { + this.line = null; + this.where = bwhere_e.top; + this.btexture = 0; + this.btimer = 0; + this.soundorg = null; + + } + +} diff --git a/src/p/bwhere_e.java b/src/p/bwhere_e.java index 88ad1908..901e3b3b 100644 --- a/src/p/bwhere_e.java +++ b/src/p/bwhere_e.java @@ -1,7 +1,7 @@ package p; public enum bwhere_e { - top, - middle, - bottom - } \ No newline at end of file + top, + middle, + bottom +} diff --git a/src/p/ceiling_e.java b/src/p/ceiling_e.java index e686979d..a36eecfd 100644 --- a/src/p/ceiling_e.java +++ b/src/p/ceiling_e.java @@ -3,14 +3,13 @@ // // P_CEILNG // - public enum ceiling_e { - lowerToFloor, - raiseToHighest, - lowerAndCrush, - crushAndRaise, - fastCrushAndRaise, - silentCrushAndRaise; + lowerToFloor, + raiseToHighest, + lowerAndCrush, + crushAndRaise, + fastCrushAndRaise, + silentCrushAndRaise; - } +} diff --git a/src/p/ceiling_t.java b/src/p/ceiling_t.java index cbfef2f9..ee39e4ae 100644 --- a/src/p/ceiling_t.java +++ b/src/p/ceiling_t.java @@ -13,9 +13,12 @@ public class ceiling_t extends SectorAction implements CacheableDoomObject, IReadableDoomObject, IPackableDoomObject { public ceiling_e type; - @fixed_t public int bottomheight; - @fixed_t public int topheight; - @fixed_t public int speed; + @fixed_t + public int bottomheight; + @fixed_t + public int topheight; + @fixed_t + public int speed; public boolean crush; // 1 = up, 0 = waiting, -1 = down diff --git a/src/p/divline_t.java b/src/p/divline_t.java index b354be4b..4b7d6ba4 100644 --- a/src/p/divline_t.java +++ b/src/p/divline_t.java @@ -1,40 +1,33 @@ package p; -import static m.fixed_t.*; +import static m.fixed_t.FRACBITS; +import static m.fixed_t.FixedMul; import rr.line_t; import static utils.C2JUtils.eval; -// -// P_MAPUTL -// public class divline_t { /** fixed_t */ - public int x, y, dx, dy; - - - /** - *P_PointOnDivlineSide - *Returns 0 or 1. (false or true) - *@param x fixed - *@param y fixed - *@param divline_t - */ - public boolean - PointOnDivlineSide - ( int x, - int y - ) - { - - - // Using Killough's version. - return - (dx==0) ? x <= this.x ? dy > 0 : dy < 0 : - (dy==0) ? y <= this.y ? dx < 0 : dx > 0 : - (dy^dx^(x -= this.x)^(y -= this.y)) < 0 ? (dy^x) < 0 : - FixedMul(y>>8, this.dx>>8) >= FixedMul(this.dy>>8, x>>8); - /* + public int x, y, dx, dy; + + /** + *P_PointOnDivlineSide + *Returns 0 or 1. (false or true) + *@param x fixed + *@param y fixed + *@param divline_t + */ + public boolean + PointOnDivlineSide(int x, + int y + ) { + + // Using Killough's version. + return (dx == 0) ? x <= this.x ? dy > 0 : dy < 0 + : (dy == 0) ? y <= this.y ? dx < 0 : dx > 0 + : (dy ^ dx ^ (x -= this.x) ^ (y -= this.y)) < 0 ? (dy ^ x) < 0 + : FixedMul(y >> 8, this.dx >> 8) >= FixedMul(this.dy >> 8, x >> 8); + /* int PUREFUNC P_PointOnDivlineSide(fixed_t x, fixed_t y, const divline_t *line) { return @@ -43,8 +36,8 @@ int PUREFUNC P_PointOnDivlineSide(fixed_t x, fixed_t y, const divline_t *line) (line->dy^line->dx^(x -= line->x)^(y -= line->y)) < 0 ? (line->dy^x) < 0 : FixedMul(y>>8, line->dx>>8) >= FixedMul(line->dy>>8, x>>8); }*/ - - /* + + /* int dx; int dy; int left; @@ -82,61 +75,51 @@ int PUREFUNC P_PointOnDivlineSide(fixed_t x, fixed_t y, const divline_t *line) if (right < left) return false; // front side return true; // back side - */ - } - - - - // - //P_MakeDivline - // - public void - MakeDivline - ( line_t li) - { - this.x = li.v1x; - this.y = li.v1y; - this.dx = li.dx; - this.dy = li.dy; - } - - public divline_t(line_t li) - { - this.x = li.v1x; - this.y = li.v1y; - this.dx = li.dx; - this.dy = li.dy; - } - - public divline_t() { - // TODO Auto-generated constructor stub - } - - - - /** - * P_DivlineSide - * Returns side 0 (front), 1 (back), or 2 (on). - */ - public int - DivlineSide - ( int x, - int y) - { - - int left,right; - // Boom-style code. Da fack. - // [Maes:] it is MUCH more corrent than the linuxdoom one, for whatever reason. - - return - (this.dx==0) ? x == this.x ? 2 : x <= this.x ? eval(this.dy > 0) : eval(this.dy < 0) : - (this.dy==0) ? (olddemo ? x : y) == this.y ? 2 : y <= this.y ? eval(this.dx < 0) : eval(this.dx > 0) : - (this.dy==0) ? y == this.y ? 2 : y <= this.y ? eval(this.dx < 0) : eval(this.dx > 0) : - (right = ((y - this.y) >> FRACBITS) * (this.dx >> FRACBITS)) < - (left = ((x - this.x) >> FRACBITS) * (this.dy >> FRACBITS)) ? 0 : - right == left ? 2 : 1; - - /* + */ + } + + // + //P_MakeDivline + // + public void + MakeDivline(line_t li) { + this.x = li.v1x; + this.y = li.v1y; + this.dx = li.dx; + this.dy = li.dy; + } + + public divline_t(line_t li) { + this.x = li.v1x; + this.y = li.v1y; + this.dx = li.dx; + this.dy = li.dy; + } + + public divline_t() { + // TODO Auto-generated constructor stub + } + + /** + * P_DivlineSide + * Returns side 0 (front), 1 (back), or 2 (on). + */ + public int + DivlineSide(int x, + int y) { + + int left, right; + // Boom-style code. Da fack. + // [Maes:] it is MUCH more corrent than the linuxdoom one, for whatever reason. + + return (this.dx == 0) ? x == this.x ? 2 : x <= this.x ? eval(this.dy > 0) : eval(this.dy < 0) + : (this.dy == 0) ? (olddemo ? x : y) == this.y ? 2 : y <= this.y ? eval(this.dx < 0) : eval(this.dx > 0) + : (this.dy == 0) ? y == this.y ? 2 : y <= this.y ? eval(this.dx < 0) : eval(this.dx > 0) + : (right = ((y - this.y) >> FRACBITS) * (this.dx >> FRACBITS)) + < (left = ((x - this.x) >> FRACBITS) * (this.dy >> FRACBITS)) ? 0 + : right == left ? 2 : 1; + + /* int left,right,dx,dy; @@ -174,10 +157,9 @@ public divline_t() { if (left == right) return 2; return 1; // back side - */ - } - - private static final boolean olddemo = true; - - - } + */ + } + + private static final boolean olddemo = true; + +} diff --git a/src/p/floor_e.java b/src/p/floor_e.java index 2a90ecc3..d8cf5b9e 100644 --- a/src/p/floor_e.java +++ b/src/p/floor_e.java @@ -3,33 +3,25 @@ public enum floor_e { // lower floor to highest surrounding floor lowerFloor, - // lower floor to lowest surrounding floor lowerFloorToLowest, - // lower floor to highest surrounding floor VERY FAST turboLower, - // raise floor to lowest surrounding CEILING raiseFloor, - // raise floor to next highest surrounding floor raiseFloorToNearest, - // raise floor to shortest height texture around it raiseToTexture, - // lower floor to lowest surrounding floor // and change floorpic lowerAndChange, - raiseFloor24, raiseFloor24AndChange, raiseFloorCrush, - - // raise to next highest floor, turbo-speed - raiseFloorTurbo, + // raise to next highest floor, turbo-speed + raiseFloorTurbo, donutRaise, raiseFloor512 - + } diff --git a/src/p/floormove_t.java b/src/p/floormove_t.java index 9e66500d..83999715 100644 --- a/src/p/floormove_t.java +++ b/src/p/floormove_t.java @@ -3,49 +3,48 @@ import java.io.DataInputStream; import java.io.IOException; import java.nio.ByteBuffer; - import rr.SectorAction; import w.DoomIO; import w.IReadableDoomObject; -public class floormove_t extends SectorAction implements IReadableDoomObject{ - - public floormove_t(){ +public class floormove_t extends SectorAction implements IReadableDoomObject { + + public floormove_t() { // MAES HACK: floors are implied to be at least of "lowerFloor" type // unless set otherwise, due to implicit zero-enum value. - this.type=floor_e.lowerFloor; + this.type = floor_e.lowerFloor; } - + public floor_e type; public boolean crush; - public int direction; - public int newspecial; - public short texture; + public int direction; + public int newspecial; + public short texture; /** fixed_t */ public int floordestheight; /** fixed_t */ public int speed; @Override - public void read(DataInputStream f) throws IOException{ + public void read(DataInputStream f) throws IOException { super.read(f); // Call thinker reader first - type=floor_e.values()[DoomIO.readLEInt(f)]; - crush=DoomIO.readIntBoolean(f); - super.sectorid=DoomIO.readLEInt(f); // Sector index (or pointer?) - direction=DoomIO.readLEInt(f); - newspecial=DoomIO.readLEInt(f); - texture=DoomIO.readLEShort(f); - floordestheight=DoomIO.readLEInt(f); - speed=DoomIO.readLEInt(f); - } - + type = floor_e.values()[DoomIO.readLEInt(f)]; + crush = DoomIO.readIntBoolean(f); + super.sectorid = DoomIO.readLEInt(f); // Sector index (or pointer?) + direction = DoomIO.readLEInt(f); + newspecial = DoomIO.readLEInt(f); + texture = DoomIO.readLEShort(f); + floordestheight = DoomIO.readLEInt(f); + speed = DoomIO.readLEInt(f); + } + @Override - public void pack(ByteBuffer b) throws IOException{ + public void pack(ByteBuffer b) throws IOException { super.pack(b); //12 b.putInt(type.ordinal()); // 16 - b.putInt(crush?1:0); //20 + b.putInt(crush ? 1 : 0); //20 b.putInt(super.sectorid); // 24 b.putInt(direction); // 28 b.putInt(newspecial); // 32 @@ -53,5 +52,5 @@ public void pack(ByteBuffer b) throws IOException{ b.putInt(floordestheight); // 38 b.putInt(speed); // 42 } - -} \ No newline at end of file + +} diff --git a/src/p/intercept_t.java b/src/p/intercept_t.java index 868bcbc8..79a6cba2 100644 --- a/src/p/intercept_t.java +++ b/src/p/intercept_t.java @@ -15,7 +15,8 @@ public class intercept_t { /** * most intercepts will belong to a static pool */ - public intercept_t() {} + public intercept_t() { + } public intercept_t(int frac, mobj_t thing) { this.frac = frac; diff --git a/src/p/mobj_t.java b/src/p/mobj_t.java index 32ba3df3..0ef9c508 100644 --- a/src/p/mobj_t.java +++ b/src/p/mobj_t.java @@ -11,7 +11,7 @@ import data.sounds.sfxenum_t; import data.spritenum_t; import data.state_t; -import defines.*; +import defines.statenum_t; import doom.DoomMain; import doom.SourceCode.fixed_t; import doom.player_t; @@ -21,6 +21,9 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import p.ActiveStates.MobjConsumer; import static p.MapUtils.AproxDistance; import rr.subsector_t; @@ -84,498 +87,498 @@ * @author admin * */ - public class mobj_t extends thinker_t implements ISoundOrigin, Interceptable, - IWritableDoomObject, IPackableDoomObject, IReadableDoomObject { + IWritableDoomObject, IPackableDoomObject, IReadableDoomObject { + + private static final Logger LOGGER = Loggers.getLogger(mobj_t.class.getName()); + + public final ActionFunctions A; - public final ActionFunctions A; - public static mobj_t createOn(final DoomMain context) { if (eval(context.actions)) { return new mobj_t(context.actions); } - + return new mobj_t(); } - + private mobj_t() { - this.spawnpoint = new mapthing_t(); - this.A = null; + this.spawnpoint = new mapthing_t(); + this.A = null; } - private mobj_t(final ActionFunctions A) { - this.spawnpoint = new mapthing_t(); - this.A = A; - // A mobj_t is ALSO a thinker, as it always contains the struct. - // Don't fall for C's trickery ;-) - // this.thinker=new thinker_t(); - } - - /* List: thinker links. */ - // public thinker_t thinker; - - /** Info for drawing: position. */ - @fixed_t public int x, y, z; - - /** More list: links in sector (if needed) */ - public thinker_t snext, sprev; - - // More drawing info: to determine current sprite. - /** - * orientation. This needs to be long or else certain checks will fail...but - * I need to see it working in order to confirm - */ - public long angle; - - /** used to find patch_t and flip value */ - public spritenum_t mobj_sprite; - /** might be ORed with FF_FULLBRIGHT */ - public int mobj_frame; - - /** Interaction info, by BLOCKMAP. Links in blocks (if needed). */ - public thinker_t bnext, bprev; - - /** MAES: was actually a pointer to a struct subsector_s */ - public subsector_t subsector; - - /** The closest interval over all contacted Sectors. */ - @fixed_t public int floorz, ceilingz; - - /** For movement checking. */ - @fixed_t public int radius, height; - - /** Momentums, used to update position. */ - @fixed_t public int momx, momy, momz; - - /** If == validcount, already checked. */ - public int validcount; - - public mobjtype_t type; - // MAES: was a pointer - public mobjinfo_t info; // &mobjinfo[mobj.type] - - public long mobj_tics; // state tic counter - // MAES: was a pointer - public state_t mobj_state; - public long flags; - public int health; - - /** Movement direction, movement generation (zig-zagging). */ - public int movedir; // 0-7 - public int movecount; // when 0, select a new dir - - /** - * Thing being chased/attacked (or NULL), also the originator for missiles. - * MAES: was a pointer - */ - public mobj_t target; - public int p_target; // for savegames - - /** - * Reaction time: if non 0, don't attack yet. Used by player to freeze a bit - * after teleporting. - */ - public int reactiontime; - - /** - * If >0, the target will be chased no matter what (even if shot) - */ - public int threshold; - - /** - * Additional info record for player avatars only. Only valid if type == - * MT_PLAYER struct player_s* player; - */ - - public player_t player; - - /** Player number last looked for. */ - public int lastlook; - - /** For nightmare respawn. */ - public mapthing_t spawnpoint; // struct - - /** Thing being chased/attacked for tracers. */ - - public mobj_t tracer; // MAES: was a pointer - - // // MF_ flags for mobjs. - - // Call P_SpecialThing when touched. - public static final int MF_SPECIAL = 1; - // Blocks. - public static final int MF_SOLID = 2; - // Can be hit. - public static final int MF_SHOOTABLE = 4; - // Don't use the sector links (invisible but touchable). - public static final int MF_NOSECTOR = 8; - // Don't use the blocklinks (inert but displayable) - public static final int MF_NOBLOCKMAP = 16; - - // Not to be activated by sound, deaf monster. - public static final int MF_AMBUSH = 32; - // Will try to attack right back. - public static final int MF_JUSTHIT = 64; - // Will take at least one step before attacking. - public static final int MF_JUSTATTACKED = 128; - // On level spawning (initial position), - // hang from ceiling instead of stand on floor. - public static final int MF_SPAWNCEILING = 256; - // Don't apply gravity (every tic), - // that is, object will float, keeping current height - // or changing it actively. - public static final int MF_NOGRAVITY = 512; - - // Movement flags. - // This allows jumps from high places. - public static final int MF_DROPOFF = 0x400; - // For players, will pick up items. - public static final int MF_PICKUP = 0x800; - // Player cheat. ??? - public static final int MF_NOCLIP = 0x1000; - // Player: keep info about sliding along walls. - public static final int MF_SLIDE = 0x2000; - // Allow moves to any height, no gravity. - // For active floaters, e.g. cacodemons, pain elementals. - public static final int MF_FLOAT = 0x4000; - // Don't cross lines - // ??? or look at heights on teleport. - public static final int MF_TELEPORT = 0x8000; - // Don't hit same species, explode on block. - // Player missiles as well as fireballs of various kinds. - public static final int MF_MISSILE = 0x10000; - // Dropped by a demon, not level spawned. - // E.g. ammo clips dropped by dying former humans. - public static final int MF_DROPPED = 0x20000; - // Use fuzzy draw (shadow demons or spectres), - // temporary player invisibility powerup. - public static final int MF_SHADOW = 0x40000; - // Flag: don't bleed when shot (use puff), - // barrels and shootable furniture shall not bleed. - public static final int MF_NOBLOOD = 0x80000; - // Don't stop moving halfway off a step, - // that is, have dead bodies slide down all the way. - public static final int MF_CORPSE = 0x100000; - // Floating to a height for a move, ??? - // don't auto float to target's height. - public static final int MF_INFLOAT = 0x200000; - - // On kill, count this enemy object - // towards intermission kill total. - // Happy gathering. - public static final int MF_COUNTKILL = 0x400000; - - // On picking up, count this item object - // towards intermission item total. - public static final int MF_COUNTITEM = 0x800000; - - // Special handling: skull in flight. - // Neither a cacodemon nor a missile. - public static final int MF_SKULLFLY = 0x1000000; - - // Don't spawn this object - // in death match mode (e.g. key cards). - public static final int MF_NOTDMATCH = 0x2000000; - - // Player sprites in multiplayer modes are modified - // using an internal color lookup table for re-indexing. - // If 0x4 0x8 or 0xc, - // use a translation table for player colormaps - public static final int MF_TRANSLATION = 0xc000000; - // Hmm ???. - public static final int MF_TRANSSHIFT = 26; - - /* + private mobj_t(final ActionFunctions A) { + this.spawnpoint = new mapthing_t(); + this.A = A; + // A mobj_t is ALSO a thinker, as it always contains the struct. + // Don't fall for C's trickery ;-) + // this.thinker=new thinker_t(); + } + + /* List: thinker links. */ + // public thinker_t thinker; + /** Info for drawing: position. */ + @fixed_t + public int x, y, z; + + /** More list: links in sector (if needed) */ + public thinker_t snext, sprev; + + // More drawing info: to determine current sprite. + /** + * orientation. This needs to be long or else certain checks will fail...but + * I need to see it working in order to confirm + */ + public long angle; + + /** used to find patch_t and flip value */ + public spritenum_t mobj_sprite; + /** might be ORed with FF_FULLBRIGHT */ + public int mobj_frame; + + /** Interaction info, by BLOCKMAP. Links in blocks (if needed). */ + public thinker_t bnext, bprev; + + /** MAES: was actually a pointer to a struct subsector_s */ + public subsector_t subsector; + + /** The closest interval over all contacted Sectors. */ + @fixed_t + public int floorz, ceilingz; + + /** For movement checking. */ + @fixed_t + public int radius, height; + + /** Momentums, used to update position. */ + @fixed_t + public int momx, momy, momz; + + /** If == validcount, already checked. */ + public int validcount; + + public mobjtype_t type; + // MAES: was a pointer + public mobjinfo_t info; // &mobjinfo[mobj.type] + + public long mobj_tics; // state tic counter + // MAES: was a pointer + public state_t mobj_state; + public long flags; + public int health; + + /** Movement direction, movement generation (zig-zagging). */ + public int movedir; // 0-7 + public int movecount; // when 0, select a new dir + + /** + * Thing being chased/attacked (or NULL), also the originator for missiles. + * MAES: was a pointer + */ + public mobj_t target; + public int p_target; // for savegames + + /** + * Reaction time: if non 0, don't attack yet. Used by player to freeze a bit + * after teleporting. + */ + public int reactiontime; + + /** + * If >0, the target will be chased no matter what (even if shot) + */ + public int threshold; + + /** + * Additional info record for player avatars only. Only valid if type == + * MT_PLAYER struct player_s* player; + */ + public player_t player; + + /** Player number last looked for. */ + public int lastlook; + + /** For nightmare respawn. */ + public mapthing_t spawnpoint; // struct + + /** Thing being chased/attacked for tracers. */ + public mobj_t tracer; // MAES: was a pointer + + // // MF_ flags for mobjs. + // Call P_SpecialThing when touched. + public static final int MF_SPECIAL = 1; + // Blocks. + public static final int MF_SOLID = 2; + // Can be hit. + public static final int MF_SHOOTABLE = 4; + // Don't use the sector links (invisible but touchable). + public static final int MF_NOSECTOR = 8; + // Don't use the blocklinks (inert but displayable) + public static final int MF_NOBLOCKMAP = 16; + + // Not to be activated by sound, deaf monster. + public static final int MF_AMBUSH = 32; + // Will try to attack right back. + public static final int MF_JUSTHIT = 64; + // Will take at least one step before attacking. + public static final int MF_JUSTATTACKED = 128; + // On level spawning (initial position), + // hang from ceiling instead of stand on floor. + public static final int MF_SPAWNCEILING = 256; + // Don't apply gravity (every tic), + // that is, object will float, keeping current height + // or changing it actively. + public static final int MF_NOGRAVITY = 512; + + // Movement flags. + // This allows jumps from high places. + public static final int MF_DROPOFF = 0x400; + // For players, will pick up items. + public static final int MF_PICKUP = 0x800; + // Player cheat. ??? + public static final int MF_NOCLIP = 0x1000; + // Player: keep info about sliding along walls. + public static final int MF_SLIDE = 0x2000; + // Allow moves to any height, no gravity. + // For active floaters, e.g. cacodemons, pain elementals. + public static final int MF_FLOAT = 0x4000; + // Don't cross lines + // ??? or look at heights on teleport. + public static final int MF_TELEPORT = 0x8000; + // Don't hit same species, explode on block. + // Player missiles as well as fireballs of various kinds. + public static final int MF_MISSILE = 0x10000; + // Dropped by a demon, not level spawned. + // E.g. ammo clips dropped by dying former humans. + public static final int MF_DROPPED = 0x20000; + // Use fuzzy draw (shadow demons or spectres), + // temporary player invisibility powerup. + public static final int MF_SHADOW = 0x40000; + // Flag: don't bleed when shot (use puff), + // barrels and shootable furniture shall not bleed. + public static final int MF_NOBLOOD = 0x80000; + // Don't stop moving halfway off a step, + // that is, have dead bodies slide down all the way. + public static final int MF_CORPSE = 0x100000; + // Floating to a height for a move, ??? + // don't auto float to target's height. + public static final int MF_INFLOAT = 0x200000; + + // On kill, count this enemy object + // towards intermission kill total. + // Happy gathering. + public static final int MF_COUNTKILL = 0x400000; + + // On picking up, count this item object + // towards intermission item total. + public static final int MF_COUNTITEM = 0x800000; + + // Special handling: skull in flight. + // Neither a cacodemon nor a missile. + public static final int MF_SKULLFLY = 0x1000000; + + // Don't spawn this object + // in death match mode (e.g. key cards). + public static final int MF_NOTDMATCH = 0x2000000; + + // Player sprites in multiplayer modes are modified + // using an internal color lookup table for re-indexing. + // If 0x4 0x8 or 0xc, + // use a translation table for player colormaps + public static final int MF_TRANSLATION = 0xc000000; + // Hmm ???. + public static final int MF_TRANSSHIFT = 26; + + /* * The following methods were for the most part "contextless" and * instance-specific, so they were implemented here rather that being * scattered all over the package. - */ - - /** - * P_SetMobjState Returns true if the mobj is still present. - */ + */ + /** + * P_SetMobjState Returns true if the mobj is still present. + */ + public boolean SetMobjState(statenum_t state) { + state_t st; + + do { + if (state == statenum_t.S_NULL) { + mobj_state = null; + // MAES/_D_: uncommented this as it should work by now (?). + A.RemoveMobj(this); + return false; + } - public boolean SetMobjState(statenum_t state) { - state_t st; + st = states[state.ordinal()]; + mobj_state = st; + mobj_tics = st.tics; + mobj_sprite = st.sprite; + mobj_frame = st.frame; - do { - if (state == statenum_t.S_NULL) { - mobj_state = null; - // MAES/_D_: uncommented this as it should work by now (?). - A.RemoveMobj(this); - return false; - } - - st = states[state.ordinal()]; - mobj_state = st; - mobj_tics = st.tics; - mobj_sprite = st.sprite; - mobj_frame = st.frame; - - // Modified handling. - // Call action functions when the state is set + // Modified handling. + // Call action functions when the state is set // TODO: try find a bug if (st.action.isParamType(MobjConsumer.class)) { st.action.fun(MobjConsumer.class).accept(A, this); } - state = st.nextstate; - } while (!eval(mobj_tics)); - - return true; - } - - /** - * P_ZMovement - */ - - public void ZMovement() { - @fixed_t int dist, delta; - - // check for smooth step up - if ((player != null) && z < floorz) { - player.viewheight -= floorz - z; - - player.deltaviewheight = (VIEWHEIGHT - player.viewheight) >> 3; - } - - // adjust height - z += momz; - - if (((flags & MF_FLOAT) != 0) && target != null) { - // float down towards target if too close - if ((flags & MF_SKULLFLY) == 0 && (flags & MF_INFLOAT) == 0) { - dist = AproxDistance(x - target.x, y - target.y); - - delta = (target.z + (height >> 1)) - z; - - if (delta < 0 && dist < -(delta * 3)) - z -= FLOATSPEED; - else if (delta > 0 && dist < (delta * 3)) - z += FLOATSPEED; - } - - } - - // clip movement - if (z <= floorz) { - // hit the floor - - // Note (id): - // somebody left this after the setting momz to 0, - // kinda useless there. - if ((flags & MF_SKULLFLY) != 0) { - // the skull slammed into something - momz = -momz; - } - - if (momz < 0) { - if (player != null && (momz < -GRAVITY * 8)) { - // Squat down. - // Decrease viewheight for a moment - // after hitting the ground (hard), - // and utter appropriate sound. - player.deltaviewheight = momz >> 3; - A.DOOM.doomSound.StartSound(this, sfxenum_t.sfx_oof); - } - momz = 0; - } - z = floorz; - - if ((flags & MF_MISSILE) != 0 && (flags & MF_NOCLIP) == 0) { - A.ExplodeMissile(this); - return; - } - } else if ((flags & MF_NOGRAVITY) == 0) { - if (momz == 0) - momz = -GRAVITY * 2; - else - momz -= GRAVITY; - } - - if (z + height > ceilingz) { - // hit the ceiling - if (momz > 0) - momz = 0; - { - z = ceilingz - height; - } - - if ((flags & MF_SKULLFLY) != 0) { // the skull slammed into - // something - momz = -momz; - } - - if ((flags & MF_MISSILE) != 0 && (flags & MF_NOCLIP) == 0) { - A.ExplodeMissile(this); - } - } - } - - public int eflags; // DOOM LEGACY - - // Fields used only during DSG unmarshalling - public int stateid; - public int playerid; - public int p_tracer; - - /** Unique thing id, used during sync debugging */ + state = st.nextstate; + } while (!eval(mobj_tics)); + + return true; + } + + /** + * P_ZMovement + */ + public void ZMovement() { + @fixed_t + int dist, delta; + + // check for smooth step up + if ((player != null) && z < floorz) { + player.viewheight -= floorz - z; + + player.deltaviewheight = (VIEWHEIGHT - player.viewheight) >> 3; + } + + // adjust height + z += momz; + + if (((flags & MF_FLOAT) != 0) && target != null) { + // float down towards target if too close + if ((flags & MF_SKULLFLY) == 0 && (flags & MF_INFLOAT) == 0) { + dist = AproxDistance(x - target.x, y - target.y); + + delta = (target.z + (height >> 1)) - z; + + if (delta < 0 && dist < -(delta * 3)) { + z -= FLOATSPEED; + } else if (delta > 0 && dist < (delta * 3)) { + z += FLOATSPEED; + } + } + + } + + // clip movement + if (z <= floorz) { + // hit the floor + + // Note (id): + // somebody left this after the setting momz to 0, + // kinda useless there. + if ((flags & MF_SKULLFLY) != 0) { + // the skull slammed into something + momz = -momz; + } + + if (momz < 0) { + if (player != null && (momz < -GRAVITY * 8)) { + // Squat down. + // Decrease viewheight for a moment + // after hitting the ground (hard), + // and utter appropriate sound. + player.deltaviewheight = momz >> 3; + A.DOOM.doomSound.StartSound(this, sfxenum_t.sfx_oof); + } + momz = 0; + } + z = floorz; + + if ((flags & MF_MISSILE) != 0 && (flags & MF_NOCLIP) == 0) { + A.ExplodeMissile(this); + return; + } + } else if ((flags & MF_NOGRAVITY) == 0) { + if (momz == 0) { + momz = -GRAVITY * 2; + } else { + momz -= GRAVITY; + } + } + + if (z + height > ceilingz) { + // hit the ceiling + if (momz > 0) { + momz = 0; + } + { + z = ceilingz - height; + } + + if ((flags & MF_SKULLFLY) != 0) { // the skull slammed into + // something + momz = -momz; + } + + if ((flags & MF_MISSILE) != 0 && (flags & MF_NOCLIP) == 0) { + A.ExplodeMissile(this); + } + } + } + + public int eflags; // DOOM LEGACY + + // Fields used only during DSG unmarshalling + public int stateid; + public int playerid; + public int p_tracer; + + /** Unique thing id, used during sync debugging */ public int thingnum; - public void clear() { - fastclear.rewind(); - try { - this.unpack(mobj_t.fastclear); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - // _D_: to permit this object to save/load + public void clear() { + fastclear.rewind(); + try { + this.unpack(mobj_t.fastclear); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, "clear failure", e); + } + } + + // _D_: to permit this object to save/load @Override - public void read(DataInputStream f) throws IOException { - // More efficient, avoids duplicating code and - // handles little endian better. - buffer.position(0); - buffer.order(ByteOrder.LITTLE_ENDIAN); - f.read(buffer.array()); - this.unpack(buffer); - } - - @Override - public void write(DataOutputStream f) throws IOException { - - // More efficient, avoids duplicating code and - // handles little endian better. - buffer.position(0); - buffer.order(ByteOrder.LITTLE_ENDIAN); - this.pack(buffer); - f.write(buffer.array()); - - } + public void read(DataInputStream f) throws IOException { + // More efficient, avoids duplicating code and + // handles little endian better. + buffer.position(0); + buffer.order(ByteOrder.LITTLE_ENDIAN); + f.read(buffer.array()); + this.unpack(buffer); + } @Override - public void pack(ByteBuffer b) throws IOException { - b.order(ByteOrder.LITTLE_ENDIAN); - super.pack(b); // Pack the head thinker. - b.putInt(x); - b.putInt(y); - b.putInt(z); - b.putInt(pointer(snext)); - b.putInt(pointer(sprev)); - b.putInt((int) (this.angle & Tables.BITS32)); - b.putInt(this.mobj_sprite.ordinal()); - b.putInt(this.mobj_frame); - b.putInt(pointer(bnext)); - b.putInt(pointer(bprev)); - b.putInt(pointer(subsector)); - b.putInt(floorz); - b.putInt(ceilingz); - b.putInt(radius); - b.putInt(height); - b.putInt(momx); - b.putInt(momy); - b.putInt(momz); - b.putInt(validcount); - b.putInt(type.ordinal()); - b.putInt(pointer(info)); // TODO: mobjinfo - b.putInt((int) (this.mobj_tics & Tables.BITS32)); - b.putInt(this.mobj_state.id); // TODO: state OK? - b.putInt((int) this.flags); // truncate - b.putInt(this.health); - b.putInt(this.movedir); - b.putInt(this.movecount); - b.putInt(pointer(target)); // TODO: p_target? - b.putInt(this.reactiontime); - b.putInt(this.threshold); - // Check for player. - if (this.player != null) { - b.putInt(1 + this.player.identify()); - - // System.out.printf("Mobj with hashcode %d is player %d",pointer(this),1+this.player.identify()); - } else - b.putInt(0); - b.putInt(lastlook); - spawnpoint.pack(b); - b.putInt(pointer(tracer)); // tracer pointer stored. - - } + public void write(DataOutputStream f) throws IOException { + + // More efficient, avoids duplicating code and + // handles little endian better. + buffer.position(0); + buffer.order(ByteOrder.LITTLE_ENDIAN); + this.pack(buffer); + f.write(buffer.array()); + + } @Override - public void unpack(ByteBuffer b) throws IOException { - b.order(ByteOrder.LITTLE_ENDIAN); - super.unpack(b); // 12 Read the head thinker. - this.x = b.getInt(); // 16 - this.y = b.getInt(); // 20 - this.z = b.getInt(); // 24 - b.getLong(); // TODO: snext, sprev. When are those set? 32 - this.angle = Tables.BITS32 & b.getInt(); // 36 - this.mobj_sprite = spritenum_t.values()[b.getInt()]; // 40 - this.mobj_frame = b.getInt(); // 44 - b.getLong(); // TODO: bnext, bprev. When are those set? 52 - b.getInt(); // TODO: subsector 56 - this.floorz = b.getInt(); // 60 - this.ceilingz = b.getInt(); // 64 - this.radius = b.getInt(); // 68 - this.height = b.getInt(); // 72 - this.momx = b.getInt(); // 76 - this.momy = b.getInt(); // 80 - this.momz = b.getInt(); // 84 - this.validcount = b.getInt(); // 88 - this.type = mobjtype_t.values()[b.getInt()]; // 92 - b.getInt(); // TODO: mobjinfo (deduced from type) //96 - this.mobj_tics = Tables.BITS32 & b.getInt(); // 100 - // System.out.println("State"+f.readLEInt()); - this.stateid = b.getInt(); // TODO: state OK? - this.flags = b.getInt()&Tables.BITS32; // Only 32-bit flags can be restored - this.health = b.getInt(); - this.movedir = b.getInt(); - this.movecount = b.getInt(); - this.p_target = b.getInt(); - this.reactiontime = b.getInt(); - this.threshold = b.getInt(); - this.playerid = b.getInt(); // TODO: player. Non null should mean that - // it IS a player. - this.lastlook = b.getInt(); - spawnpoint.unpack(b); - this.p_tracer = b.getInt(); // TODO: tracer - } - - private static ByteBuffer buffer = ByteBuffer.allocate(154); - private static ByteBuffer fastclear = ByteBuffer.allocate(154); - - /* + public void pack(ByteBuffer b) throws IOException { + b.order(ByteOrder.LITTLE_ENDIAN); + super.pack(b); // Pack the head thinker. + b.putInt(x); + b.putInt(y); + b.putInt(z); + b.putInt(pointer(snext)); + b.putInt(pointer(sprev)); + b.putInt((int) (this.angle & Tables.BITS32)); + b.putInt(this.mobj_sprite.ordinal()); + b.putInt(this.mobj_frame); + b.putInt(pointer(bnext)); + b.putInt(pointer(bprev)); + b.putInt(pointer(subsector)); + b.putInt(floorz); + b.putInt(ceilingz); + b.putInt(radius); + b.putInt(height); + b.putInt(momx); + b.putInt(momy); + b.putInt(momz); + b.putInt(validcount); + b.putInt(type.ordinal()); + b.putInt(pointer(info)); // TODO: mobjinfo + b.putInt((int) (this.mobj_tics & Tables.BITS32)); + b.putInt(this.mobj_state.id); // TODO: state OK? + b.putInt((int) this.flags); // truncate + b.putInt(this.health); + b.putInt(this.movedir); + b.putInt(this.movecount); + b.putInt(pointer(target)); // TODO: p_target? + b.putInt(this.reactiontime); + b.putInt(this.threshold); + // Check for player. + if (this.player != null) { + b.putInt(1 + this.player.identify()); + + // System.out.printf("Mobj with hashcode %d is player %d",pointer(this),1+this.player.identify()); + } else { + b.putInt(0); + } + b.putInt(lastlook); + spawnpoint.pack(b); + b.putInt(pointer(tracer)); // tracer pointer stored. + + } + + @Override + public void unpack(ByteBuffer b) throws IOException { + b.order(ByteOrder.LITTLE_ENDIAN); + super.unpack(b); // 12 Read the head thinker. + this.x = b.getInt(); // 16 + this.y = b.getInt(); // 20 + this.z = b.getInt(); // 24 + b.getLong(); // TODO: snext, sprev. When are those set? 32 + this.angle = Tables.BITS32 & b.getInt(); // 36 + this.mobj_sprite = spritenum_t.values()[b.getInt()]; // 40 + this.mobj_frame = b.getInt(); // 44 + b.getLong(); // TODO: bnext, bprev. When are those set? 52 + b.getInt(); // TODO: subsector 56 + this.floorz = b.getInt(); // 60 + this.ceilingz = b.getInt(); // 64 + this.radius = b.getInt(); // 68 + this.height = b.getInt(); // 72 + this.momx = b.getInt(); // 76 + this.momy = b.getInt(); // 80 + this.momz = b.getInt(); // 84 + this.validcount = b.getInt(); // 88 + this.type = mobjtype_t.values()[b.getInt()]; // 92 + b.getInt(); // TODO: mobjinfo (deduced from type) //96 + this.mobj_tics = Tables.BITS32 & b.getInt(); // 100 + // System.out.println("State"+f.readLEInt()); + this.stateid = b.getInt(); // TODO: state OK? + this.flags = b.getInt() & Tables.BITS32; // Only 32-bit flags can be restored + this.health = b.getInt(); + this.movedir = b.getInt(); + this.movecount = b.getInt(); + this.p_target = b.getInt(); + this.reactiontime = b.getInt(); + this.threshold = b.getInt(); + this.playerid = b.getInt(); // TODO: player. Non null should mean that + // it IS a player. + this.lastlook = b.getInt(); + spawnpoint.unpack(b); + this.p_tracer = b.getInt(); // TODO: tracer + } + + private static ByteBuffer buffer = ByteBuffer.allocate(154); + private static ByteBuffer fastclear = ByteBuffer.allocate(154); + + /* * @Override protected void finalize(){ count++; if (count%100==0) * System.err * .printf("Total %d Mobj %s@%d finalized free memory: %d\n",count, * this.type.name(),this.hashCode(),Runtime.getRuntime().freeMemory()); } - */ - protected static int count = 0; - - // TODO: a linked list of sectors where this object appears - // public msecnode_t touching_sectorlist; - - // Sound origin stuff - - @Override - public final int getX() { - return x; - } - - @Override - public final int getY() { - return y; - } - - @Override - public final int getZ() { - return z; - } - + */ + protected static int count = 0; + + // TODO: a linked list of sectors where this object appears + // public msecnode_t touching_sectorlist; + // Sound origin stuff @Override - public String toString(){ - return String.format("%s %d",this.type,this.thingnum); - } + public final int getX() { + return x; + } + + @Override + public final int getY() { + return y; + } + + @Override + public final int getZ() { + return z; + } + + @Override + public String toString() { + return String.format("%s %d", this.type, this.thingnum); + } } diff --git a/src/p/plat_e.java b/src/p/plat_e.java index c36ecc8d..5ffa9861 100644 --- a/src/p/plat_e.java +++ b/src/p/plat_e.java @@ -3,10 +3,9 @@ // // P_PLATS // - public enum plat_e { - up, - down, - waiting, - in_stasis - } + up, + down, + waiting, + in_stasis +} diff --git a/src/p/plat_t.java b/src/p/plat_t.java index f998f28b..c0dcdffb 100644 --- a/src/p/plat_t.java +++ b/src/p/plat_t.java @@ -12,7 +12,8 @@ public class plat_t extends SectorAction implements IReadableDoomObject { public sector_t sector; - public @fixed_t int speed, low, high; + public @fixed_t + int speed, low, high; public int wait; public int count; public plat_e status; @@ -40,8 +41,8 @@ public void read(DataInputStream f) throws IOException { count = DoomIO.readLEInt(f); status = plat_e.values()[DoomIO.readLEInt(f)]; oldstatus = plat_e.values()[DoomIO.readLEInt(f)]; - System.out.println(status); - System.out.println(oldstatus); + //System.out.println(status); + //System.out.println(oldstatus); crush = DoomIO.readIntBoolean(f); tag = DoomIO.readLEInt(f); type = plattype_e.values()[DoomIO.readLEInt(f)]; @@ -58,8 +59,8 @@ public void pack(ByteBuffer b) throws IOException { b.putInt(count); //36 b.putInt(status.ordinal()); //40 b.putInt(oldstatus.ordinal()); //44 - System.out.println(status); - System.out.println(oldstatus); + //System.out.println(status); + //System.out.println(oldstatus); b.putInt(crush ? 1 : 0); // 48 b.putInt(tag); // 52 b.putInt(type.ordinal()); // 56 diff --git a/src/p/plattype_e.java b/src/p/plattype_e.java index 0b3e510c..1c3a3e50 100644 --- a/src/p/plattype_e.java +++ b/src/p/plattype_e.java @@ -1,10 +1,10 @@ package p; public enum plattype_e { - perpetualRaise, - downWaitUpStay, - raiseAndChange, - raiseToNearestAndChange, - blazeDWUS + perpetualRaise, + downWaitUpStay, + raiseAndChange, + raiseToNearestAndChange, + blazeDWUS - } \ No newline at end of file +} diff --git a/src/p/pspdef_t.java b/src/p/pspdef_t.java index 5777f439..81ce85da 100644 --- a/src/p/pspdef_t.java +++ b/src/p/pspdef_t.java @@ -1,41 +1,43 @@ package p; +import data.state_t; import java.io.DataInputStream; import java.io.IOException; import java.nio.ByteBuffer; - import w.DoomIO; import w.IPackableDoomObject; import w.IReadableDoomObject; -import data.state_t; -public class pspdef_t implements IReadableDoomObject,IPackableDoomObject{ +public class pspdef_t implements IReadableDoomObject, IPackableDoomObject { - public pspdef_t(){ - state=new state_t(); + public pspdef_t() { + state = new state_t(); } /** a NULL state means not active */ - public state_t state; - public int tics; + public state_t state; + public int tics; /** fixed_t */ - public int sx, sy; + public int sx, sy; // When read from disk. public int readstate; - + @Override public void read(DataInputStream f) throws IOException { //state=data.info.states[f.readLEInt()]; - readstate=DoomIO.readLEInt(f); - tics=DoomIO.readLEInt(f); - sx=DoomIO.readLEInt(f); - sy=DoomIO.readLEInt(f); + readstate = DoomIO.readLEInt(f); + tics = DoomIO.readLEInt(f); + sx = DoomIO.readLEInt(f); + sy = DoomIO.readLEInt(f); } - + @Override public void pack(ByteBuffer f) throws IOException { - if (state==null) f.putInt(0); - else f.putInt(state.id); + if (state == null) { + f.putInt(0); + } else { + f.putInt(state.id); + } f.putInt(tics); f.putInt(sx); f.putInt(sy); diff --git a/src/p/result_e.java b/src/p/result_e.java index 802d62df..7c3e6ceb 100644 --- a/src/p/result_e.java +++ b/src/p/result_e.java @@ -1,7 +1,7 @@ package p; public enum result_e { - ok, - crushed, - pastdest + ok, + crushed, + pastdest } diff --git a/src/p/sd_e.java b/src/p/sd_e.java index fbb8970f..2addc4a9 100644 --- a/src/p/sd_e.java +++ b/src/p/sd_e.java @@ -1,7 +1,7 @@ package p; public enum sd_e { - sd_opening, - sd_waiting, - sd_closing - } \ No newline at end of file + sd_opening, + sd_waiting, + sd_closing +} diff --git a/src/p/sdt_e.java b/src/p/sdt_e.java index 0122e1db..95282eda 100644 --- a/src/p/sdt_e.java +++ b/src/p/sdt_e.java @@ -1,7 +1,7 @@ package p; public enum sdt_e { - sdt_openOnly, - sdt_closeOnly, - sdt_openAndClose - } \ No newline at end of file + sdt_openOnly, + sdt_closeOnly, + sdt_openAndClose +} diff --git a/src/p/slidedoor_t.java b/src/p/slidedoor_t.java index f2c76c75..027bb891 100644 --- a/src/p/slidedoor_t.java +++ b/src/p/slidedoor_t.java @@ -6,6 +6,7 @@ import rr.sector_t; public class slidedoor_t extends SectorAction { + public sdt_e type; public line_t line; public int frame; diff --git a/src/p/slideframe_t.java b/src/p/slideframe_t.java index 5ea2ce4c..6d895361 100644 --- a/src/p/slideframe_t.java +++ b/src/p/slideframe_t.java @@ -1,6 +1,7 @@ package p; public class slideframe_t { - public int[] frontFrames = new int[4]; - public int[] backFrames = new int[4]; -} \ No newline at end of file + + public int[] frontFrames = new int[4]; + public int[] backFrames = new int[4]; +} diff --git a/src/p/slidename_t.java b/src/p/slidename_t.java index 5add2022..2d9000fe 100644 --- a/src/p/slidename_t.java +++ b/src/p/slidename_t.java @@ -2,30 +2,30 @@ public class slidename_t { - public slidename_t() { + public slidename_t() { - } + } - public slidename_t(String frontFrame1, String frontFrame2, - String frontFrame3, String frontFrame4, String backFrame1, - String backFrame2, String backFrame3, String backFrame4) { - this.frontFrame1 = frontFrame1; - this.frontFrame2 = frontFrame2; - this.frontFrame3 = frontFrame3; - this.frontFrame4 = frontFrame4; - this.backFrame1 = backFrame1; - this.backFrame2 = backFrame2; - this.backFrame3 = backFrame3; - this.backFrame4 = backFrame4; - } + public slidename_t(String frontFrame1, String frontFrame2, + String frontFrame3, String frontFrame4, String backFrame1, + String backFrame2, String backFrame3, String backFrame4) { + this.frontFrame1 = frontFrame1; + this.frontFrame2 = frontFrame2; + this.frontFrame3 = frontFrame3; + this.frontFrame4 = frontFrame4; + this.backFrame1 = backFrame1; + this.backFrame2 = backFrame2; + this.backFrame3 = backFrame3; + this.backFrame4 = backFrame4; + } - public String frontFrame1; - public String frontFrame2; - public String frontFrame3; - public String frontFrame4; - public String backFrame1; - public String backFrame2; - public String backFrame3; - public String backFrame4; + public String frontFrame1; + public String frontFrame2; + public String frontFrame3; + public String frontFrame4; + public String backFrame1; + public String backFrame2; + public String backFrame3; + public String backFrame4; -} \ No newline at end of file +} diff --git a/src/p/stair_e.java b/src/p/stair_e.java index 4c0172e8..132a052d 100644 --- a/src/p/stair_e.java +++ b/src/p/stair_e.java @@ -1,7 +1,6 @@ package p; -public enum stair_e -{ +public enum stair_e { build8, // slowly build by 8 turbo16 // quickly build by 16 -} \ No newline at end of file +} diff --git a/src/p/switchlist_t.java b/src/p/switchlist_t.java index 170ae2f1..a0541cb4 100644 --- a/src/p/switchlist_t.java +++ b/src/p/switchlist_t.java @@ -3,20 +3,16 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; - import w.CacheableDoomObject; import w.DoomBuffer; -// -// P_SWITCH -// public class switchlist_t implements CacheableDoomObject { - - public switchlist_t(){ - + + public switchlist_t() { + } - + // Were char[9] public String name1; @@ -48,4 +44,4 @@ public final static int size() { public String toString() { return String.format("%s %s %d", name1, name2, episode); } -} \ No newline at end of file +} diff --git a/src/p/vldoor_e.java b/src/p/vldoor_e.java index 83b2f1d8..5bebde3e 100644 --- a/src/p/vldoor_e.java +++ b/src/p/vldoor_e.java @@ -3,16 +3,15 @@ // // P_DOORS // - public enum vldoor_e { - normal, - close30ThenOpen, - close, - open, - raiseIn5Mins, - blazeRaise, - blazeOpen, - blazeClose; - - public static final int VALUES=vldoor_e.values().length; - } \ No newline at end of file + normal, + close30ThenOpen, + close, + open, + raiseIn5Mins, + blazeRaise, + blazeOpen, + blazeClose; + + public static final int VALUES = vldoor_e.values().length; +} diff --git a/src/p/vldoor_t.java b/src/p/vldoor_t.java index f99221d5..dc97dbec 100644 --- a/src/p/vldoor_t.java +++ b/src/p/vldoor_t.java @@ -3,50 +3,49 @@ import java.io.DataInputStream; import java.io.IOException; import java.nio.ByteBuffer; - import rr.SectorAction; import w.DoomIO; import w.IReadableDoomObject; -public class vldoor_t extends SectorAction implements IReadableDoomObject{ - - public vldoor_e type; - /** fixed_t */ - public int topheight, speed; - - /** 1 = up, 0 = waiting at top, -1 = down */ - public int direction; - - /** tics to wait at the top */ - public int topwait; - - /**(keep in case a door going down is reset) - when it reaches 0, start going down */ - public int topcountdown; - - @Override - public void read(DataInputStream f) throws IOException{ - - super.read(f); // Call thinker reader first - type=vldoor_e.values()[DoomIO.readLEInt(f)]; - super.sectorid=DoomIO.readLEInt(f); // Sector index (or pointer?) - topheight=DoomIO.readLEInt(f); - speed=DoomIO.readLEInt(f); - direction=DoomIO.readLEInt(f); - topwait=DoomIO.readLEInt(f); - topcountdown=DoomIO.readLEInt(f); - } - - @Override - public void pack(ByteBuffer b) throws IOException{ - super.pack(b); //12 - b.putInt(type.ordinal()); // 16 - b.putInt(super.sectorid); // 20 - b.putInt(topheight); // 24 - b.putInt(speed); //28 - b.putInt(direction); // 32 - b.putInt(topwait); //36 - b.putInt(topcountdown); //40 - } - - } \ No newline at end of file +public class vldoor_t extends SectorAction implements IReadableDoomObject { + + public vldoor_e type; + /** fixed_t */ + public int topheight, speed; + + /** 1 = up, 0 = waiting at top, -1 = down */ + public int direction; + + /** tics to wait at the top */ + public int topwait; + + /**(keep in case a door going down is reset) + when it reaches 0, start going down */ + public int topcountdown; + + @Override + public void read(DataInputStream f) throws IOException { + + super.read(f); // Call thinker reader first + type = vldoor_e.values()[DoomIO.readLEInt(f)]; + super.sectorid = DoomIO.readLEInt(f); // Sector index (or pointer?) + topheight = DoomIO.readLEInt(f); + speed = DoomIO.readLEInt(f); + direction = DoomIO.readLEInt(f); + topwait = DoomIO.readLEInt(f); + topcountdown = DoomIO.readLEInt(f); + } + + @Override + public void pack(ByteBuffer b) throws IOException { + super.pack(b); //12 + b.putInt(type.ordinal()); // 16 + b.putInt(super.sectorid); // 20 + b.putInt(topheight); // 24 + b.putInt(speed); //28 + b.putInt(direction); // 32 + b.putInt(topwait); //36 + b.putInt(topcountdown); //40 + } + +} diff --git a/src/pooling/AudioChunkPool.java b/src/pooling/AudioChunkPool.java index 111874f9..6b8bf359 100644 --- a/src/pooling/AudioChunkPool.java +++ b/src/pooling/AudioChunkPool.java @@ -4,28 +4,22 @@ // Referenced classes of package pooling: // ObjectPool +public class AudioChunkPool extends ObjectQueuePool { -public class AudioChunkPool extends ObjectQueuePool -{ - - public AudioChunkPool() - { - // A reasonable time limit for Audio chunks - super(10000L); + public AudioChunkPool() { + // A reasonable time limit for Audio chunks + super(10000L); } - protected AudioChunk create() - { + protected AudioChunk create() { return new AudioChunk(); } - public void expire(AudioChunk o) - { + public void expire(AudioChunk o) { o.free = true; } - public boolean validate(AudioChunk o) - { + public boolean validate(AudioChunk o) { return o.free; } diff --git a/src/pooling/GenericIntMap.java b/src/pooling/GenericIntMap.java index 75fca2f1..7e61c96f 100644 --- a/src/pooling/GenericIntMap.java +++ b/src/pooling/GenericIntMap.java @@ -3,21 +3,22 @@ import java.util.Arrays; public abstract class GenericIntMap { + protected static final int DEFAULT_CAPACITY = 16; - + /** Concrete implementations must allocate patches * */ GenericIntMap() { - - lumps = new int[DEFAULT_CAPACITY]; + + lumps = new int[DEFAULT_CAPACITY]; // patches = new K[DEFAULT_CAPACITY]; } - + public boolean containsKey(int lump) { return indexOf(lump) >= 0; } - + public K get(int lump) { int index = indexOf(lump); if (index >= 0) { @@ -26,7 +27,7 @@ public K get(int lump) { return null; } } - + public void put(int lump, K patch) { int index = indexOf(lump); if (index >= 0) { @@ -36,35 +37,35 @@ public void put(int lump, K patch) { int newIndex = ~index; int moveCount = numEntries - newIndex; if (moveCount > 0) { - System.arraycopy(lumps, newIndex, lumps, newIndex+1, moveCount); - System.arraycopy(patches, newIndex, patches, newIndex+1, moveCount); + System.arraycopy(lumps, newIndex, lumps, newIndex + 1, moveCount); + System.arraycopy(patches, newIndex, patches, newIndex + 1, moveCount); } lumps[newIndex] = lump; patches[newIndex] = patch; - ++ numEntries; + ++numEntries; } } - + protected void ensureCapacity(int cap) { while (lumps.length <= cap) { - lumps = - Arrays.copyOf(lumps, Math.max(lumps.length * 2, DEFAULT_CAPACITY)); + lumps + = Arrays.copyOf(lumps, Math.max(lumps.length * 2, DEFAULT_CAPACITY)); } while (patches.length <= cap) { - patches = - Arrays.copyOf(patches, Math.max(patches.length * 2, DEFAULT_CAPACITY)); + patches + = Arrays.copyOf(patches, Math.max(patches.length * 2, DEFAULT_CAPACITY)); } } + protected int indexOf(int lump) { - return Arrays.binarySearch(lumps, 0, numEntries, lump); - //for (int i=0;i { + private static final Logger LOGGER = Loggers.getLogger(ObjectPool.class.getName()); -public abstract class ObjectPool -{ + private static final boolean D = false; - private static final boolean D=false; - - public ObjectPool(long expirationTime) - { + public ObjectPool(long expirationTime) { this.expirationTime = expirationTime; - locked = new Hashtable(); - unlocked = new Hashtable(); + locked = new Hashtable<>(); + unlocked = new Hashtable<>(); } protected abstract K create(); @@ -30,36 +30,36 @@ public ObjectPool(long expirationTime) public abstract void expire(K obj); - public synchronized K checkOut() - { + public synchronized K checkOut() { long now = System.currentTimeMillis(); K t; - if(unlocked.size() > 0) - { + if (!unlocked.isEmpty()) { Enumeration e = unlocked.keys(); - // System.out.println((new StringBuilder("Pool size ")).append(unlocked.size()).toString()); - while(e.hasMoreElements()) - { + // System.out.println((new StringBuilder("Pool size ")).append(unlocked.size()).toString()); + while (e.hasMoreElements()) { t = e.nextElement(); - if(now - ((Long)unlocked.get(t)).longValue() > expirationTime) - { - // object has expired - if (t instanceof mobj_t) - if (D) System.out.printf("Object %s expired\n",t.toString()); + if (now - ((Long) unlocked.get(t)).longValue() > expirationTime) { + // object has expired + if (t instanceof mobj_t) { + if (D) { + LOGGER.log(Level.FINE, String.format("Object %s expired", t.toString())); + } + } unlocked.remove(t); expire(t); t = null; - } else - { - if(validate(t)) - { + } else { + if (validate(t)) { unlocked.remove(t); locked.put(t, Long.valueOf(now)); - if (D) if (t instanceof mobj_t) - System.out.printf("Object %s reused\n",t.toString()); + if (D) { + if (t instanceof mobj_t) { + LOGGER.log(Level.FINE, String.format("Object %s reused", t.toString())); + } + } return t; } - + // object failed validation unlocked.remove(t); expire(t); @@ -73,15 +73,17 @@ public synchronized K checkOut() return t; } - public synchronized void checkIn(K t) - { - if (D) if (t instanceof mobj_t) - System.out.printf("Object %s returned to the pool\n",t.toString()); + public synchronized void checkIn(K t) { + if (D) { + if (t instanceof mobj_t) { + LOGGER.log(Level.FINE, String.format("Object %s returned to the pool", t.toString())); + } + } locked.remove(t); unlocked.put(t, Long.valueOf(System.currentTimeMillis())); } private long expirationTime; - protected Hashtable locked; - private Hashtable unlocked; + protected Hashtable locked; + private Hashtable unlocked; } diff --git a/src/pooling/ObjectQueuePool.java b/src/pooling/ObjectQueuePool.java index 2db6d1e6..5cef27fa 100644 --- a/src/pooling/ObjectQueuePool.java +++ b/src/pooling/ObjectQueuePool.java @@ -1,7 +1,9 @@ package pooling; import java.util.Stack; - +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import p.mobj_t; /** A convenient object pooling class, derived from the stock ObjectPool. @@ -10,17 +12,15 @@ * because it doesn't do that bullshit object cleanup every so often. * */ +public abstract class ObjectQueuePool { + + private static final Logger LOGGER = Loggers.getLogger(ObjectQueuePool.class.getName()); + private static final boolean D = false; -public abstract class ObjectQueuePool -{ + public ObjectQueuePool(long expirationTime) { + locked = new Stack<>(); - private static final boolean D=false; - - public ObjectQueuePool(long expirationTime) - { - locked = new Stack(); - } protected abstract K create(); @@ -29,17 +29,15 @@ public ObjectQueuePool(long expirationTime) public abstract void expire(K obj); - public void drain(){ + public void drain() { locked.clear(); - } - - public K checkOut() - { - + } + + public K checkOut() { + K t; - if(!locked.isEmpty()) - { - return locked.pop(); + if (!locked.isEmpty()) { + return locked.pop(); } @@ -47,13 +45,15 @@ public K checkOut() return t; } - public void checkIn(K t) - { - if (D) if (t instanceof mobj_t) - System.out.printf("Object %s returned to the pool\n",t.toString()); + public void checkIn(K t) { + if (D) { + if (t instanceof mobj_t) { + LOGGER.log(Level.FINE, String.format("Object %s returned to the pool", t.toString())); + } + } locked.push(t); } protected Stack locked; - // private Hashtable unlocked; + // private Hashtable unlocked; } diff --git a/src/pooling/RoguePatchMap.java b/src/pooling/RoguePatchMap.java index d23c344c..c3960699 100644 --- a/src/pooling/RoguePatchMap.java +++ b/src/pooling/RoguePatchMap.java @@ -1,9 +1,9 @@ package pooling; public class RoguePatchMap extends GenericIntMap { - - public RoguePatchMap(){ - super(); - patches = new byte[DEFAULT_CAPACITY][][]; - } + + public RoguePatchMap() { + super(); + patches = new byte[DEFAULT_CAPACITY][][]; + } } diff --git a/src/pooling/RoguePatchMap2.java b/src/pooling/RoguePatchMap2.java index f12bce68..b70a42c2 100644 --- a/src/pooling/RoguePatchMap2.java +++ b/src/pooling/RoguePatchMap2.java @@ -3,14 +3,18 @@ import java.util.Arrays; public class RoguePatchMap2 { + private static final int DEFAULT_CAPACITY = 16; + public RoguePatchMap2() { lumps = new int[DEFAULT_CAPACITY]; patches = new byte[DEFAULT_CAPACITY][][]; } + boolean containsKey(int lump) { return indexOf(lump) >= 0; } + public byte[][] get(int lump) { int index = indexOf(lump); if (index >= 0) { @@ -19,6 +23,7 @@ public byte[][] get(int lump) { return null; } } + public void put(int lump, byte[][] patch) { int index = indexOf(lump); if (index >= 0) { @@ -28,28 +33,30 @@ public void put(int lump, byte[][] patch) { int newIndex = ~index; int moveCount = numEntries - newIndex; if (moveCount > 0) { - System.arraycopy(lumps, newIndex, lumps, newIndex+1, moveCount); - System.arraycopy(patches, newIndex, patches, newIndex+1, moveCount); + System.arraycopy(lumps, newIndex, lumps, newIndex + 1, moveCount); + System.arraycopy(patches, newIndex, patches, newIndex + 1, moveCount); } lumps[newIndex] = lump; patches[newIndex] = patch; - ++ numEntries; + ++numEntries; } } + private void ensureCapacity(int cap) { while (lumps.length <= cap) { - lumps = - Arrays.copyOf(lumps, Math.max(lumps.length * 2, DEFAULT_CAPACITY)); + lumps + = Arrays.copyOf(lumps, Math.max(lumps.length * 2, DEFAULT_CAPACITY)); } while (patches.length <= cap) { - patches = - Arrays.copyOf(patches, Math.max(patches.length * 2, DEFAULT_CAPACITY)); + patches + = Arrays.copyOf(patches, Math.max(patches.length * 2, DEFAULT_CAPACITY)); } } + private int indexOf(int lump) { return Arrays.binarySearch(lumps, 0, numEntries, lump); } private int[] lumps; private int numEntries; private byte[][][] patches; -} \ No newline at end of file +} diff --git a/src/rr/AbstractThings.java b/src/rr/AbstractThings.java index 127c62ce..5de70723 100644 --- a/src/rr/AbstractThings.java +++ b/src/rr/AbstractThings.java @@ -34,14 +34,13 @@ * * */ +public abstract class AbstractThings implements IMaskedDrawer { -public abstract class AbstractThings implements IMaskedDrawer { + private final static boolean RANGECHECK = false; - private final static boolean RANGECHECK=false; - protected short[] maskedtexturecol; protected int pmaskedtexturecol = 0; - + // Cache those you get from the sprite manager protected int[] spritewidth, spriteoffset, spritetopoffset; @@ -55,7 +54,7 @@ public abstract class AbstractThings implements IMaskedDrawer { protected int spryscale; protected int sprtopscreen; - + protected short[] mfloorclip; protected int p_mfloorclip; @@ -70,11 +69,11 @@ public abstract class AbstractThings implements IMaskedDrawer { // This must be "pegged" to the one used by the default renderer. protected ColVars maskedcvars; - - protected ColumnFunction colfunc; - protected ColFuncs colfuncs; - protected ColFuncs colfuncshi; - protected ColFuncs colfuncslow; + + protected ColumnFunction colfunc; + protected ColFuncs colfuncs; + protected ColFuncs colfuncshi; + protected ColFuncs colfuncslow; protected final VideoScale vs; protected final LightsAndColors colormaps; protected final ViewVars view; @@ -86,8 +85,8 @@ public abstract class AbstractThings implements IMaskedDrawer { protected final IVisSpriteManagement VIS; protected final IWadLoader W; protected final vissprite_t avis; - - public AbstractThings(VideoScale vs, SceneRenderer R) { + + public AbstractThings(VideoScale vs, SceneRenderer R) { this.colfuncshi = R.getColFuncsHi(); this.colfuncslow = R.getColFuncsLow(); this.colormaps = R.getColorMap(); @@ -99,7 +98,7 @@ public AbstractThings(VideoScale vs, SceneRenderer R) { this.MyBSP = R.getBSPVars(); this.VIS = R.getVisSpriteManager(); this.W = R.getWadLoader(); - this.avis = new vissprite_t(); + this.avis = new vissprite_t<>(); this.maskedcvars = R.getMaskedDCVars(); this.vs = vs; clipbot = new short[vs.getScreenWidth()]; @@ -143,20 +142,21 @@ protected void DrawVisSprite(vissprite_t vis) { maskedcvars.dc_texturemid = vis.texturemid; frac = vis.startfrac; spryscale = vis.scale; - sprtopscreen = - view.centeryfrac - - FixedMul(maskedcvars.dc_texturemid, spryscale); + sprtopscreen + = view.centeryfrac + - FixedMul(maskedcvars.dc_texturemid, spryscale); // A texture height of 0 means "not tiling" and holds for // all sprite/masked renders. maskedcvars.dc_texheight = 0; - for (maskedcvars.dc_x = vis.x1; maskedcvars.dc_x <= vis.x2; maskedcvars.dc_x++, frac += - vis.xiscale) { + for (maskedcvars.dc_x = vis.x1; maskedcvars.dc_x <= vis.x2; maskedcvars.dc_x++, frac + += vis.xiscale) { texturecolumn = frac >> FRACBITS; if (RANGECHECK) { - if (texturecolumn < 0 || texturecolumn >= patch.width) + if (texturecolumn < 0 || texturecolumn >= patch.width) { I.Error("R_DrawSpriteRange: bad texturecolumn"); + } } column = patch.columns[texturecolumn]; DrawMaskedColumn(column); @@ -179,7 +179,6 @@ protected void RenderMaskedSegRange(drawseg_t ds, int x1, int x2) { int texnum; // System.out.printf("RenderMaskedSegRange from %d to %d\n",x1,x2); - // Calculate light table. // Use different light tables // for horizontal / vertical / diagonal. Diagonal? @@ -189,19 +188,20 @@ protected void RenderMaskedSegRange(drawseg_t ds, int x1, int x2) { backsector = MyBSP.curline.backsector; texnum = TexMan.getTextureTranslation(MyBSP.curline.sidedef.midtexture); // System.out.print(" for texture "+textures[texnum].name+"\n:"); - lightnum = - (frontsector.lightlevel >> colormaps.lightSegShift()) + colormaps.extralight; + lightnum + = (frontsector.lightlevel >> colormaps.lightSegShift()) + colormaps.extralight; - if (MyBSP.curline.v1y == MyBSP.curline.v2y) + if (MyBSP.curline.v1y == MyBSP.curline.v2y) { lightnum--; - else if (MyBSP.curline.v1x == MyBSP.curline.v2x) + } else if (MyBSP.curline.v1x == MyBSP.curline.v2x) { lightnum++; + } // Killough code. - colormaps.walllights = - lightnum >= colormaps.lightLevels() ? colormaps.scalelight[colormaps.lightLevels() - 1] - : lightnum < 0 ? colormaps.scalelight[0] - : colormaps.scalelight[lightnum]; + colormaps.walllights + = lightnum >= colormaps.lightLevels() ? colormaps.scalelight[colormaps.lightLevels() - 1] + : lightnum < 0 ? colormaps.scalelight[0] + : colormaps.scalelight[lightnum]; // Get the list maskedtexturecol = ds.getMaskedTextureColList(); @@ -218,27 +218,28 @@ else if (MyBSP.curline.v1x == MyBSP.curline.v2x) p_mceilingclip = ds.getSprTopClipPointer(); // find positioning if ((MyBSP.curline.linedef.flags & ML_DONTPEGBOTTOM) != 0) { - maskedcvars.dc_texturemid = - frontsector.floorheight > backsector.floorheight ? frontsector.floorheight - : backsector.floorheight; - maskedcvars.dc_texturemid = - maskedcvars.dc_texturemid + TexMan.getTextureheight(texnum) - - view.z; + maskedcvars.dc_texturemid + = frontsector.floorheight > backsector.floorheight ? frontsector.floorheight + : backsector.floorheight; + maskedcvars.dc_texturemid + = maskedcvars.dc_texturemid + TexMan.getTextureheight(texnum) + - view.z; } else { - maskedcvars.dc_texturemid = - frontsector.ceilingheight < backsector.ceilingheight ? frontsector.ceilingheight - : backsector.ceilingheight; + maskedcvars.dc_texturemid + = frontsector.ceilingheight < backsector.ceilingheight ? frontsector.ceilingheight + : backsector.ceilingheight; maskedcvars.dc_texturemid = maskedcvars.dc_texturemid - view.z; } maskedcvars.dc_texturemid += MyBSP.curline.sidedef.rowoffset; - if (colormaps.fixedcolormap != null) + if (colormaps.fixedcolormap != null) { maskedcvars.dc_colormap = colormaps.fixedcolormap; + } // Texture height must be set at this point. This will trigger // tiling. For sprites, it should be set to 0. - maskedcvars.dc_texheight = - TexMan.getTextureheight(texnum) >> FRACBITS; + maskedcvars.dc_texheight + = TexMan.getTextureheight(texnum) >> FRACBITS; // draw the columns for (maskedcvars.dc_x = x1; maskedcvars.dc_x <= x2; maskedcvars.dc_x++) { @@ -247,26 +248,27 @@ else if (MyBSP.curline.v1x == MyBSP.curline.v2x) if (colormaps.fixedcolormap == null) { index = spryscale >>> colormaps.lightScaleShift(); - if (index >= colormaps.maxLightScale()) + if (index >= colormaps.maxLightScale()) { index = colormaps.maxLightScale() - 1; + } maskedcvars.dc_colormap = colormaps.walllights[index]; } - sprtopscreen = - view.centeryfrac - - FixedMul(maskedcvars.dc_texturemid, spryscale); + sprtopscreen + = view.centeryfrac + - FixedMul(maskedcvars.dc_texturemid, spryscale); maskedcvars.dc_iscale = (int) (0xffffffffL / spryscale); // draw the texture column_t data = TexMan.GetColumnStruct(texnum, - (int) maskedtexturecol[pmaskedtexturecol - + maskedcvars.dc_x]);// -3); + (int) maskedtexturecol[pmaskedtexturecol + + maskedcvars.dc_x]);// -3); DrawMaskedColumn(data); - maskedtexturecol[pmaskedtexturecol + maskedcvars.dc_x] = - Short.MAX_VALUE; + maskedtexturecol[pmaskedtexturecol + maskedcvars.dc_x] + = Short.MAX_VALUE; } spryscale += rw_scalestep; } @@ -277,7 +279,6 @@ else if (MyBSP.curline.v1x == MyBSP.curline.v2x) * R_DrawPSprite Draws a "player sprite" with slighly different rules * than normal sprites. This is actually a PITA, at best :-/ */ - protected void DrawPSprite(pspdef_t psp) { int tx; @@ -291,17 +292,19 @@ protected void DrawPSprite(pspdef_t psp) { // decide which patch to use (in terms of angle?) if (RANGECHECK) { - if (psp.state.sprite.ordinal() >= SM.getNumSprites()) + if (psp.state.sprite.ordinal() >= SM.getNumSprites()) { I.Error("R_ProjectSprite: invalid sprite number %d ", - psp.state.sprite); + psp.state.sprite); + } } sprdef = SM.getSprite(psp.state.sprite.ordinal()); if (RANGECHECK) { - if ((psp.state.frame & FF_FRAMEMASK) >= sprdef.numframes) + if ((psp.state.frame & FF_FRAMEMASK) >= sprdef.numframes) { I.Error("R_ProjectSprite: invalid sprite frame %d : %d ", - psp.state.sprite, psp.state.frame); + psp.state.sprite, psp.state.frame); + } } sprframe = sprdef.spriteframes[psp.state.frame & FF_FRAMEMASK]; @@ -321,23 +324,25 @@ protected void DrawPSprite(pspdef_t psp) { x1 = (view.centerxfrac + FixedMul(tx, pspritescale)) >> FRACBITS; // off the right side - if (x1 > view.width) + if (x1 > view.width) { return; + } tx += spritewidth[lump]; - x2 = - ((view.centerxfrac + FixedMul(tx, pspritescale)) >> FRACBITS) - 1; + x2 + = ((view.centerxfrac + FixedMul(tx, pspritescale)) >> FRACBITS) - 1; // off the left side - if (x2 < 0) + if (x2 < 0) { return; + } // store information in a vissprite ? vis = avis; vis.mobjflags = 0; - vis.texturemid = - ((BASEYCENTER + view.lookdir) << FRACBITS) + FRACUNIT / 2 - - (psp.sy - spritetopoffset[lump]); + vis.texturemid + = ((BASEYCENTER + view.lookdir) << FRACBITS) + FRACUNIT / 2 + - (psp.sy - spritetopoffset[lump]); vis.x1 = x1 < 0 ? 0 : x1; vis.x2 = x2 >= view.width ? view.width - 1 : x2; vis.scale = (pspritescale) << view.detailshift; @@ -350,8 +355,9 @@ protected void DrawPSprite(pspdef_t psp) { vis.startfrac = 0; } - if (vis.x1 > x1) + if (vis.x1 > x1) { vis.startfrac += vis.xiscale * (vis.x1 - x1); + } vis.patch = lump; @@ -377,37 +383,37 @@ protected void DrawPSprite(pspdef_t psp) { DrawVisSprite(vis); } - protected int PSpriteSY[] = { 0, // staff - 5 * FRACUNIT, // goldwand - 15 * FRACUNIT, // crossbow - 15 * FRACUNIT, // blaster - 15 * FRACUNIT, // skullrod - 15 * FRACUNIT, // phoenix rod - 15 * FRACUNIT, // mace - 15 * FRACUNIT, // gauntlets - 15 * FRACUNIT // beak - }; + protected int PSpriteSY[] = {0, // staff + 5 * FRACUNIT, // goldwand + 15 * FRACUNIT, // crossbow + 15 * FRACUNIT, // blaster + 15 * FRACUNIT, // skullrod + 15 * FRACUNIT, // phoenix rod + 15 * FRACUNIT, // mace + 15 * FRACUNIT, // gauntlets + 15 * FRACUNIT // beak +}; /** * R_DrawPlayerSprites This is where stuff like guns is drawn...right? */ - protected final void DrawPlayerSprites() { int i; int lightnum; pspdef_t psp; // get light level - lightnum = - (view.player.mo.subsector.sector.lightlevel >> colormaps.lightSegShift()) - + colormaps.extralight; + lightnum + = (view.player.mo.subsector.sector.lightlevel >> colormaps.lightSegShift()) + + colormaps.extralight; - if (lightnum < 0) + if (lightnum < 0) { colormaps.spritelights = colormaps.scalelight[0]; - else if (lightnum >= colormaps.lightLevels()) + } else if (lightnum >= colormaps.lightLevels()) { colormaps.spritelights = colormaps.scalelight[colormaps.lightLevels() - 1]; - else + } else { colormaps.spritelights = colormaps.scalelight[lightnum]; + } // clip to screen bounds mfloorclip = view.screenheightarray; @@ -436,7 +442,6 @@ else if (lightnum >= colormaps.lightLevels()) /** * R_DrawSprite */ - protected final void DrawSprite(vissprite_t spr) { int ds; drawseg_t dss; @@ -448,8 +453,9 @@ protected final void DrawSprite(vissprite_t spr) { int lowscale; // fixed int silhouette; - for (x = spr.x1; x <= spr.x2; x++) + for (x = spr.x1; x <= spr.x2; x++) { clipbot[x] = cliptop[x] = -2; + } // Scan drawsegs from end to start for obscuring segs. // The first drawseg that has a greater scale @@ -481,8 +487,9 @@ protected final void DrawSprite(vissprite_t spr) { || (lowscale < spr.scale && (dss.curline .PointOnSegSide(spr.gx, spr.gy) == 0))) { // masked mid texture? - if (!dss.nullMaskedTextureCol()) + if (!dss.nullMaskedTextureCol()) { RenderMaskedSegRange(dss, r1, r2); + } // seg is behind sprite continue; } @@ -490,45 +497,54 @@ protected final void DrawSprite(vissprite_t spr) { // clip this piece of the sprite silhouette = dss.silhouette; - if (spr.gz >= dss.bsilheight) + if (spr.gz >= dss.bsilheight) { silhouette &= ~SIL_BOTTOM; + } - if (spr.gzt <= dss.tsilheight) + if (spr.gzt <= dss.tsilheight) { silhouette &= ~SIL_TOP; + } // BOTTOM clipping if (silhouette == 1) { // bottom sil - for (x = r1; x <= r2; x++) - if (clipbot[x] == -2) + for (x = r1; x <= r2; x++) { + if (clipbot[x] == -2) { clipbot[x] = dss.getSprBottomClip(x); + } + } } else if (silhouette == 2) { // top sil - for (x = r1; x <= r2; x++) - if (cliptop[x] == -2) + for (x = r1; x <= r2; x++) { + if (cliptop[x] == -2) { cliptop[x] = dss.getSprTopClip(x); + } + } } else if (silhouette == 3) { // both for (x = r1; x <= r2; x++) { - if (clipbot[x] == -2) + if (clipbot[x] == -2) { clipbot[x] = dss.getSprBottomClip(x); - if (cliptop[x] == -2) + } + if (cliptop[x] == -2) { cliptop[x] = dss.getSprTopClip(x); + } } } } // all clipping has been performed, so draw the sprite - // check for unclipped columns for (x = spr.x1; x <= spr.x2; x++) { - if (clipbot[x] == -2) + if (clipbot[x] == -2) { clipbot[x] = (short) view.height; + } // ?? What's this bullshit? - if (cliptop[x] == -2) + if (cliptop[x] == -2) { cliptop[x] = -1; + } } mfloorclip = clipbot; @@ -545,7 +561,6 @@ protected final void DrawSprite(vissprite_t spr) { * anything, and it will work better, in-place and be simpler to draw, * too. */ - @Override public void DrawMasked() { // vissprite_t spr; @@ -561,7 +576,6 @@ public void DrawMasked() { // modified mergesort, while // the original algorithm is so dreadful it actually does slow // things down. - VIS.SortVisSprites(); // If you are feeling adventurous, try these ones. They *might* @@ -571,12 +585,9 @@ public void DrawMasked() { // of your view, but I hardly see any benefits in that. They are // both // much better than the original anyway. - // combSort(vissprites,vissprite_p); // shellsort(vissprites,vissprite_p); - // pQuickSprite.sort(vissprites); - // The original sort. It's incredibly bad on so many levels (uses a // separate // linked list for the sorted sequence, which is pointless since the @@ -592,12 +603,10 @@ public void DrawMasked() { * vsprsortedhead.next ; spr != vsprsortedhead ; spr=spr.next) { * DrawSprite (spr); } } */ - // After using in-place sorts, sprites can be drawn as simply as // that. - colfunc = colfuncs.masked; // Sprites use fully-masked capable - // function. + // function. final vissprite_t[] vissprites = VIS.getVisSprites(); final int numvissprites = VIS.getNumVisSprites(); @@ -609,8 +618,9 @@ public void DrawMasked() { // render any remaining masked mid textures for (ds = seg_vars.ds_p - 1; ds >= 0; ds--) { dss = seg_vars.drawsegs[ds]; - if (!dss.nullMaskedTextureCol()) + if (!dss.nullMaskedTextureCol()) { RenderMaskedSegRange(dss, dss.x1, dss.x2); + } } // draw the psprites on top of everything // but does not draw on side views @@ -628,7 +638,7 @@ public void DrawMasked() { * you're doing. */ - /* protected final void DrawMaskedColumn(T column) { + /* protected final void DrawMaskedColumn(T column) { int topscreen; int bottomscreen; int basetexturemid; // fixed_t @@ -681,9 +691,7 @@ public void DrawMasked() { maskedcvars.dc_texturemid = basetexturemid; } - */ - - + */ /** * R_DrawMaskedColumn Used for sprites and masked mid textures. Masked * means: partly transparent, i.e. stored in posts/runs of opaque @@ -691,7 +699,6 @@ public void DrawMasked() { * post is drawn outside of the screen the rest appear screwed up. * SOLUTION: use the version taking raw byte[] arguments. */ - @SuppressWarnings("unchecked") protected final void DrawMaskedColumn(column_t column) { int topscreen; @@ -715,13 +722,15 @@ protected final void DrawMaskedColumn(column_t column) { maskedcvars.dc_yh = (bottomscreen - 1) >> FRACBITS; if (maskedcvars.dc_yh >= mfloorclip[p_mfloorclip - + maskedcvars.dc_x]) - maskedcvars.dc_yh = - mfloorclip[p_mfloorclip + maskedcvars.dc_x] - 1; + + maskedcvars.dc_x]) { + maskedcvars.dc_yh + = mfloorclip[p_mfloorclip + maskedcvars.dc_x] - 1; + } if (maskedcvars.dc_yl <= mceilingclip[p_mceilingclip - + maskedcvars.dc_x]) - maskedcvars.dc_yl = - mceilingclip[p_mceilingclip + maskedcvars.dc_x] + 1; + + maskedcvars.dc_x]) { + maskedcvars.dc_yl + = mceilingclip[p_mceilingclip + maskedcvars.dc_x] + 1; + } // killough 3/2/98, 3/27/98: Failsafe against overflow/crash: if (maskedcvars.dc_yl <= maskedcvars.dc_yh @@ -729,9 +738,8 @@ protected final void DrawMaskedColumn(column_t column) { // Set pointer inside column to current post's data // Remember, it goes {postlen}{postdelta}{pad}[data]{pad} - - maskedcvars.dc_texturemid = - basetexturemid - (column.postdeltas[i] << FRACBITS); + maskedcvars.dc_texturemid + = basetexturemid - (column.postdeltas[i] << FRACBITS); // Drawn by either R_DrawColumn or (SHADOW) // R_DrawFuzzColumn. @@ -742,21 +750,19 @@ protected final void DrawMaskedColumn(column_t column) { // frac = dc_texturemid + (dc_yl - centery) * fracstep; // // results in a negative initial frac number. - // Drawn by either R_DrawColumn // or (SHADOW) R_DrawFuzzColumn. - // FUN FACT: this was missing and fucked my shit up. - maskedcvars.dc_texheight=0; // Killough - + maskedcvars.dc_texheight = 0; // Killough + completeColumn(); - + } } maskedcvars.dc_texturemid = basetexturemid; } - + /* * R_DrawMaskedColumn * Used for sprites and masked mid textures. @@ -768,7 +774,7 @@ protected final void DrawMaskedColumn(column_t column) { * REALLY needed. * */ -/* + /* protected final void DrawMaskedColumn (byte[] column) { int topscreen; @@ -819,8 +825,7 @@ protected final void DrawMaskedColumn (byte[] column) dc_texturemid = basetexturemid; } - */ - + */ @Override public void setPspriteIscale(int i) { pspriteiscale = i; @@ -833,15 +838,15 @@ public void setPspriteScale(int i) { } @Override - public void setDetail(int detailshift){ - switch (detailshift){ - case HIGH_DETAIL: - colfuncs=colfuncshi; - break; - case LOW_DETAIL: - colfuncs=colfuncslow; - break; + public void setDetail(int detailshift) { + switch (detailshift) { + case HIGH_DETAIL: + colfuncs = colfuncshi; + break; + case LOW_DETAIL: + colfuncs = colfuncslow; + break; } } - + } diff --git a/src/rr/BSPVars.java b/src/rr/BSPVars.java index fd53e7c3..314d5dec 100644 --- a/src/rr/BSPVars.java +++ b/src/rr/BSPVars.java @@ -1,12 +1,11 @@ package rr; - /** Stuff used to pass information between the BSP and the SegDrawer */ +public class BSPVars { -public class BSPVars{ -/** The sectors of the line currently being considered */ -public sector_t frontsector, backsector; -public seg_t curline; -public side_t sidedef; -public line_t linedef; + /** The sectors of the line currently being considered */ + public sector_t frontsector, backsector; + public seg_t curline; + public side_t sidedef; + public line_t linedef; } diff --git a/src/rr/IDetailAware.java b/src/rr/IDetailAware.java index ce4e89f7..39bbbae4 100644 --- a/src/rr/IDetailAware.java +++ b/src/rr/IDetailAware.java @@ -2,7 +2,8 @@ public interface IDetailAware { - public static int HIGH_DETAIL=0; - public static int LOW_DETAIL=1; + public static int HIGH_DETAIL = 0; + public static int LOW_DETAIL = 1; + void setDetail(int detailshift); } diff --git a/src/rr/IGetCachedColumn.java b/src/rr/IGetCachedColumn.java index 6262c43a..f2bc343a 100644 --- a/src/rr/IGetCachedColumn.java +++ b/src/rr/IGetCachedColumn.java @@ -6,9 +6,8 @@ * @author Maes * */ - public interface IGetCachedColumn { - T GetCachedColumn(int tex, int col); + T GetCachedColumn(int tex, int col); } diff --git a/src/rr/IGetColumn.java b/src/rr/IGetColumn.java index 611cecc6..b936b2bb 100644 --- a/src/rr/IGetColumn.java +++ b/src/rr/IGetColumn.java @@ -6,9 +6,8 @@ * @author Maes * */ - public interface IGetColumn { - T GetColumn(int tex, int col); + T GetColumn(int tex, int col); } diff --git a/src/rr/ILimitResettable.java b/src/rr/ILimitResettable.java index f7ee2455..2b32ac88 100644 --- a/src/rr/ILimitResettable.java +++ b/src/rr/ILimitResettable.java @@ -7,7 +7,7 @@ * @author admin * */ - public interface ILimitResettable { - public void resetLimits(); + + public void resetLimits(); } diff --git a/src/rr/IMaskedDrawer.java b/src/rr/IMaskedDrawer.java index 89b7b6b6..5a16fd11 100644 --- a/src/rr/IMaskedDrawer.java +++ b/src/rr/IMaskedDrawer.java @@ -1,13 +1,11 @@ package rr; /** Draws any masked stuff -sprites, textures, or special 3D floors */ - -public interface IMaskedDrawer extends IDetailAware { +public interface IMaskedDrawer extends IDetailAware { public static final int BASEYCENTER = 100; - - /** Cache the sprite manager, if possible */ + /** Cache the sprite manager, if possible */ void cacheSpriteManager(ISpriteManager SM); void DrawMasked(); @@ -21,6 +19,5 @@ public interface IMaskedDrawer extends IDetailAware { * parallel version, store rendering instructions and execute later on. * HINT: you need to discern between masked and non-masked draws. */ - void completeColumn(); } diff --git a/src/rr/ISpriteManager.java b/src/rr/ISpriteManager.java index f3453737..353f2d81 100644 --- a/src/rr/ISpriteManager.java +++ b/src/rr/ISpriteManager.java @@ -6,46 +6,48 @@ * @author velktron. * */ - public interface ISpriteManager { - + /** Default known sprite names for DOOM */ public final static String[] doomsprnames = { - "TROO","SHTG","PUNG","PISG","PISF","SHTF","SHT2","CHGG","CHGF","MISG", - "MISF","SAWG","PLSG","PLSF","BFGG","BFGF","BLUD","PUFF","BAL1","BAL2", - "PLSS","PLSE","MISL","BFS1","BFE1","BFE2","TFOG","IFOG","PLAY","POSS", - "SPOS","VILE","FIRE","FATB","FBXP","SKEL","MANF","FATT","CPOS","SARG", - "HEAD","BAL7","BOSS","BOS2","SKUL","SPID","BSPI","APLS","APBX","CYBR", - "PAIN","SSWV","KEEN","BBRN","BOSF","ARM1","ARM2","BAR1","BEXP","FCAN", - "BON1","BON2","BKEY","RKEY","YKEY","BSKU","RSKU","YSKU","STIM","MEDI", - "SOUL","PINV","PSTR","PINS","MEGA","SUIT","PMAP","PVIS","CLIP","AMMO", - "ROCK","BROK","CELL","CELP","SHEL","SBOX","BPAK","BFUG","MGUN","CSAW", - "LAUN","PLAS","SHOT","SGN2","COLU","SMT2","GOR1","POL2","POL5","POL4", - "POL3","POL1","POL6","GOR2","GOR3","GOR4","GOR5","SMIT","COL1","COL2", - "COL3","COL4","CAND","CBRA","COL6","TRE1","TRE2","ELEC","CEYE","FSKU", - "COL5","TBLU","TGRN","TRED","SMBT","SMGT","SMRT","HDB1","HDB2","HDB3", - "HDB4","HDB5","HDB6","POB1","POB2","BRS1","TLMP","TLP2" + "TROO", "SHTG", "PUNG", "PISG", "PISF", "SHTF", "SHT2", "CHGG", "CHGF", "MISG", + "MISF", "SAWG", "PLSG", "PLSF", "BFGG", "BFGF", "BLUD", "PUFF", "BAL1", "BAL2", + "PLSS", "PLSE", "MISL", "BFS1", "BFE1", "BFE2", "TFOG", "IFOG", "PLAY", "POSS", + "SPOS", "VILE", "FIRE", "FATB", "FBXP", "SKEL", "MANF", "FATT", "CPOS", "SARG", + "HEAD", "BAL7", "BOSS", "BOS2", "SKUL", "SPID", "BSPI", "APLS", "APBX", "CYBR", + "PAIN", "SSWV", "KEEN", "BBRN", "BOSF", "ARM1", "ARM2", "BAR1", "BEXP", "FCAN", + "BON1", "BON2", "BKEY", "RKEY", "YKEY", "BSKU", "RSKU", "YSKU", "STIM", "MEDI", + "SOUL", "PINV", "PSTR", "PINS", "MEGA", "SUIT", "PMAP", "PVIS", "CLIP", "AMMO", + "ROCK", "BROK", "CELL", "CELP", "SHEL", "SBOX", "BPAK", "BFUG", "MGUN", "CSAW", + "LAUN", "PLAS", "SHOT", "SGN2", "COLU", "SMT2", "GOR1", "POL2", "POL5", "POL4", + "POL3", "POL1", "POL6", "GOR2", "GOR3", "GOR4", "GOR5", "SMIT", "COL1", "COL2", + "COL3", "COL4", "CAND", "CBRA", "COL6", "TRE1", "TRE2", "ELEC", "CEYE", "FSKU", + "COL5", "TBLU", "TGRN", "TRED", "SMBT", "SMGT", "SMRT", "HDB1", "HDB2", "HDB3", + "HDB4", "HDB5", "HDB6", "POB1", "POB2", "BRS1", "TLMP", "TLP2" }; - + void InitSpriteLumps(); - + int getNumSprites(); int getFirstSpriteLump(); - + spritedef_t[] getSprites(); - + spritedef_t getSprite(int index); - + int[] getSpriteWidth(); + int[] getSpriteOffset(); + int[] getSpriteTopOffset(); int getSpriteWidth(int index); + int getSpriteOffset(int index); + int getSpriteTopOffset(int index); void InitSprites(String[] namelist); - -} \ No newline at end of file +} diff --git a/src/rr/IVisSpriteManagement.java b/src/rr/IVisSpriteManagement.java index ebf5d31f..4cf5202a 100644 --- a/src/rr/IVisSpriteManagement.java +++ b/src/rr/IVisSpriteManagement.java @@ -8,16 +8,13 @@ * * @param */ - - public interface IVisSpriteManagement extends ILimitResettable { - + void AddSprites(sector_t sec); - + /** Cache the sprite manager, if possible */ - void cacheSpriteManager(ISpriteManager SM); - + void SortVisSprites(); int getNumVisSprites(); @@ -25,5 +22,5 @@ public interface IVisSpriteManagement extends ILimitResettable { vissprite_t[] getVisSprites(); void ClearSprites(); - + } diff --git a/src/rr/MultiPatchSynthesizer.java b/src/rr/MultiPatchSynthesizer.java index 2b875507..5a678bca 100644 --- a/src/rr/MultiPatchSynthesizer.java +++ b/src/rr/MultiPatchSynthesizer.java @@ -13,141 +13,139 @@ * @author velktron * */ - public class MultiPatchSynthesizer { - static class PixelRange { + public PixelRange(int start, int end) { - this.start=start; - this.end=end; + this.start = start; + this.end = end; } - - public int getLength(){ - return (end-start+1); + + public int getLength() { + return (end - start + 1); } - + public int start; public int end; } - - public static patch_t synthesizePatchFromFlat(String name,byte[] flat, int width, int height){ - - byte[] expected=new byte[width *height]; - byte[][] pixels=new byte[width][height]; - boolean[][] solid=new boolean[width][height]; - + + public static patch_t synthesizePatchFromFlat(String name, byte[] flat, int width, int height) { + + byte[] expected = new byte[width * height]; + byte[][] pixels = new byte[width][height]; + boolean[][] solid = new boolean[width][height]; + // Copy as much data as possible. - System.arraycopy(flat,0,expected,0,Math.min(flat.length,expected.length)); + System.arraycopy(flat, 0, expected, 0, Math.min(flat.length, expected.length)); - for (int i=0;i ranges=new ArrayList(); - + public static column_t getColumnStream(byte[] pixels, boolean[] solid, int height) { + + column_t result = new column_t(); + int start = -1; + int end = -1; + + List ranges = new ArrayList<>(); + // Scan column for continuous pixel ranges - for (int i=0;i 1-1 - } + if (!solid[i] && start != -1 && end == -1) { + end = i - 1; // Single-pixel runs would be e.g. 1-2 -> 1-1 + } - if (start!=-1 && end!=-1){ + if (start != -1 && end != -1) { // Range complete. - ranges.add(new PixelRange(start,end)); - start=end=-1; // reset start/end + ranges.add(new PixelRange(start, end)); + start = end = -1; // reset start/end } } - + // There should be at least an empty post - if (ranges.size()==0){ - ranges.add(new PixelRange(0,-1)); + if (ranges.isEmpty()) { + ranges.add(new PixelRange(0, -1)); } - + // Ideal for this use, since we don't know how big the patch is going to be a-priori - ByteArrayOutputStream file=new ByteArrayOutputStream(); - int topdelta=0; - int n=ranges.size(); - short topdeltas[]=new short[n]; - int postofs[]=new int[n]; - short postlens[]=new short[n]; - + ByteArrayOutputStream file = new ByteArrayOutputStream(); + int topdelta = 0; + int n = ranges.size(); + short topdeltas[] = new short[n]; + int postofs[] = new int[n]; + short postlens[] = new short[n]; + + for (int i = 0; i < n; i++) { + PixelRange pr = ranges.get(i); + topdelta = pr.start; // cumulative top delta - - for (int i=0;i implements IPlaneDrawer { - - private static final boolean DEBUG2=false; +public abstract class PlaneDrawer implements IPlaneDrawer { + private static final boolean DEBUG2 = false; protected final boolean RANGECHECK = false; - + // // spanstart holds the start of a plane span // initialized to 0 at start @@ -37,10 +36,10 @@ public abstract class PlaneDrawer implements IPlaneDrawer { /** To treat as fixed_t */ protected int[] cacheddistance, cachedxstep, cachedystep; - protected final ViewVars view; + protected final ViewVars view; protected final SegVars seg_vars; - protected final SpanVars dsvars; + protected final SpanVars dsvars; /** The visplane data. Set separately. For threads, use the same for * everyone. */ @@ -49,22 +48,21 @@ public abstract class PlaneDrawer implements IPlaneDrawer { protected final TextureManager TexMan; protected final IDoomSystem I; protected final VideoScale vs; - - - protected PlaneDrawer(DoomMain DOOM, SceneRenderer R){ - this.view=R.getView(); - this.vpvars=R.getVPVars(); - this.dsvars=R.getDSVars(); - this.seg_vars=R.getSegVars(); - this.colormap=R.getColorMap(); - this.TexMan=R.getTextureManager(); - this.I=R.getDoomSystem(); + + protected PlaneDrawer(DoomMain DOOM, SceneRenderer R) { + this.view = R.getView(); + this.vpvars = R.getVPVars(); + this.dsvars = R.getDSVars(); + this.seg_vars = R.getSegVars(); + this.colormap = R.getColorMap(); + this.TexMan = R.getTextureManager(); + this.I = R.getDoomSystem(); this.vs = DOOM.vs; // Pre-scale stuff. spanstart = new int[vs.getScreenHeight()]; spanstop = new int[vs.getScreenHeight()]; - distscale = new int[vs.getScreenWidth()]; + distscale = new int[vs.getScreenWidth()]; cacheddistance = new int[vs.getScreenHeight()]; cachedxstep = new int[vs.getScreenHeight()]; cachedystep = new int[vs.getScreenHeight()]; @@ -87,7 +85,6 @@ protected PlaneDrawer(DoomMain DOOM, SceneRenderer R){ * * BASIC PRIMITIVE */ - public void MapPlane(int y, int x1, int x2) { // MAES: angle_t int angle; @@ -97,7 +94,7 @@ public void MapPlane(int y, int x1, int x2) { int index; if (RANGECHECK) { - rangeCheck(x1,x2,y); + rangeCheck(x1, x2, y); } if (planeheight != vpvars.cachedheight[y]) { @@ -116,13 +113,14 @@ public void MapPlane(int y, int x1, int x2) { dsvars.ds_xfrac = view.x + FixedMul(finecosine[angle], length); dsvars.ds_yfrac = -view.y - FixedMul(finesine[angle], length); - if (colormap.fixedcolormap != null) + if (colormap.fixedcolormap != null) { dsvars.ds_colormap = colormap.fixedcolormap; - else { + } else { index = distance >>> colormap.lightZShift(); - if (index >= colormap.maxLightZ()) + if (index >= colormap.maxLightZ()) { index = colormap.maxLightZ() - 1; + } dsvars.ds_colormap = planezlight[index]; } @@ -135,12 +133,12 @@ public void MapPlane(int y, int x1, int x2) { dsvars.spanfunc.invoke(); } - protected final void rangeCheck(int x1,int x2,int y) { - if (x2 < x1 || x1 < 0 || x2 >= view.width || y > view.height) - I.Error("%s: %d, %d at %d",this.getClass().getName(), x1, x2, y); + protected final void rangeCheck(int x1, int x2, int y) { + if (x2 < x1 || x1 < 0 || x2 >= view.width || y > view.height) { + I.Error("%s: %d, %d at %d", this.getClass().getName(), x1, x2, y); } - - + } + /** * R_MakeSpans * @@ -162,7 +160,6 @@ protected final void rangeCheck(int x1,int x2,int y) { * Bottom-right y coord ? * */ - protected void MakeSpans(int x, int t1, int b1, int t2, int b2) { // If t1 = [sentinel value] then this part won't be executed. @@ -187,7 +184,6 @@ protected void MakeSpans(int x, int t1, int b1, int t2, int b2) { // So...if t1 for some reason b2 > b1, we decrease b2 AND store the // current x // at spanstart [t2] :-S - while (b2 > b1 && b2 >= t2) { // System.out.println("Decreasing b2"); spanstart[b2] = x; @@ -198,40 +194,39 @@ protected void MakeSpans(int x, int t1, int b1, int t2, int b2) { /** * R_InitPlanes Only at game startup. */ - @Override public void InitPlanes() { // Doh! } - protected final void rangeCheckErrors(){ - if (seg_vars.ds_p > seg_vars.MAXDRAWSEGS) + protected final void rangeCheckErrors() { + if (seg_vars.ds_p > seg_vars.MAXDRAWSEGS) { I.Error("R_DrawPlanes: drawsegs overflow (%d)", seg_vars.ds_p); + } - if (vpvars.lastvisplane > vpvars.MAXVISPLANES) + if (vpvars.lastvisplane > vpvars.MAXVISPLANES) { I.Error(" R_DrawPlanes: visplane overflow (%d)", - vpvars.lastvisplane); + vpvars.lastvisplane); + } - if (vpvars.lastopening > vpvars.MAXOPENINGS) + if (vpvars.lastopening > vpvars.MAXOPENINGS) { I.Error("R_DrawPlanes: opening overflow (%d)", vpvars.lastopening); + } } /** Default implementation which DOES NOTHING. MUST OVERRIDE */ - - public void DrawPlanes(){ - + public void DrawPlanes() { + } - - public void sync(){ + + public void sync() { // Nothing required if serial. } - - /////////////// VARIOUS BORING GETTERS //////////////////// - + /////////////// VARIOUS BORING GETTERS //////////////////// @Override public int[] getDistScale() { return distscale; } - + } diff --git a/src/rr/RendererState.java b/src/rr/RendererState.java index 1bb46c69..1b634763 100644 --- a/src/rr/RendererState.java +++ b/src/rr/RendererState.java @@ -36,6 +36,8 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; import static m.BBox.BOXBOTTOM; import static m.BBox.BOXLEFT; import static m.BBox.BOXRIGHT; @@ -48,6 +50,7 @@ import static m.fixed_t.FixedDiv; import static m.fixed_t.FixedMul; import mochadoom.Engine; +import mochadoom.Loggers; import static p.ActiveStates.P_MobjThinker; import p.mobj_t; import rr.drawfuns.ColFuncs; @@ -55,7 +58,9 @@ import rr.drawfuns.DoomColumnFunction; import rr.drawfuns.DoomSpanFunction; import rr.drawfuns.SpanVars; -import static rr.line_t.*; +import static rr.line_t.ML_DONTPEGBOTTOM; +import static rr.line_t.ML_DONTPEGTOP; +import static rr.line_t.ML_MAPPED; import utils.C2JUtils; import static utils.GenericCopy.malloc; import static v.DoomGraphicSystem.V_NOSCALEOFFSET; @@ -63,7 +68,8 @@ import static v.DoomGraphicSystem.V_NOSCALESTART; import v.graphics.Palettes; import v.renderers.DoomScreen; -import static v.renderers.DoomScreen.*; +import static v.renderers.DoomScreen.BG; +import static v.renderers.DoomScreen.FG; import v.tables.BlurryTable; import v.tables.LightsAndColors; import w.IWadLoader; @@ -81,6 +87,8 @@ */ public abstract class RendererState implements SceneRenderer, ILimitResettable { + private static final Logger LOGGER = Loggers.getLogger(RendererState.class.getName()); + protected static final boolean DEBUG = false; protected static final boolean DEBUG2 = false; @@ -188,8 +196,8 @@ public void SetupFrame(player_t player) { int yslope[] = vp_vars.yslope; for (int i = 0; i < view.height; i++) { yslope[i] = FixedDiv( - (view.width << view.detailshift) / 2 * FRACUNIT, - Math.abs(((i - view.centery) << FRACBITS) + FRACUNIT / 2) + (view.width << view.detailshift) / 2 * FRACUNIT, + Math.abs(((i - view.centery) << FRACBITS) + FRACUNIT / 2) ); } @@ -371,7 +379,7 @@ private void ClipSolidWallSegment(int first, int last) { while (last >= solidsegs[(next + 1)].first - 1) { // There is a fragment between two posts. MySegs.StoreWallRange(solidsegs[next].last + 1, - solidsegs[next + 1].first - 1); + solidsegs[next + 1].first - 1); next++; if (last <= solidsegs[next].last) { @@ -471,7 +479,7 @@ private void ClipPassWallSegment(int first, int last) { while (last >= solidsegs[start + 1].first - 1) { // There is a fragment between two posts. MySegs.StoreWallRange(solidsegs[start].last + 1, - solidsegs[start + 1].first - 1); + solidsegs[start + 1].first - 1); start++; // if (startptr>=MAXSEGS-2) return; // start=solidsegs[startptr]; @@ -510,7 +518,7 @@ public void ClearClipSegs() { */ private void AddLine(seg_t line) { if (DEBUG) { - System.out.println("Entered AddLine for " + line); + LOGGER.log(Level.FINE, String.format("Entered AddLine for %s", String.valueOf(line))); } int x1; int x2; @@ -586,20 +594,20 @@ private void AddLine(seg_t line) { // Single sided line? if (backsector == null) { if (DEBUG) { - System.out .println("Entering ClipSolidWallSegment SS with params " + x1 + " " + (x2 - 1)); + LOGGER.log(Level.FINE, String.format("Entering ClipSolidWallSegment SS with params %d %d", x1, (x2 - 1))); } ClipSolidWallSegment(x1, x2 - 1); // to clipsolid if (DEBUG) { - System.out.println("Exiting ClipSolidWallSegment"); + LOGGER.log(Level.FINE, "Exiting ClipSolidWallSegment"); } return; } // Closed door. if (backsector.ceilingheight <= frontsector.floorheight - || backsector.floorheight >= frontsector.ceilingheight) { + || backsector.floorheight >= frontsector.ceilingheight) { if (DEBUG) { - System.out.println("Entering ClipSolidWallSegment Closed door with params " + x1 + " " + (x2 - 1)); + LOGGER.log(Level.FINE, String.format("Entering ClipSolidWallSegment Closed door with params %d %d", x1, (x2 - 1))); } ClipSolidWallSegment(x1, x2 - 1); // to clipsolid @@ -608,9 +616,9 @@ private void AddLine(seg_t line) { // Window. This includes same-level floors with different textures if (backsector.ceilingheight != frontsector.ceilingheight - || backsector.floorheight != frontsector.floorheight) { + || backsector.floorheight != frontsector.floorheight) { if (DEBUG) { - System.out.println("Entering ClipSolidWallSegment window with params " + x1 + " " + (x2 - 1)); + LOGGER.log(Level.FINE, String.format("Entering ClipSolidWallSegment window with params %d %d", x1, (x2 - 1))); } ClipPassWallSegment(x1, x2 - 1); // to clippass return; @@ -622,9 +630,9 @@ private void AddLine(seg_t line) { // identical light levels on both sides, // and no middle texture. if (backsector.ceilingpic == frontsector.ceilingpic - && backsector.floorpic == frontsector.floorpic - && backsector.lightlevel == frontsector.lightlevel - && curline.sidedef.midtexture == 0) { + && backsector.floorpic == frontsector.floorpic + && backsector.lightlevel == frontsector.lightlevel + && curline.sidedef.midtexture == 0) { return; } @@ -635,7 +643,7 @@ private void AddLine(seg_t line) { // Fucking GOTOs.... ClipPassWallSegment(x1, x2 - 1); // to clippass if (DEBUG) { - System.out.println("Exiting AddLine for " + line); + LOGGER.log(Level.FINE, String.format("Exiting AddLine for %s", String.valueOf(line))); } } @@ -791,7 +799,7 @@ public boolean CheckBBox(int[] bspcoord) { */ private void Subsector(int num) { if (DEBUG) { - System.out.println("\t\tSubSector " + num + " to render"); + LOGGER.log(Level.FINE, String.format("SubSector %d to render", num)); } int count; int line; // pointer into a list of segs instead of seg_t @@ -800,7 +808,7 @@ private void Subsector(int num) { if (RANGECHECK) { if (num >= DOOM.levelLoader.numsubsectors) { DOOM.doomSystem.Error("R_Subsector: ss %d with numss = %d", num, - DOOM.levelLoader.numsubsectors); + DOOM.levelLoader.numsubsectors); } } @@ -809,19 +817,19 @@ private void Subsector(int num) { frontsector = sub.sector; if (DEBUG) { - System.out.println("Frontsector to render :" + frontsector); + LOGGER.log(Level.FINE, String.format("Frontsector to render: %s", String.valueOf(frontsector))); } count = sub.numlines; // line = LL.segs[sub.firstline]; line = sub.firstline; if (DEBUG) { - System.out.println("Trying to find an existing FLOOR visplane..."); + LOGGER.log(Level.FINE, "Trying to find an existing FLOOR visplane..."); } if (frontsector.floorheight < view.z) { vp_vars.floorplane - = vp_vars.FindPlane(frontsector.floorheight, - frontsector.floorpic, frontsector.lightlevel); + = vp_vars.FindPlane(frontsector.floorheight, + frontsector.floorpic, frontsector.lightlevel); } else { // FIXME: unclear what would happen with a null visplane used // It's never checked explicitly for either condition, just @@ -831,10 +839,10 @@ private void Subsector(int num) { // System.out.println("Trying to find an existing CEILING visplane..."); if (frontsector.ceilingheight > view.z - || frontsector.ceilingpic == TexMan.getSkyFlatNum()) { + || frontsector.ceilingpic == TexMan.getSkyFlatNum()) { vp_vars.ceilingplane - = vp_vars.FindPlane(frontsector.ceilingheight, - frontsector.ceilingpic, frontsector.lightlevel); + = vp_vars.FindPlane(frontsector.ceilingheight, + frontsector.ceilingpic, frontsector.lightlevel); } else { vp_vars.ceilingplane = -1; // In lieu of NULL. Will bomb if // actually @@ -844,14 +852,14 @@ private void Subsector(int num) { VIS.AddSprites(frontsector); if (DEBUG) { - System.out.println("Enter Addline for SubSector " + num + " count " + count); + LOGGER.log(Level.FINE, String.format("Enter Addline for SubSector %d count %d", num, count)); } while (count-- > 0) { AddLine(DOOM.levelLoader.segs[line]); line++; } if (DEBUG) { - System.out.println("Exit Addline for SubSector " + num); + LOGGER.log(Level.FINE, String.format("Exit Addline for SubSector %d", num)); } } @@ -861,7 +869,7 @@ private void Subsector(int num) { */ public void RenderBSPNode(int bspnum) { if (DEBUG) { - System.out.println("Processing BSP Node " + bspnum); + LOGGER.log(Level.FINE, String.format("Processing BSP Node %d", bspnum)); } node_t bsp; @@ -871,7 +879,7 @@ public void RenderBSPNode(int bspnum) { // SubSector. if (C2JUtils.flags(bspnum, NF_SUBSECTOR)) { if (DEBUG) { - System.out.println("Subsector found."); + LOGGER.log(Level.FINE, "Subsector found."); } if (bspnum == -1) { Subsector(0); @@ -886,26 +894,26 @@ public void RenderBSPNode(int bspnum) { // Decide which side the view point is on. side = bsp.PointOnSide(view.x, view.y); if (DEBUG) { - System.out.println("\tView side: " + side); + LOGGER.log(Level.FINE, String.format("View side: %d", side)); } // Recursively divide front space. if (DEBUG) { - System.out.println("\tEnter Front space of " + bspnum); + LOGGER.log(Level.FINE, String.format("Enter Front space of %d", bspnum)); } RenderBSPNode(bsp.children[side]); if (DEBUG) { - System.out.println("\tReturn Front space of " + bspnum); + LOGGER.log(Level.FINE, String.format("Return Front space of %d", bspnum)); } // Possibly divide back space. if (CheckBBox(bsp.bbox[side ^ 1].bbox)) { if (DEBUG) { - System.out.println("\tEnter Back space of " + bspnum); + LOGGER.log(Level.FINE, String.format("Enter Back space of %d", bspnum)); } RenderBSPNode(bsp.children[side ^ 1]); if (DEBUG) { - System.out.println("\tReturn Back space of " + bspnum); + LOGGER.log(Level.FINE, String.format("Return Back space of %d", bspnum)); } } } @@ -996,7 +1004,7 @@ public short[] getCeilingClip() { * fixed_t */ protected int rw_offset, rw_distance, rw_scale, rw_scalestep, - rw_midtexturemid, rw_toptexturemid, rw_bottomtexturemid; + rw_midtexturemid, rw_toptexturemid, rw_bottomtexturemid; @Override public void resetLimits() { @@ -1026,7 +1034,7 @@ public void sync() { public void StoreWallRange(int start, int stop) { if (DEBUG2) { - System.out.println("\t\t\t\tStorewallrange called between " + start + " and " + stop); + LOGGER.log(Level.FINER, String.format("Storewallrange called between %d and %d", start, stop)); } int hyp; // fixed_t @@ -1092,14 +1100,14 @@ public void StoreWallRange(int start, int stop) { // calculate scale at both ends and step // this is the ONLY place where rw_scale is set. seg.scale1 - = rw_scale - = ScaleFromGlobalAngle((view.angle + view.xtoviewangle[start])); + = rw_scale + = ScaleFromGlobalAngle((view.angle + view.xtoviewangle[start])); if (stop > start) { seg.scale2 - = ScaleFromGlobalAngle(view.angle + view.xtoviewangle[stop]); + = ScaleFromGlobalAngle(view.angle + view.xtoviewangle[stop]); seg.scalestep - = rw_scalestep = (seg.scale2 - rw_scale) / (stop - start); + = rw_scalestep = (seg.scale2 - rw_scale) / (stop - start); } else { // UNUSED: try to fix the stretched line bug /* @@ -1125,13 +1133,13 @@ public void StoreWallRange(int start, int stop) { if (MyBSP.backsector == null) { // single sided line midtexture - = TexMan.getTextureTranslation(MyBSP.sidedef.midtexture); + = TexMan.getTextureTranslation(MyBSP.sidedef.midtexture); // a single sided line is terminal, so it must mark ends markfloor = markceiling = true; if ((MyBSP.linedef.flags & ML_DONTPEGBOTTOM) != 0) { vtop - = MyBSP.frontsector.floorheight - + TexMan.getTextureheight(MyBSP.sidedef.midtexture); + = MyBSP.frontsector.floorheight + + TexMan.getTextureheight(MyBSP.sidedef.midtexture); // bottom of texture at bottom rw_midtexturemid = vtop - view.z; } else { @@ -1186,20 +1194,20 @@ public void StoreWallRange(int start, int stop) { // hack to allow height changes in outdoor areas if (MyBSP.frontsector.ceilingpic == TexMan.getSkyFlatNum() - && MyBSP.backsector.ceilingpic == TexMan - .getSkyFlatNum()) { + && MyBSP.backsector.ceilingpic == TexMan + .getSkyFlatNum()) { worldtop = worldhigh; } markfloor = worldlow != worldbottom - || MyBSP.backsector.floorpic != MyBSP.frontsector.floorpic - || MyBSP.backsector.lightlevel != MyBSP.frontsector.lightlevel; // same plane on both sides + || MyBSP.backsector.floorpic != MyBSP.frontsector.floorpic + || MyBSP.backsector.lightlevel != MyBSP.frontsector.lightlevel; // same plane on both sides markceiling = worldhigh != worldtop - || MyBSP.backsector.ceilingpic != MyBSP.frontsector.ceilingpic - || MyBSP.backsector.lightlevel != MyBSP.frontsector.lightlevel; // same plane on both sides + || MyBSP.backsector.ceilingpic != MyBSP.frontsector.ceilingpic + || MyBSP.backsector.lightlevel != MyBSP.frontsector.lightlevel; // same plane on both sides if (MyBSP.backsector.ceilingheight <= MyBSP.frontsector.floorheight - || MyBSP.backsector.floorheight >= MyBSP.frontsector.ceilingheight) { + || MyBSP.backsector.floorheight >= MyBSP.frontsector.ceilingheight) { // closed door markceiling = markfloor = true; } @@ -1207,14 +1215,14 @@ public void StoreWallRange(int start, int stop) { if (worldhigh < worldtop) { // top texture toptexture - = TexMan.getTextureTranslation(MyBSP.sidedef.toptexture); + = TexMan.getTextureTranslation(MyBSP.sidedef.toptexture); if ((MyBSP.linedef.flags & ML_DONTPEGTOP) != 0) { // top of texture at top rw_toptexturemid = worldtop; } else { vtop - = MyBSP.backsector.ceilingheight - + TexMan.getTextureheight(MyBSP.sidedef.toptexture); + = MyBSP.backsector.ceilingheight + + TexMan.getTextureheight(MyBSP.sidedef.toptexture); // bottom of texture rw_toptexturemid = vtop - view.z; @@ -1223,7 +1231,7 @@ public void StoreWallRange(int start, int stop) { if (worldlow > worldbottom) { // bottom texture bottomtexture - = TexMan.getTextureTranslation(MyBSP.sidedef.bottomtexture); + = TexMan.getTextureTranslation(MyBSP.sidedef.bottomtexture); if ((MyBSP.linedef.flags & ML_DONTPEGBOTTOM) != 0) { // bottom of texture at bottom @@ -1244,14 +1252,14 @@ public void StoreWallRange(int start, int stop) { seg_vars.maskedtexturecol = vp_vars.openings; seg_vars.pmaskedtexturecol = vp_vars.lastopening - rw_x; seg.setMaskedTextureCol(seg_vars.maskedtexturecol, - seg_vars.pmaskedtexturecol); + seg_vars.pmaskedtexturecol); vp_vars.lastopening += rw_stopx - rw_x; } } // calculate rw_offset (only needed for textured lines) segtextured - = (((midtexture | toptexture | bottomtexture) != 0) | maskedtexture); + = (((midtexture | toptexture | bottomtexture) != 0) | maskedtexture); if (segtextured) { offsetangle = addAngles(rw_normalangle, -rw_angle1); @@ -1288,8 +1296,8 @@ public void StoreWallRange(int start, int stop) { // OPTIMIZE: get rid of LIGHTSEGSHIFT globally if (colormaps.fixedcolormap == null) { lightnum - = (MyBSP.frontsector.lightlevel >> colormaps.lightSegShift()) - + colormaps.extralight; + = (MyBSP.frontsector.lightlevel >> colormaps.lightSegShift()) + + colormaps.extralight; if (MyBSP.curline.v1y == MyBSP.curline.v2y) { lightnum--; @@ -1301,7 +1309,7 @@ public void StoreWallRange(int start, int stop) { colormaps.walllights = colormaps.scalelight[0]; } else if (lightnum >= colormaps.lightLevels()) { colormaps.walllights - = colormaps.scalelight[colormaps.lightLevels() - 1]; + = colormaps.scalelight[colormaps.lightLevels() - 1]; } else { colormaps.walllights = colormaps.scalelight[lightnum]; } @@ -1317,7 +1325,7 @@ public void StoreWallRange(int start, int stop) { } if (MyBSP.frontsector.ceilingheight <= view.z - && MyBSP.frontsector.ceilingpic != TexMan.getSkyFlatNum()) { + && MyBSP.frontsector.ceilingpic != TexMan.getSkyFlatNum()) { // below view plane markceiling = false; } @@ -1331,7 +1339,7 @@ public void StoreWallRange(int start, int stop) { bottomstep = -FixedMul(rw_scalestep, worldbottom); bottomfrac - = (view.centeryfrac >> 4) - FixedMul(worldbottom, rw_scale); + = (view.centeryfrac >> 4) - FixedMul(worldbottom, rw_scale); if (MyBSP.backsector != null) { worldhigh >>= 4; @@ -1339,13 +1347,13 @@ public void StoreWallRange(int start, int stop) { if (worldhigh < worldtop) { pixhigh - = (view.centeryfrac >> 4) - FixedMul(worldhigh, rw_scale); + = (view.centeryfrac >> 4) - FixedMul(worldhigh, rw_scale); pixhighstep = -FixedMul(rw_scalestep, worldhigh); } if (worldlow > worldbottom) { pixlow - = (view.centeryfrac >> 4) - FixedMul(worldlow, rw_scale); + = (view.centeryfrac >> 4) - FixedMul(worldlow, rw_scale); pixlowstep = -FixedMul(rw_scalestep, worldlow); } } @@ -1354,13 +1362,13 @@ public void StoreWallRange(int start, int stop) { if (markceiling) { // System.out.println("Markceiling"); vp_vars.ceilingplane - = vp_vars.CheckPlane(vp_vars.ceilingplane, rw_x, rw_stopx - 1); + = vp_vars.CheckPlane(vp_vars.ceilingplane, rw_x, rw_stopx - 1); } if (markfloor) { // System.out.println("Markfloor"); vp_vars.floorplane - = vp_vars.CheckPlane(vp_vars.floorplane, rw_x, rw_stopx - 1); + = vp_vars.CheckPlane(vp_vars.floorplane, rw_x, rw_stopx - 1); } RenderSegLoop(); @@ -1368,11 +1376,11 @@ public void StoreWallRange(int start, int stop) { // After rendering is actually performed, clipping is set. // save sprite clipping info ... no top clipping? if ((C2JUtils.flags(seg.silhouette, SIL_TOP) || maskedtexture) - && seg.nullSprTopClip()) { + && seg.nullSprTopClip()) { // memcpy (lastopening, ceilingclip+start, 2*(rw_stopx-start)); System.arraycopy(ceilingclip, start, vp_vars.openings, - vp_vars.lastopening, rw_stopx - start); + vp_vars.lastopening, rw_stopx - start); seg.setSprTopClip(vp_vars.openings, vp_vars.lastopening - start); // seg.setSprTopClipPointer(); @@ -1380,12 +1388,12 @@ public void StoreWallRange(int start, int stop) { } // no floor clipping? if ((C2JUtils.flags(seg.silhouette, SIL_BOTTOM) || maskedtexture) - && seg.nullSprBottomClip()) { + && seg.nullSprBottomClip()) { // memcpy (lastopening, floorclip+start, 2*(rw_stopx-start)); System.arraycopy(floorclip, start, vp_vars.openings, - vp_vars.lastopening, rw_stopx - start); + vp_vars.lastopening, rw_stopx - start); seg.setSprBottomClip(vp_vars.openings, vp_vars.lastopening - - start); + - start); vp_vars.lastopening += rw_stopx - start; } @@ -1440,9 +1448,9 @@ protected void RenderSegLoop() { if (top <= bottom) { vp_vars.visplanes[vp_vars.ceilingplane].setTop(rw_x, - (char) top); + (char) top); vp_vars.visplanes[vp_vars.ceilingplane].setBottom(rw_x, - (char) bottom); + (char) bottom); } } @@ -1461,9 +1469,9 @@ protected void RenderSegLoop() { } if (top <= bottom) { vp_vars.visplanes[vp_vars.floorplane].setTop(rw_x, - (char) top); + (char) top); vp_vars.visplanes[vp_vars.floorplane].setBottom(rw_x, - (char) bottom); + (char) bottom); } } @@ -1479,8 +1487,8 @@ protected void RenderSegLoop() { // doesn't hold anymore, // not even if accounting for overflow. angle - = Tables.toBAMIndex(rw_centerangle - + (int) view.xtoviewangle[rw_x]); + = Tables.toBAMIndex(rw_centerangle + + (int) view.xtoviewangle[rw_x]); // FIXME: We are accessing finetangent here, the code seems // pretty confident in that angle won't exceed 4K no matter @@ -1494,7 +1502,7 @@ protected void RenderSegLoop() { // with 0x1FFF if you're so inclined. // FIXED by allowing overflow. See Tables for details. texturecolumn - = rw_offset - FixedMul(finetangent[angle], rw_distance); + = rw_offset - FixedMul(finetangent[angle], rw_distance); texturecolumn >>= FRACBITS; // calculate lighting index = rw_scale >> colormaps.lightScaleShift(); @@ -1514,11 +1522,11 @@ protected void RenderSegLoop() { dcvars.dc_yl = yl; dcvars.dc_yh = yh; dcvars.dc_texheight - = TexMan.getTextureheight(midtexture) >> FRACBITS; // killough + = TexMan.getTextureheight(midtexture) >> FRACBITS; // killough dcvars.dc_texturemid = rw_midtexturemid; dcvars.dc_source_ofs = 0; dcvars.dc_source - = TexMan.GetCachedColumn(midtexture, texturecolumn); + = TexMan.GetCachedColumn(midtexture, texturecolumn); CompleteColumn(); ceilingclip[rw_x] = (short) view.height; floorclip[rw_x] = -1; @@ -1541,7 +1549,7 @@ protected void RenderSegLoop() { dcvars.dc_source = TexMan.GetCachedColumn(toptexture, texturecolumn); dcvars.dc_source_ofs = 0; if (dcvars.dc_colormap == null) { - System.out.println("Two-sided"); + LOGGER.log(Level.FINE, "Two-sided"); } CompleteColumn(); ceilingclip[rw_x] = (short) mid; @@ -1692,9 +1700,13 @@ public void setGlobalAngle(long angle) { } protected interface IPlaneDrawer { + void InitPlanes(); + void MapPlane(int y, int x1, int x2); + void DrawPlanes(); + int[] getDistScale(); /** @@ -1704,13 +1716,21 @@ protected interface IPlaneDrawer { } protected interface ISegDrawer extends ILimitResettable { + void ClearClips(); + short[] getBLANKCEILINGCLIP(); + short[] getBLANKFLOORCLIP(); + short[] getFloorClip(); + short[] getCeilingClip(); + void ExecuteSetViewSize(int viewwidth); + void setGlobalAngle(long angle1); + void StoreWallRange(int first, int last); /** @@ -1741,7 +1761,7 @@ protected class Planes extends PlaneDrawer { @Override public void DrawPlanes() { if (DEBUG) { - System.out.println(" >>>>>>>>>>>>>>>>>>>>> DrawPlanes: " + vp_vars.lastvisplane); + LOGGER.log(Level.FINE, String.format("DrawPlanes: %d", vp_vars.lastvisplane)); } visplane_t pln; // visplane_t int light; @@ -1756,7 +1776,7 @@ public void DrawPlanes() { for (int pl = 0; pl < vp_vars.lastvisplane; pl++) { pln = vp_vars.visplanes[pl]; if (DEBUG2) { - System.out.println(pln); + LOGGER.log(Level.FINER, String.valueOf(pln)); } if (pln.minx > pln.maxx) { @@ -1769,9 +1789,9 @@ public void DrawPlanes() { // being drawn, after all, are they? int skytexture = TexMan.getSkyTexture(); skydcvars.dc_texheight - = TexMan.getTextureheight(skytexture) >> FRACBITS; + = TexMan.getTextureheight(skytexture) >> FRACBITS; skydcvars.dc_iscale - = vpvars.getSkyScale() >> view.detailshift; + = vpvars.getSkyScale() >> view.detailshift; /** * Sky is allways drawn full bright, i.e. colormaps[0] is @@ -1792,12 +1812,12 @@ public void DrawPlanes() { if (skydcvars.dc_yl <= skydcvars.dc_yh) { angle - = (int) (addAngles(view.angle, view.xtoviewangle[x]) >>> ANGLETOSKYSHIFT); + = (int) (addAngles(view.angle, view.xtoviewangle[x]) >>> ANGLETOSKYSHIFT); skydcvars.dc_x = x; // Optimized: texheight is going to be the same // during normal skies drawing...right? skydcvars.dc_source - = TexMan.GetCachedColumn(skytexture, angle); + = TexMan.GetCachedColumn(skytexture, angle); colfunc.sky.invoke(); } } @@ -2228,7 +2248,7 @@ public void ExecuteSetViewSize() { } skydcvars.viewheight - = maskedcvars.viewheight = dcvars.viewheight = view.height; + = maskedcvars.viewheight = dcvars.viewheight = view.height; view.detailshift = setdetail; view.width = view.scaledwidth >> view.detailshift; @@ -2299,7 +2319,7 @@ public void ExecuteSetViewSize() { startmap = ((colormaps.lightLevels() - colormaps.lightBright() - i) * 2) * colormaps.numColorMaps() / colormaps.lightLevels(); for (int j = 0; j < colormaps.maxLightScale(); j++) { level - = startmap - j / DISTMAP; + = startmap - j / DISTMAP; if (level < 0) { level = 0; } @@ -2312,7 +2332,7 @@ public void ExecuteSetViewSize() { MySegs.ExecuteSetViewSize(view.width); } - + private final Rectangle backScreenRect = new Rectangle(); private final Rectangle tilePatchRect = new Rectangle(); @@ -2353,7 +2373,7 @@ public void FillBackScreen() { /* This is a flat we're reading here */ src = DOOM.wadLoader.CacheLumpName(name, PU_CACHE, flat_t.class); dest = BG; - + /** * TODO: cache it? * This part actually draws the border itself, without bevels @@ -2366,7 +2386,8 @@ public void FillBackScreen() { * * @SourceCode.Compatible */ - Tiling: { + Tiling: + { this.backScreenRect.setBounds(0, 0, DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight() - DOOM.statusBar.getHeight()); this.tilePatchRect.setBounds(0, 0, 64, 64); V block = DOOM.graphicSystem.convertPalettedBlock(src.data); @@ -2377,7 +2398,7 @@ public void FillBackScreen() { } DOOM.graphicSystem.TileScreenArea(dest, backScreenRect, block, tilePatchRect); } - + final int scaleFlags = V_NOSCALESTART | (scaleSetting ? 0 : V_NOSCALEOFFSET | V_NOSCALEPATCH); final int stepX = scaleSetting ? DOOM.graphicSystem.getScalingX() << 3 : 8; final int stepY = scaleSetting ? DOOM.graphicSystem.getScalingY() << 3 : 8; @@ -2413,7 +2434,7 @@ public void FillBackScreen() { // Bottom-left patch = DOOM.wadLoader.CachePatchName("BRDR_BL", PU_CACHE); DOOM.graphicSystem.DrawPatchScaled(BG, patch, DOOM.vs, view.windowx - stepX, view.windowy + view.height, scaleFlags); - + // Bottom-right. patch = DOOM.wadLoader.CachePatchName("BRDR_BR", PU_CACHE); DOOM.graphicSystem.DrawPatchScaled(BG, patch, DOOM.vs, view.windowx + view.width, view.windowy + view.height, scaleFlags); @@ -2431,32 +2452,33 @@ public void Init() { // DON'T FORGET ABOUT MEEEEEE!!!11!!! this.screen = this.DOOM.graphicSystem.getScreen(FG); - System.out.print("\nR_InitData"); + LOGGER.log(Level.INFO, "R_InitData"); InitData(); // InitPointToAngle (); - System.out.print("\nR_InitPointToAngle"); + LOGGER.log(Level.INFO, "R_InitPointToAngle"); // ds.DM.viewwidth / ds.viewheight / detailLevel are set by the defaults - System.out.print("\nR_InitTables"); + LOGGER.log(Level.INFO, "R_InitTables"); InitTables(); SetViewSize(DOOM.menu.getScreenBlocks(), DOOM.menu.getDetailLevel()); - System.out.print("\nR_InitPlanes"); + LOGGER.log(Level.INFO, "R_InitPlanes"); MyPlanes.InitPlanes(); - System.out.print("\nR_InitLightTables"); + LOGGER.log(Level.INFO, "R_InitLightTables"); InitLightTables(); - System.out.print("\nR_InitSkyMap: " + TexMan.InitSkyMap()); + int initSkyMap = TexMan.InitSkyMap(); + LOGGER.log(Level.INFO, String.format("R_InitSkyMap: %d", initSkyMap)); - System.out.print("\nR_InitTranslationsTables"); + LOGGER.log(Level.INFO, "R_InitTranslationsTables"); InitTranslationTables(); - System.out.print("\nR_InitTranMap: "); + LOGGER.log(Level.INFO, "R_InitTranMap"); R_InitTranMap(0); - System.out.print("\nR_InitDrawingFunctions: "); + LOGGER.log(Level.INFO, "R_InitDrawingFunctions"); R_InitDrawingFunctions(); framecount = 0; @@ -2521,8 +2543,8 @@ protected void InitTextureMapping() { // Calc focallength // so FIELDOFVIEW angles covers vs.getScreenWidth(). focallength - = FixedDiv(view.centerxfrac, finetangent[QUARTERMARK + FIELDOFVIEW - / 2]); + = FixedDiv(view.centerxfrac, finetangent[QUARTERMARK + FIELDOFVIEW + / 2]); for (i = 0; i < FINEANGLES / 2; i++) { if (finetangent[i] > FRACUNIT * 2) { @@ -2609,7 +2631,7 @@ protected void InitLightTables() { } protected static final int TSC = 12; - + /** * number of fixed point digits in * filter percent @@ -2631,19 +2653,21 @@ protected void R_InitTranMap(int progress) { // it. If OK, this trumps even those specified in lumps. DOOM.cVarManager.with(CommandVariable.TRANMAP, 0, (String tranmap) -> { if (C2JUtils.testReadAccess(tranmap)) { - System.out.printf("Translucency map file %s specified in -tranmap arg. Attempting to use...\n", tranmap); + LOGGER.log(Level.INFO, + String.format("Translucency map file %s specified in -tranmap arg. Attempting to use...", tranmap)); main_tranmap = new byte[256 * 256]; // killough 4/11/98 int result = MenuMisc.ReadFile(tranmap, main_tranmap); if (result > 0) { return; } - System.out.print("...failure.\n"); + + LOGGER.log(Level.SEVERE, "R_InitTranMap: translucency map failure"); } }); // Next, if a tranlucency filter map lump is present, use it if (lump != -1) { // Set a pointer to the translucency filter maps. - System.out.print("Translucency map found in lump. Attempting to use..."); + LOGGER.log(Level.INFO, "Translucency map found in lump. Attempting to use..."); // main_tranmap=new byte[256*256]; // killough 4/11/98 main_tranmap = DOOM.wadLoader.CacheLumpNumAsRawBytes(lump, Defines.PU_STATIC); // killough // 4/11/98 @@ -2651,12 +2675,12 @@ protected void R_InitTranMap(int progress) { if (main_tranmap.length >= 0x10000) { return; } - System.out.print("...failure.\n"); // Not good, try something else. + LOGGER.log(Level.SEVERE, "R_InitTranMap: tranlucency filter map failure"); // Not good, try something else. } // A default map file already exists. Try to read it. if (C2JUtils.testReadAccess("tranmap.dat")) { - System.out.print("Translucency map found in default tranmap.dat file. Attempting to use..."); + LOGGER.log(Level.INFO, "Translucency map found in default tranmap.dat file. Attempting to use..."); main_tranmap = new byte[256 * 256]; // killough 4/11/98 int result = MenuMisc.ReadFile("tranmap.dat", main_tranmap); if (result > 0) { @@ -2667,7 +2691,7 @@ protected void R_InitTranMap(int progress) { // Nothing to do, so we must synthesize it from scratch. And, boy, is it // slooow. { // Compose a default transparent filter map based on PLAYPAL. - System.out.print("Computing translucency map from scratch...that's gonna be SLOW..."); + LOGGER.log(Level.INFO, "Computing translucency map from scratch...that's gonna be SLOW..."); byte[] playpal = DOOM.wadLoader.CacheLumpNameAsRawBytes("PLAYPAL", Defines.PU_STATIC); main_tranmap = new byte[256 * 256]; // killough 4/11/98 int[] basepal = new int[3 * 256]; @@ -2710,22 +2734,22 @@ protected void R_InitTranMap(int progress) { main_tranmap[(b << 8) | a] = main_tranmap[(a << 8) | b]; } } - System.out.print("...done\n"); + LOGGER.log(Level.INFO, "R_InitTranMap: done"); if (MenuMisc.WriteFile("tranmap.dat", main_tranmap, - main_tranmap.length)) { - System.out.print("TRANMAP.DAT saved to disk for your convenience! Next time will be faster.\n"); + main_tranmap.length)) { + LOGGER.log(Level.INFO, "TRANMAP.DAT saved to disk for your convenience! Next time will be faster."); } } long b = System.nanoTime(); - System.out.printf("Tranmap %d\n", (b - ta) / 1000000); + LOGGER.log(Level.INFO, String.format("Tranmap %d", (b - ta) / 1000000)); } /** * Mixes two RGB colors. Nuff said */ protected void mixColors(int[] a, int[] b, int[] c, int pa, int pb, - int pc) { + int pc) { c[pc] = (a[pa] + b[pb]) / 2; c[pc + 1] = (a[pa + 1] + b[pb + 1]) / 2; c[pc + 2] = (a[pa + 2] + b[pb + 2]) / 2; @@ -2737,8 +2761,8 @@ protected void mixColors(int[] a, int[] b, int[] c, int pa, int pb, */ protected float colorDistance(int[] a, int[] b, int pa, int pb) { return (float) Math.sqrt((a[pa] - b[pb]) * (a[pa] - b[pb]) - + (a[pa + 1] - b[pb + 1]) * (a[pa + 1] - b[pb + 1]) - + (a[pa + 2] - b[pb + 2]) * (a[pa + 2] - b[pb + 2])); + + (a[pa + 1] - b[pb + 1]) * (a[pa + 1] - b[pb + 1]) + + (a[pa + 2] - b[pb + 2]) * (a[pa + 2] - b[pb + 2])); } /** @@ -2803,21 +2827,21 @@ protected int findMin(float[] a) { */ public void InitData() { try { - System.out.print("\nInit Texture and Flat Manager"); + LOGGER.log(Level.INFO, "Init Texture and Flat Manager"); TexMan = this.DOOM.textureManager; - System.out.print("\nInitTextures"); + LOGGER.log(Level.INFO, "InitTextures"); TexMan.InitTextures(); - System.out.print("\nInitFlats"); + LOGGER.log(Level.INFO, "InitFlats"); TexMan.InitFlats(); - System.out.print("\nInitSprites"); + LOGGER.log(Level.INFO, "InitSprites"); DOOM.spriteManager.InitSpriteLumps(); MyThings.cacheSpriteManager(DOOM.spriteManager); VIS.cacheSpriteManager(DOOM.spriteManager); - System.out.print("\nInitColormaps\t\t"); + LOGGER.log(Level.INFO, "InitColormaps"); InitColormaps(); } catch (IOException e) { - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Error: InitData failure", e); } } @@ -2882,7 +2906,7 @@ protected void InitTranslationTables() { // translationtables = Z_Malloc (256*3+255, PU_STATIC, 0); // translationtables = (byte *)(( (int)translationtables + 255 )& ~255); byte[][] translationtables - = colormaps.translationtables = new byte[TR_COLORS][256]; + = colormaps.translationtables = new byte[TR_COLORS][256]; // translate just the 16 green colors for (i = 0; i < 256; i++) { diff --git a/src/rr/SceneRenderer.java b/src/rr/SceneRenderer.java index 8e0a5655..b3b90c77 100644 --- a/src/rr/SceneRenderer.java +++ b/src/rr/SceneRenderer.java @@ -29,28 +29,47 @@ public interface SceneRenderer { public static final long viewangleoffset = 0; public void Init(); + public void RenderPlayerView(player_t player); + public void ExecuteSetViewSize(); + @R_Draw.C(R_FillBackScreen) public void FillBackScreen(); + public void DrawViewBorder(); + public void SetViewSize(int size, int detaillevel); + public long PointToAngle2(int x1, int y1, int x2, int y2); + public void PreCacheThinkers(); + public int getValidCount(); + public void increaseValidCount(int amount); + public boolean isFullHeight(); + public void resetLimits(); + public boolean getSetSizeNeeded(); + public boolean isFullScreen(); // Isolation methods public TextureManager getTextureManager(); + public PlaneDrawer getPlaneDrawer(); + public ViewVars getView(); + public SpanVars getDSVars(); + public LightsAndColors getColorMap(); + public IDoomSystem getDoomSystem(); + public IWadLoader getWadLoader(); /** @@ -60,12 +79,19 @@ public interface SceneRenderer { * @return */ public Visplanes getVPVars(); + public SegVars getSegVars(); + public ISpriteManager getSpriteManager(); + public BSPVars getBSPVars(); + public IVisSpriteManagement getVisSpriteManager(); + public ColFuncs getColFuncsHi(); + public ColFuncs getColFuncsLow(); + public ColVars getMaskedDCVars(); //public subsector_t PointInSubsector(int x, int y); diff --git a/src/rr/SectorAction.java b/src/rr/SectorAction.java index 6c7b1376..0f5783ce 100644 --- a/src/rr/SectorAction.java +++ b/src/rr/SectorAction.java @@ -8,11 +8,10 @@ * it. Also, it extends thinker so futher extensions are thinkers too. * */ - public abstract class SectorAction extends thinker_t { - + public sector_t sector; - + /** Special, only used when (un)archiving in order to re-link stuff * to their proper sector. */ diff --git a/src/rr/SegVars.java b/src/rr/SegVars.java index dcdc1b54..3360bcde 100644 --- a/src/rr/SegVars.java +++ b/src/rr/SegVars.java @@ -4,11 +4,11 @@ import utils.C2JUtils; public class SegVars { - // /// FROM BSP ///////// - + // /// FROM BSP ///////// + public int MAXDRAWSEGS = Limits.MAXDRAWSEGS; - /** pointer to drawsegs */ + /** pointer to drawsegs */ public int ds_p; public drawseg_t[] drawsegs; @@ -16,18 +16,17 @@ public class SegVars { public short[] maskedtexturecol; public int pmaskedtexturecol = 0; - - /** - * R_ClearDrawSegs - * - * The drawseg list is reset by pointing back at 0. - * - */ - public void ClearDrawSegs() { - ds_p = 0; - } - - public final void ResizeDrawsegs() { - drawsegs = C2JUtils.resize(drawsegs[0], drawsegs, drawsegs.length*2); - } + /** + * R_ClearDrawSegs + * + * The drawseg list is reset by pointing back at 0. + * + */ + public void ClearDrawSegs() { + ds_p = 0; + } + + public final void ResizeDrawsegs() { + drawsegs = C2JUtils.resize(drawsegs[0], drawsegs, drawsegs.length * 2); + } } diff --git a/src/rr/SimpleTextureManager.java b/src/rr/SimpleTextureManager.java index 2d7ab17a..fffa7bb2 100644 --- a/src/rr/SimpleTextureManager.java +++ b/src/rr/SimpleTextureManager.java @@ -16,8 +16,11 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; +import java.util.logging.Level; +import java.util.logging.Logger; import static m.fixed_t.FRACBITS; import static m.fixed_t.FRACUNIT; +import mochadoom.Loggers; import p.AbstractLevelLoader; import w.DoomBuffer; import w.IWadLoader; @@ -32,13 +35,15 @@ * @author Maes * */ - public class SimpleTextureManager implements TextureManager { + + private static final Logger LOGGER = Loggers.getLogger(SimpleTextureManager.class.getName()); + IWadLoader W; IDoomSystem I; AbstractLevelLoader LL; - DoomMain DM; - + DoomMain DM; + // // Graphics. // DOOM graphics for walls and sprites @@ -46,35 +51,33 @@ public class SimpleTextureManager implements TextureManager { // A column is composed of zero or more posts, // a patch or sprite is composed of zero or more columns. // - - protected int firstflat; - protected int lastflat; - protected int numflats; + protected int firstflat; + protected int lastflat; + protected int numflats; /** HACK */ protected flat_t[] flats; - + //protected int firstpatch; //protected int lastpatch; - protected int numpatches; + protected int numpatches; + protected int numtextures; - protected int numtextures; - /** The unchached textures themselves, stored just as patch lists and various properties */ protected texture_t[] textures; /** Width per texture? */ - protected int[] texturewidthmask; + protected int[] texturewidthmask; /** fixed_t[] needed for texture pegging */ - + /** How tall each composite texture is supposed to be */ - protected int[] textureheight; - + protected int[] textureheight; + /** How large each composite texture is supposed to be */ - protected int[] texturecompositesize; + protected int[] texturecompositesize; /** Tells us which patch lump covers which column of which texture */ - protected short[][] texturecolumnlump; - + protected short[][] texturecolumnlump; + /** This is supposed to store indexes into a patch_t lump which point to the columns themselves * Instead, we're going to return indexes to columns inside a particular patch. * In the case of patches inside a non-cached multi-patch texture (e.g. those made of non-overlapping @@ -82,88 +85,87 @@ public class SimpleTextureManager implements TextureManager { * 32-px wide patches, it should go something like 0, 1,2 ,3...31, 0,1,2,....31. * * */ - protected char[][] texturecolumnofs; - + protected char[][] texturecolumnofs; + /** couple with texturecomposite */ protected char texturecoloffset; //short[][] texturecolumnindexes; /** Stores [textures][columns][data]. */ protected byte[][][] texturecomposite; - - /** HACK to store "composite masked textures", a Boomism. */ + + /** HACK to store "composite masked textures", a Boomism. */ protected patch_t[] patchcomposite; /** for global animation. Storage stores actual lumps, translation is a relative -> relative map */ - protected int[] flattranslation, flatstorage,texturetranslation; - + protected int[] flattranslation, flatstorage, texturetranslation; + // This is also in DM, but one is enough, really. - protected int skytexture,skytexturemid,skyflatnum; - - public SimpleTextureManager(DoomMain DC) { - this.DM=DC; - this.W=DM.wadLoader; - this.I=DM.doomSystem; - this.LL=DM.levelLoader; - FlatPatchCache=new Hashtable(); + protected int skytexture, skytexturemid, skyflatnum; + + public SimpleTextureManager(DoomMain DC) { + this.DM = DC; + this.W = DM.wadLoader; + this.I = DM.doomSystem; + this.LL = DM.levelLoader; + FlatPatchCache = new Hashtable<>(); } - - /** Hash table used for matching flat lump to flat num */ + /** Hash table used for matching flat lump to flat num */ Hashtable FlatCache; - + Hashtable FlatPatchCache; - /** - * R_CheckTextureNumForName Check whether texture is available. Filter out - * NoTexture indicator. Can be sped up with a hash table, but it's pointless. - */ - - @Override - public int CheckTextureNumForName(String name) { - Integer i; - // "NoTexture" marker. - if (name.charAt(0) == '-') return 0; - - i=TextureCache.get(name); - if (i==null) return -1; - else return i; - - /* for (i = 0; i < numtextures; i++) + /** + * R_CheckTextureNumForName Check whether texture is available. Filter out + * NoTexture indicator. Can be sped up with a hash table, but it's pointless. + */ + @Override + public int CheckTextureNumForName(String name) { + Integer i; + // "NoTexture" marker. + if (name.charAt(0) == '-') { + return 0; + } + + i = TextureCache.get(name); + if (i == null) { + return -1; + } else { + return i; + } + + /* for (i = 0; i < numtextures; i++) if (textures[i].name.compareToIgnoreCase(name) == 0) return i; return -1; */ - } - - /** Hash table used for fast texture lookup */ + } - Hashtable TextureCache; - - /** - * R_TextureNumForName - * Calls R_CheckTextureNumForName, - * aborts with error message. - */ - - public int TextureNumForName(String name) { - int i; + /** Hash table used for fast texture lookup */ + Hashtable TextureCache; + + /** + * R_TextureNumForName + * Calls R_CheckTextureNumForName, + * aborts with error message. + */ + public int TextureNumForName(String name) { + int i; - i = CheckTextureNumForName(name); + i = CheckTextureNumForName(name); - if (i == -1) { - I.Error("R_TextureNumForName: %s not found", name); - } - return i; + if (i == -1) { + I.Error("R_TextureNumForName: %s not found", name); } + return i; + } /** * R_InitTextures * Initializes the texture list * with the textures from the world map. */ - - public void InitTextures () throws IOException - { + public void InitTextures() throws IOException { // This drives the rest maptexture_t mtexture = new maptexture_t(); texture_t texture; @@ -176,117 +178,111 @@ public void InitTextures () throws IOException int[] maxoff = new int[texturelumps.length]; int[] _numtextures = new int[texturelumps.length]; int directory = 1; - int texset=TEXTURE1; + int texset = TEXTURE1; // Load the patch names from pnames.lmp. //name[8] = 0; - patchlookup=loadPatchNames("PNAMES"); - + patchlookup = loadPatchNames("PNAMES"); + // Load the map texture definitions from textures.lmp. // The data is contained in one or two lumps, // TEXTURE1 for shareware, plus TEXTURE2 for commercial. - - for (int i=0;i(numtextures); - + TextureCache = new Hashtable<>(numtextures); + texturecolumnlump = new short[numtextures][]; texturecolumnofs = new char[numtextures][]; - patchcomposite=new patch_t[numtextures]; + patchcomposite = new patch_t[numtextures]; texturecomposite = new byte[numtextures][][]; texturecompositesize = new int[numtextures]; texturewidthmask = new int[numtextures]; textureheight = new int[numtextures]; totalwidth = 0; - - // Really complex printing shit... - System.out.print("["); - for (int i=0 ; i maxoff[texset]) - I.Error("R_InitTextures: bad texture directory"); - - maptex[texset].position(offset); - // Read "maptexture", which is the on-disk form. - mtexture.unpack(maptex[texset]); + LOGGER.log(Level.INFO, String.format("Textures: %d", numtextures)); + for (int i = 0; i < numtextures; i++, directory++) { + if (i == _numtextures[TEXTURE1]) { + // Start looking in second texture file. + texset = TEXTURE2; + directory = 1; // offset "1" inside maptex buffer + //System.err.print("Starting looking into TEXTURE2\n"); + } - // MAES: the HashTable only needs to know the correct names. - TextureCache.put(mtexture.name.toUpperCase(), new Integer(i)); - - // We don't need to manually copy trivial fields. - textures[i]=new texture_t(); - textures[i].copyFromMapTexture(mtexture); - texture = textures[i]; - - // However we do need to correct the "patch.patch" field through the patchlookup - mpatch = mtexture.patches; - patch = texture.patches; - - for (int j=0 ; j maxoff[texset]) { + I.Error("R_InitTextures: bad texture directory"); } - } - - // Columns and offsets of taxture = textures[i] - texturecolumnlump[i] = new short[texture.width]; - //C2JUtils.initArrayOfObjects( texturecolumnlump[i], column_t.class); - texturecolumnofs[i] = new char[texture.width]; - - int j = 1; - while (j*2 <= texture.width) - j<<=1; - - texturewidthmask[i] = j-1; - textureheight[i] = texture.height< texture.width) - x2 = texture.width; - for ( ; x texture.width) { + x2 = texture.width; + } + for (; x < x2; x++) { + /* Obviously, if a patch starts at x it does cover the x-th column * of a texture, even if transparent. - */ - patchcount[x]++; - // Column "x" of composite texture "texnum" is covered by this patch. - collump[x] = (short) patch[i].patch; - - /* This is supposed to be a raw pointer to the beginning of the column + */ + patchcount[x]++; + // Column "x" of composite texture "texnum" is covered by this patch. + collump[x] = (short) patch[i].patch; + + /* This is supposed to be a raw pointer to the beginning of the column * data, as it appears inside the PATCH. * * Instead, we can return the actual column index (x-x1) @@ -440,44 +431,39 @@ public void GenerateLookup (int texnum) throws IOException * * Any questions? * - */ - colofs[x] = (char) (x-x1); - // This implies that colofs[x] is 0 for a void column? - - } // end column of patch. + */ + colofs[x] = (char) (x - x1); + // This implies that colofs[x] is 0 for a void column? + + } // end column of patch. } // end patch - + // Now check all columns again. - for ( x=0 ; x 1) - { - // Use the cached block. This column won't be read from the wad system. - collump[x] = -1; - colofs[x] = (char) texturecompositesize[texnum]; - - /* Do we really mind? + for (x = 0; x < texture.width; x++) { + // Can only occur if a column isn't covered by a patch at all, not even a transparent one. + if (patchcount[x] == 0) { + // TODO: somehow handle this. + LOGGER.log(Level.WARNING, String.format("R_GenerateLookup: column without a patch (%s), width: %d", + texture.name, realpatch.width)); + //return; + } + // I_Error ("R_GenerateLookup: column without a patch"); + + // Columns where more than one patch overlaps. + if (patchcount[x] > 1) { + // Use the cached block. This column won't be read from the wad system. + collump[x] = -1; + colofs[x] = (char) texturecompositesize[texnum]; + + /* Do we really mind? if (texturecompositesize[texnum] > 0x10000-texture.height) { I.Error ("R_GenerateLookup: texture no %d (%s) is >64k", texnum,textures[texnum].name); } */ - - texturecompositesize[texnum] += texture.height; + texturecompositesize[texnum] += texture.height; + } } - } } /** @@ -489,78 +475,73 @@ public void GenerateLookup (int texnum) throws IOException * @param texnum * */ - - public void GenerateComposite (int texnum) - { - byte[][] block; - texture_t texture; - texpatch_t[] patch; - patch_t realpatch=null; - int x; - int x1; - int x2; - column_t patchcol; - short[] collump; + public void GenerateComposite(int texnum) { + byte[][] block; + texture_t texture; + texpatch_t[] patch; + patch_t realpatch = null; + int x; + int x1; + int x2; + column_t patchcol; + short[] collump; char[] colofs; // unsigned short - // short[] colidxs; // unsigned short - + // short[] colidxs; // unsigned short + texture = textures[texnum]; // BOth allocate the composite texture, and assign it to block. // texturecompositesize indicates a size in BYTES. We need a number of columns, though. // Now block is divided into columns. We need to allocate enough data for each column - - block = texturecomposite[texnum]=new byte[texture.width][texture.height]; - + block = texturecomposite[texnum] = new byte[texture.width][texture.height]; + // Lump where a certain column will be read from (actually, a patch) collump = texturecolumnlump[texnum]; - + // Offset of said column into the patch. colofs = texturecolumnofs[texnum]; - - // colidxs = texturecolumnindexes[texnum]; - + + // colidxs = texturecolumnindexes[texnum]; // Composite the columns together. patch = texture.patches; - + // For each patch in the texture... - for (int i=0 ;i texture.width) - x2 = texture.width; + for (int i = 0; i < texture.patchcount; i++) { + // Retrieve patch...if it IS a patch. + realpatch = this.retrievePatchSafe(patch[i].patch); + + x1 = patch[i].originx; + x2 = x1 + realpatch.width; + + if (x1 < 0) { + x = 0; + } else { + x = x1; + } + + if (x2 > texture.width) { + x2 = texture.width; + } + + for (; x < x2; x++) { + // Column does not have multiple patches? + if (collump[x] >= 0) { + continue; + } + + // patchcol = (column_t *)((byte *)realpatch + // + LONG(realpatch.columnofs[x-x1])); + // We can look this up cleanly in Java. Ha! + patchcol = realpatch.columns[x - x1]; + DrawColumnInCache(patchcol, + block[x], colofs[x], + patch[i].originy, + texture.height); + } - for ( ; x= 0) - continue; - - // patchcol = (column_t *)((byte *)realpatch - // + LONG(realpatch.columnofs[x-x1])); - - - // We can look this up cleanly in Java. Ha! - patchcol=realpatch.columns[x-x1]; - DrawColumnInCache (patchcol, - block[x], colofs[x], - patch[i].originy, - texture.height); - } - } } - + /** * R_GenerateMaskedComposite * @@ -582,7 +563,6 @@ public void GenerateComposite (int texnum) * @param texnum * */ - @Override public void GenerateMaskedComposite(int texnum) { byte[][] block; @@ -601,7 +581,6 @@ public void GenerateMaskedComposite(int texnum) { // MAES: we don't want to save a solid block this time. Will only use // it for synthesis. - block = new byte[texture.width][texture.height]; pixmap = new boolean[texture.width][texture.height]; // True values = solid @@ -621,34 +600,36 @@ public void GenerateMaskedComposite(int texnum) { x1 = patch[i].originx; x2 = x1 + realpatch.width; - if (x1 < 0) + if (x1 < 0) { x = 0; - else + } else { x = x1; + } - if (x2 > texture.width) + if (x2 > texture.width) { x2 = texture.width; + } for (; x < x2; x++) { // Column does not have multiple patches? - if (collump[x] >= 0) + if (collump[x] >= 0) { continue; + } // patchcol = (column_t *)((byte *)realpatch // + LONG(realpatch.columnofs[x-x1])); - // We can look this up cleanly in Java. Ha! patchcol = realpatch.columns[x - x1]; DrawColumnInCache(patchcol, block[x], pixmap[x], colofs[x], - patch[i].originy, texture.height); + patch[i].originy, texture.height); } } - + // Patch drawn on cache, synthesize patch_t using it. - this.patchcomposite[texnum]=MultiPatchSynthesizer.synthesize(this.CheckTextureNameForNum(texnum),block, pixmap,texture.width,texture.height); + this.patchcomposite[texnum] = MultiPatchSynthesizer.synthesize(this.CheckTextureNameForNum(texnum), block, pixmap, texture.width, texture.height); } - + /** * R_DrawColumnInCache * Clip and draw a column from a patch into a cached post. @@ -669,7 +650,6 @@ public void GenerateMaskedComposite(int texnum) { * @param cacheheight the maximum height it's supposed to reach when drawing? * */ - public void DrawColumnInCache(column_t patch, byte[] cache, int offset, int originy, int cacheheight) { int count; @@ -681,7 +661,6 @@ public void DrawColumnInCache(column_t patch, byte[] cache, int offset, * because post positions AND offsets are already precomputed at load * time */ - for (int i = 0; i < patch.posts; i++) { // This should position us at the beginning of the next post @@ -689,29 +668,30 @@ public void DrawColumnInCache(column_t patch, byte[] cache, int offset, count = patch.postlen[i]; // length of this particular post position = originy + patch.postdeltas[i]; // Position to draw inside - // cache. + // cache. // Post starts outside of texture's bounds. Adjust offset. - if (position < 0) { count += position; // Consider that we have a "drawing debt". position = 0; } // Post will go too far outside. - if (position + count > cacheheight) + if (position + count > cacheheight) { count = cacheheight - position; + } if (count > 0) // Draw this post. Won't draw posts that start - // "outside" - // Will start at post's start, but will only draw enough pixels - // not to overdraw. + // "outside" + // Will start at post's start, but will only draw enough pixels + // not to overdraw. + { System.arraycopy(patch.data, source, cache, position, count); + } } } - - + // Version also drawing on a supplied transparency map public void DrawColumnInCache(column_t patch, byte[] cache, boolean[] pixmap, int offset, int originy, int cacheheight) { @@ -724,7 +704,6 @@ public void DrawColumnInCache(column_t patch, byte[] cache, * because post positions AND offsets are already precomputed at load * time */ - for (int i = 0; i < patch.posts; i++) { // This should position us at the beginning of the next post @@ -732,18 +711,18 @@ public void DrawColumnInCache(column_t patch, byte[] cache, count = patch.postlen[i]; // length of this particular post position = originy + patch.postdeltas[i]; // Position to draw inside - // cache. + // cache. // Post starts outside of texture's bounds. Adjust offset. - if (position < 0) { count += position; // Consider that we have a "drawing debt". position = 0; } // Post will go too far outside. - if (position + count > cacheheight) + if (position + count > cacheheight) { count = cacheheight - position; + } if (count > 0) { // Draw post, AND fill solidity map @@ -773,72 +752,67 @@ public void DrawColumnInCache(column_t patch, byte[] cache, * speeds up lookups. * */ - @Override - public final void InitFlats () - { - numflats=0; - int extendedflatstart=-1; - firstflat=W.GetNumForName(LUMPSTART); // This is the start of normal lumps. - if (FlatCache==null) FlatCache=new Hashtable(); - else FlatCache.clear(); - Hashtable FlatNames=new Hashtable (); // Store names here. - + public final void InitFlats() { + numflats = 0; + int extendedflatstart = -1; + firstflat = W.GetNumForName(LUMPSTART); // This is the start of normal lumps. + if (FlatCache == null) { + FlatCache = new Hashtable<>(); + } else { + FlatCache.clear(); + } + Hashtable FlatNames = new Hashtable<>(); // Store names here. + // Normally, if we don't use Boom features, we could look for F_END and that's it. // However we want to avoid using flat translation and instead store absolute lump numbers. // So we need to do a clean parse. - // The rule is: we scan from the very first F_START to the very first F_END. // We discard markers, and only assign sequential numbers to valid lumps. // These are the vanilla flats, and will work with fully merged PWADs too. - // Normally, this marks the end of regular lumps. However, if DEUTEX extension // are present, it will actually mark the end of the extensions due to lump // priority, so its usefulness as an absolute end-index for regular flats // is dodgy at best. Gotta love the inconsistent mundo hacks! - //int lastflatlump=W.GetNumForName(LUMPEND); - - // - int lump=firstflat; - int seq=0; + // + int lump = firstflat; + int seq = 0; String name; - while (!(name=W.GetNameForNum(lump)).equalsIgnoreCase(LUMPEND)){ - if (!W.isLumpMarker(lump)){ + while (!(name = W.GetNameForNum(lump)).equalsIgnoreCase(LUMPEND)) { + if (!W.isLumpMarker(lump)) { // Not a marker. Put in cache. FlatCache.put(lump, seq); // Save its name too. FlatNames.put(name, lump); seq++; // Advance sequence numflats++; // Total flats do increase - } + } lump++; // Advance lump. } - - extendedflatstart=W.CheckNumForName(DEUTEX_START); // This is the start of DEUTEX flats. - if (extendedflatstart>-1){ - // If extended ones are present, then Advance slowly. - lump=extendedflatstart; - - // Safeguard: FF_START without corresponding F_END (e.g. in helltest.wad) - - name=W.GetNameForNum(lump); - - // The end of those extended flats is also marked by F_END or FF_END, as noted above. - // It can also be non-existent in some broken maps like helltest.wad. Jesus. - while (!(name==null || name.equalsIgnoreCase(LUMPEND)||name.equalsIgnoreCase(DEUTEX_END))){ - if (!W.isLumpMarker(lump)){ - // Not a marker. Check if it's supposed to replace something. - if (FlatNames.containsKey(name)){ - // Well, it is. Off with its name, save the lump number though. - int removed=FlatNames.remove(name); - // Put new name in list - FlatNames.put(name, lump); - // Remove old lump, but keep sequence. - int oldseq=FlatCache.remove(removed); - // Put new lump number with old sequence. - FlatCache.put(lump, oldseq); + extendedflatstart = W.CheckNumForName(DEUTEX_START); // This is the start of DEUTEX flats. + if (extendedflatstart > -1) { + // If extended ones are present, then Advance slowly. + lump = extendedflatstart; + + // Safeguard: FF_START without corresponding F_END (e.g. in helltest.wad) + name = W.GetNameForNum(lump); + + // The end of those extended flats is also marked by F_END or FF_END, as noted above. + // It can also be non-existent in some broken maps like helltest.wad. Jesus. + while (!(name == null || name.equalsIgnoreCase(LUMPEND) || name.equalsIgnoreCase(DEUTEX_END))) { + if (!W.isLumpMarker(lump)) { + // Not a marker. Check if it's supposed to replace something. + if (FlatNames.containsKey(name)) { + // Well, it is. Off with its name, save the lump number though. + int removed = FlatNames.remove(name); + // Put new name in list + FlatNames.put(name, lump); + // Remove old lump, but keep sequence. + int oldseq = FlatCache.remove(removed); + // Put new lump number with old sequence. + FlatCache.put(lump, oldseq); } else { // Add normally FlatCache.put(lump, seq); // Save its name too. @@ -846,42 +820,40 @@ public final void InitFlats () seq++; // Advance sequence numflats++; // Total flats do increase } + } + lump++; // Advance lump. + name = W.GetNameForNum(lump); } - lump++; // Advance lump. - name=W.GetNameForNum(lump); - } } - + // So now we have a lump -> sequence number mapping. + // Create translation table for global animation. + flattranslation = new int[numflats]; + flatstorage = new int[numflats]; + + // MAJOR CHANGE: flattranslation stores absolute lump numbers. Adding + // firstlump is not necessary anymore. + // Now, we're pretty sure that we have a progressive value mapping. + Enumeration stuff = FlatCache.keys(); + while (stuff.hasMoreElements()) { + int nextlump = stuff.nextElement(); + flatstorage[FlatCache.get(nextlump)] = nextlump; + // Lump is used as the key, while the relative lump number is the value. + //FlatCache.put(j, k-1); + + } + + for (int i = 0; i < numflats; i++) { + flattranslation[i] = i; + // System.out.printf("Verification: flat[%d] is %s in lump %d\n",i,W.GetNameForNum(flattranslation[i]),flatstorage[i]); + } + } + + private final static String LUMPSTART = "F_START"; + private final static String LUMPEND = "F_END"; + private final static String DEUTEX_END = "FF_END"; + private final static String DEUTEX_START = "FF_START"; - // Create translation table for global animation. - flattranslation = new int[numflats]; - flatstorage = new int[numflats]; - - // MAJOR CHANGE: flattranslation stores absolute lump numbers. Adding - // firstlump is not necessary anymore. - // Now, we're pretty sure that we have a progressive value mapping. - - Enumeration stuff= FlatCache.keys(); - while (stuff.hasMoreElements()){ - int nextlump=stuff.nextElement(); - flatstorage[FlatCache.get(nextlump)]=nextlump; - // Lump is used as the key, while the relative lump number is the value. - //FlatCache.put(j, k-1); - - } - - for (int i=0;i roguePatches= new HashMap (); - - class TextureDirectoryEntry implements Comparable{ - /** Where an entry starts within the TEXTUREx lump */ - int offset; - /** Its implicit position as indicated by the directory's ordering */ - int entry; - /** Its MAXIMUM possible length, depending on what follows it. - * Not trivial to compute without thoroughtly examining the entire lump */ - int length; - - /** Entries are ranked according to actual offset */ + patch_t p = this.retrievePatchSafe(lump); + + // Allocate space for a cached block. + byte[][] block = new byte[p.width][p.height]; + + for (int i = 0; i < p.width; i++) { + DrawColumnInCache(p.columns[i], block[i], i, 0, p.height); + } + + // Don't keep this twice in memory. + W.UnlockLumpNum(lump); + return block; + } + + int lastrogue = -1; + byte[][] rogue; + + HashMap roguePatches = new HashMap<>(); + + class TextureDirectoryEntry implements Comparable { + + /** Where an entry starts within the TEXTUREx lump */ + int offset; + /** Its implicit position as indicated by the directory's ordering */ + int entry; + /** Its MAXIMUM possible length, depending on what follows it. + * Not trivial to compute without thoroughtly examining the entire lump */ + int length; + + /** Entries are ranked according to actual offset */ @Override public int compareTo(TextureDirectoryEntry o) { - if (this.offset * @param */ - - -public final class SimpleThings extends AbstractThings { +public final class SimpleThings extends AbstractThings { public SimpleThings(VideoScale vs, SceneRenderer R) { super(vs, R); diff --git a/src/rr/SpriteManager.java b/src/rr/SpriteManager.java index 42df4ab8..09ca9964 100644 --- a/src/rr/SpriteManager.java +++ b/src/rr/SpriteManager.java @@ -5,7 +5,10 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; import static m.fixed_t.FRACBITS; +import mochadoom.Loggers; import static utils.C2JUtils.memset; import static utils.GenericCopy.malloc; import w.lumpinfo_t; @@ -19,171 +22,168 @@ * @author Maes * */ - public class SpriteManager implements ISpriteManager { - - /** There seems to be an arbitrary limit of 29 distinct frames per THING */ - public static final int MAX_SPRITE_FRAMES = 29; - - public SpriteManager(DoomMain DOOM){ - sprtemp = malloc(spriteframe_t::new, spriteframe_t[]::new, MAX_SPRITE_FRAMES); - this.DOOM = DOOM; - } - - private final DoomMain DOOM; - - // Temporarily contains the frames of a given sprite before they are - // registered with the rendering system. Apparently, a maximum of 29 frames - // per sprite is allowed. - protected spriteframe_t[] sprtemp = new spriteframe_t[29]; - protected int maxframe; - protected String spritename; - - // MAES: Shit taken from things - - protected int firstspritelump; - protected int lastspritelump; - protected int numspritelumps; - - // variables used to look up and range check thing_t sprites patches - // - protected spritedef_t[] sprites; - - protected int numsprites; - - /** needed for pre rendering (fixed_t[]) */ - protected int[] spritewidth, spriteoffset, spritetopoffset; - - - // - // R_InitSpriteDefs - // Pass a null terminated list of sprite names - // (4 chars exactly) to be used. - // - // Builds the sprite rotation matrixes to account - // for horizontally flipped sprites. - // - // Will report an error if the lumps are inconsistent. - // Only called at startup. - // - // Sprite lump names are 4 characters for the actor, - // a letter for the frame, and a number for the rotation. - // - // A sprite that is flippable will have an additional - // letter/number appended. - // - // The rotation character can be 0 to signify no rotations. - // - // 1/25/98, 1/31/98 killough : Rewritten for performance - // - // Empirically verified to have excellent hash - // properties across standard Doom sprites: - - protected final void InitSpriteDefs(String[] namelist) { - int numentries = lastspritelump - firstspritelump + 1; - HashMap> hash; - int i; - - if (numentries == 0 || namelist == null) - return; - - // count the number of sprite names - i = namelist.length; - - numsprites = i; - sprites = malloc(spritedef_t::new, spritedef_t[]::new, numsprites); + private static final Logger LOGGER = Loggers.getLogger(SpriteManager.class.getName()); + + /** There seems to be an arbitrary limit of 29 distinct frames per THING */ + public static final int MAX_SPRITE_FRAMES = 29; + + public SpriteManager(DoomMain DOOM) { + sprtemp = malloc(spriteframe_t::new, spriteframe_t[]::new, MAX_SPRITE_FRAMES); + this.DOOM = DOOM; + } + + private final DoomMain DOOM; + + // Temporarily contains the frames of a given sprite before they are + // registered with the rendering system. Apparently, a maximum of 29 frames + // per sprite is allowed. + protected spriteframe_t[] sprtemp = new spriteframe_t[29]; + protected int maxframe; + protected String spritename; + + // MAES: Shit taken from things + protected int firstspritelump; + protected int lastspritelump; + protected int numspritelumps; + + // variables used to look up and range check thing_t sprites patches + // + protected spritedef_t[] sprites; + + protected int numsprites; + + /** needed for pre rendering (fixed_t[]) */ + protected int[] spritewidth, spriteoffset, spritetopoffset; + + // + // R_InitSpriteDefs + // Pass a null terminated list of sprite names + // (4 chars exactly) to be used. + // + // Builds the sprite rotation matrixes to account + // for horizontally flipped sprites. + // + // Will report an error if the lumps are inconsistent. + // Only called at startup. + // + // Sprite lump names are 4 characters for the actor, + // a letter for the frame, and a number for the rotation. + // + // A sprite that is flippable will have an additional + // letter/number appended. + // + // The rotation character can be 0 to signify no rotations. + // + // 1/25/98, 1/31/98 killough : Rewritten for performance + // + // Empirically verified to have excellent hash + // properties across standard Doom sprites: + protected final void InitSpriteDefs(String[] namelist) { + int numentries = lastspritelump - firstspritelump + 1; + HashMap> hash; + int i; + + if (numentries == 0 || namelist == null) { + return; + } - // Create hash table based on just the first four letters of each - // sprite - // killough 1/31/98 - // Maes: the idea is to have a chained hastable which can handle - // multiple entries (sprites) on the same primary key (the 4 first chars of - // the sprite name) + // count the number of sprite names + i = namelist.length; + + numsprites = i; + + sprites = malloc(spritedef_t::new, spritedef_t[]::new, numsprites); + + // Create hash table based on just the first four letters of each + // sprite + // killough 1/31/98 + // Maes: the idea is to have a chained hastable which can handle + // multiple entries (sprites) on the same primary key (the 4 first chars of + // the sprite name) + hash = new HashMap<>(numentries); // allocate hash table + + // We have to trasverse this in the opposite order, so that later + // lumps + // trump previous ones in order. + for (i = numentries - 1; i >= 0; i--) { + int hashcode = SpriteNameHash(DOOM.wadLoader.GetLumpInfo(i + firstspritelump).name); + // Create chain list for each sprite class (e.g. TROO, POSS, + // etc.) + // + if (!hash.containsKey(hashcode)) { + hash.put(hashcode, new ArrayList<>()); + } - hash = new HashMap<>(numentries); // allocate hash table + // Store (yet another) lump index for this sprite. + hash.get(hashcode).add(i); + } - // We have to trasverse this in the opposite order, so that later - // lumps - // trump previous ones in order. - for (i = numentries - 1; i >= 0; i--) { - int hashcode = SpriteNameHash(DOOM.wadLoader.GetLumpInfo(i + firstspritelump).name); - // Create chain list for each sprite class (e.g. TROO, POSS, - // etc.) - // - if (!hash.containsKey(hashcode)) { - hash.put(hashcode, new ArrayList<>()); + // scan all the lump names for each of the names, + // noting the highest frame letter. + for (i = 0; i < numsprites; i++) { + + // We only look for entries that are known to be sprites. + // The hashtable may contain a lot of other shit, at this point + // which will be hopefully ignored. + String spritename = namelist[i]; + List list = hash.get(SpriteNameHash(spritename)); + + // Well, it may have been something else. Fuck it. + if (list != null && !list.isEmpty()) { + + // Maes: the original code actually set everything to "-1" + // here, including the + // "boolean" rotate value. The idea was to create a + // "tristate" of sorts, where -1 + // means a sprite of uncertain status. Goto + // InstallSpriteLumps for more. + for (final spriteframe_t sprtemp1 : sprtemp) { + memset(sprtemp1.flip, (byte) -1, sprtemp1.flip.length); + memset(sprtemp1.lump, (short) -1, sprtemp1.lump.length); + // This should be INDETERMINATE at this point. + sprtemp1.rotate = -1; } + maxframe = -1; - // Store (yet another) lump index for this sprite. - hash.get(hashcode).add(i); - } - - // scan all the lump names for each of the names, - // noting the highest frame letter. - - for (i = 0; i < numsprites; i++) { - - // We only look for entries that are known to be sprites. - // The hashtable may contain a lot of other shit, at this point - // which will be hopefully ignored. - String spritename = namelist[i]; - List list = hash.get(SpriteNameHash(spritename)); - - // Well, it may have been something else. Fuck it. - if (list != null && !list.isEmpty()) { - - // Maes: the original code actually set everything to "-1" - // here, including the - // "boolean" rotate value. The idea was to create a - // "tristate" of sorts, where -1 - // means a sprite of uncertain status. Goto - // InstallSpriteLumps for more. - for (final spriteframe_t sprtemp1: sprtemp) { - memset(sprtemp1.flip, (byte) -1, sprtemp1.flip.length); - memset(sprtemp1.lump, (short) -1, sprtemp1.lump.length); - // This should be INDETERMINATE at this point. - sprtemp1.rotate = -1; - } - maxframe = -1; - - // What is stored in the lists are all actual lump numbers - // relative - // to e.g. TROO. In coalesced lumps, there will be overlap. - // This procedure should, in theory, trump older ones. - list.forEach((j) -> { - lumpinfo_t lump = DOOM.wadLoader.GetLumpInfo(j + firstspritelump); - // We don't know a-priori which frames exist. - // However, we do know how to interpret existing ones, - // and have an implicit maximum sequence of 29 Frames. - // A frame can also hame multiple rotations. - if (lump.name.substring(0, 4).equalsIgnoreCase( + // What is stored in the lists are all actual lump numbers + // relative + // to e.g. TROO. In coalesced lumps, there will be overlap. + // This procedure should, in theory, trump older ones. + list.forEach((j) -> { + lumpinfo_t lump = DOOM.wadLoader.GetLumpInfo(j + firstspritelump); + // We don't know a-priori which frames exist. + // However, we do know how to interpret existing ones, + // and have an implicit maximum sequence of 29 Frames. + // A frame can also hame multiple rotations. + if (lump.name.substring(0, 4).equalsIgnoreCase( spritename.substring(0, 4))) { - int frame = lump.name.charAt(4) - 'A'; - int rotation = lump.name.charAt(5) - '0'; - if (sprtemp[frame].rotate != -1) { - // We already encountered this sprite, but we - // may need to trump it with something else + int frame = lump.name.charAt(4) - 'A'; + int rotation = lump.name.charAt(5) - '0'; + if (sprtemp[frame].rotate != -1) { + // We already encountered this sprite, but we + // may need to trump it with something else - } - InstallSpriteLump(j + firstspritelump, frame, + } + InstallSpriteLump(j + firstspritelump, frame, rotation, false); - if (lump.name.length() >= 7) { - frame = lump.name.charAt(6) - 'A'; - rotation = lump.name.charAt(7) - '0'; - InstallSpriteLump(j + firstspritelump, frame, + if (lump.name.length() >= 7) { + frame = lump.name.charAt(6) - 'A'; + rotation = lump.name.charAt(7) - '0'; + InstallSpriteLump(j + firstspritelump, frame, rotation, true); - } } - }); - - // check the frames that were found for completeness - if ((sprites[i].numframes = ++maxframe) != 0) // killough - // 1/31/98 - { - int frame; - for (frame = 0; frame < maxframe; frame++) - switch (sprtemp[frame].rotate) { + } + }); + + // check the frames that were found for completeness + if ((sprites[i].numframes = ++maxframe) != 0) // killough + // 1/31/98 + { + int frame; + for (frame = 0; frame < maxframe; frame++) { + switch (sprtemp[frame].rotate) { case -1: // no rotations were found for that frame at all DOOM.doomSystem.Error("R_InitSprites: No patches found for %s frame %c", @@ -194,175 +194,168 @@ protected final void InitSpriteDefs(String[] namelist) { // only the first rotation is needed break; - case 1: - // must have all 8 frames + case 1: // must have all 8 frames { int rotation; - for (rotation = 0; rotation < 8; rotation++) - if (sprtemp[frame].lump[rotation] == -1) + for (rotation = 0; rotation < 8; rotation++) { + if (sprtemp[frame].lump[rotation] == -1) { DOOM.doomSystem.Error("R_InitSprites: Sprite %s frame %c is missing rotations", namelist[i], frame + 'A'); + } + } break; } - } - // allocate space for the frames present and copy - // sprtemp to it - // MAES: we can do that elegantly in one line. - - sprites[i].copy(sprtemp, maxframe); + } } + // allocate space for the frames present and copy + // sprtemp to it + // MAES: we can do that elegantly in one line. - } - } - - } - - /** - * R_InitSpriteLumps Finds the width and hoffset of all sprites in the wad, - * so the sprite does not need to be cached completely just for having the - * header info ready during rendering. - */ - - public void InitSpriteLumps() { - int i; - patch_t patch; - - firstspritelump = DOOM.wadLoader.GetNumForName("S_START") + 1; - lastspritelump = DOOM.wadLoader.GetNumForName("S_END") - 1; - - numspritelumps = lastspritelump - firstspritelump + 1; - spritewidth = new int[numspritelumps]; - spriteoffset = new int[numspritelumps]; - spritetopoffset = new int[numspritelumps]; - - for (i = 0; i < numspritelumps; i++) { - if ((i & 63) == 0) { - System.out.print("."); + sprites[i].copy(sprtemp, maxframe); } - patch = DOOM.wadLoader.CacheLumpNum(firstspritelump + i, PU_CACHE, - patch_t.class); - spritewidth[i] = patch.width << FRACBITS; - spriteoffset[i] = patch.leftoffset << FRACBITS; - spritetopoffset[i] = patch.topoffset << FRACBITS; } } - - /** - * R_InstallSpriteLump Local function for R_InitSprites. - * - * Boom function, more suited to resource coalescing. - * - */ - public final void InstallSpriteLump(int lump, int frame, - int rotation, boolean flipped) { - if (frame >= MAX_SPRITE_FRAMES || rotation > 8) - DOOM.doomSystem.Error("R_InstallSpriteLump: Bad frame characters in lump %d", - lump); - - if (frame > maxframe) { - maxframe = frame; - } - - if (rotation == 0) { // the lump should be used for all rotations - int r; - for (r = 0; r < 8; r++) - if (sprtemp[frame].lump[r] == -1) { - sprtemp[frame].lump[r] = lump - firstspritelump; - sprtemp[frame].flip[r] = (byte) (flipped ? 1 : 0); - sprtemp[frame].rotate = 0; // jff 4/24/98 if any subbed, - // rotless - } - return; - } + } - // the lump is only used for one rotation + /** + * R_InitSpriteLumps Finds the width and hoffset of all sprites in the wad, + * so the sprite does not need to be cached completely just for having the + * header info ready during rendering. + */ + public void InitSpriteLumps() { + int i; + patch_t patch; - if (sprtemp[frame].lump[--rotation] == -1) { - sprtemp[frame].lump[rotation] = lump - firstspritelump; - sprtemp[frame].flip[rotation] = (byte) (flipped ? 1 : 0); - sprtemp[frame].rotate = 1; // jff 4/24/98 only change if rot - // used - } - } + firstspritelump = DOOM.wadLoader.GetNumForName("S_START") + 1; + lastspritelump = DOOM.wadLoader.GetNumForName("S_END") - 1; - /** - * R_InitSprites Called at program start. - * - */ + numspritelumps = lastspritelump - firstspritelump + 1; + spritewidth = new int[numspritelumps]; + spriteoffset = new int[numspritelumps]; + spritetopoffset = new int[numspritelumps]; - @Override - public void InitSprites(String[] namelist) { - InitSpriteDefs(namelist); - } - - - protected final int SpriteNameHash(String ss) { - return ss.substring(0, 4).hashCode(); - } - - // GETTERS - - @Override - public final int getFirstSpriteLump(){ - return firstspritelump; - } - - @Override - public final int getNumSprites(){ - return numsprites; - } - - @Override - public final spritedef_t[] getSprites() { - return sprites; - } - - @Override - public final spritedef_t getSprite(int index) { - return sprites[index]; - } - - @Override - public final int[] getSpriteWidth() { - return spritewidth; - } - - @Override - public final int[] getSpriteOffset() { - return spriteoffset; + LOGGER.log(Level.INFO, String.format("Sprite lumps: %d", numspritelumps)); + for (i = 0; i < numspritelumps; i++) { + patch = DOOM.wadLoader.CacheLumpNum(firstspritelump + i, PU_CACHE, + patch_t.class); + spritewidth[i] = patch.width << FRACBITS; + spriteoffset[i] = patch.leftoffset << FRACBITS; + spritetopoffset[i] = patch.topoffset << FRACBITS; } - - @Override - public final int[] getSpriteTopOffset() { - return spritetopoffset; + } + + /** + * R_InstallSpriteLump Local function for R_InitSprites. + * + * Boom function, more suited to resource coalescing. + * + */ + public final void InstallSpriteLump(int lump, int frame, + int rotation, boolean flipped) { + if (frame >= MAX_SPRITE_FRAMES || rotation > 8) { + DOOM.doomSystem.Error("R_InstallSpriteLump: Bad frame characters in lump %d", + lump); } - @Override - public final int getSpriteWidth(int index) { - return spritewidth[index]; + if (frame > maxframe) { + maxframe = frame; } - @Override - public final int getSpriteOffset(int index) { - return spriteoffset[index]; + if (rotation == 0) { // the lump should be used for all rotations + int r; + for (r = 0; r < 8; r++) { + if (sprtemp[frame].lump[r] == -1) { + sprtemp[frame].lump[r] = lump - firstspritelump; + sprtemp[frame].flip[r] = (byte) (flipped ? 1 : 0); + sprtemp[frame].rotate = 0; // jff 4/24/98 if any subbed, + // rotless + } + } + return; } - @Override - public final int getSpriteTopOffset(int index) { - return spritetopoffset[index]; + // the lump is only used for one rotation + if (sprtemp[frame].lump[--rotation] == -1) { + sprtemp[frame].lump[rotation] = lump - firstspritelump; + sprtemp[frame].flip[rotation] = (byte) (flipped ? 1 : 0); + sprtemp[frame].rotate = 1; // jff 4/24/98 only change if rot + // used } - - // Some unused shit - - /* + } + + /** + * R_InitSprites Called at program start. + * + */ + @Override + public void InitSprites(String[] namelist) { + InitSpriteDefs(namelist); + } + + protected final int SpriteNameHash(String ss) { + return ss.substring(0, 4).hashCode(); + } + + // GETTERS + @Override + public final int getFirstSpriteLump() { + return firstspritelump; + } + + @Override + public final int getNumSprites() { + return numsprites; + } + + @Override + public final spritedef_t[] getSprites() { + return sprites; + } + + @Override + public final spritedef_t getSprite(int index) { + return sprites[index]; + } + + @Override + public final int[] getSpriteWidth() { + return spritewidth; + } + + @Override + public final int[] getSpriteOffset() { + return spriteoffset; + } + + @Override + public final int[] getSpriteTopOffset() { + return spritetopoffset; + } + + @Override + public final int getSpriteWidth(int index) { + return spritewidth[index]; + } + + @Override + public final int getSpriteOffset(int index) { + return spriteoffset[index]; + } + + @Override + public final int getSpriteTopOffset(int index) { + return spritetopoffset[index]; + } + + // Some unused shit + /* * R_InstallSpriteLump Local function for R_InitSprites. * * Older function, closer to linuxdoom. Using Boom-derived one instead. - */ - - /* + */ + /* protected final void InstallSpriteLump(int lump, int frame, int rotation, boolean flipped) { @@ -452,11 +445,8 @@ protected final void InstallSpriteLump(int lump, int frame, // used } } - */ - - - - /* + */ + /* * OLDER, UNUSED VERSION * * R_InitSpriteDefs Pass a null terminated list of sprite names (4 chars @@ -468,9 +458,9 @@ protected final void InstallSpriteLump(int lump, int frame, * frame, and a number for the rotation. A sprite that is flippable will * have an additional letter/number appended. The rotation character can * be 0 to signify no rotations. - */ + */ - /* public void InitSpriteDefs2(String[] namelist) { + /* public void InitSpriteDefs2(String[] namelist) { int intname; int frame; @@ -599,7 +589,5 @@ protected final void InstallSpriteLump(int lump, int frame, } } - */ - - } - + */ +} diff --git a/src/rr/TextureManager.java b/src/rr/TextureManager.java index 3ab5be63..c19b217e 100644 --- a/src/rr/TextureManager.java +++ b/src/rr/TextureManager.java @@ -12,48 +12,46 @@ * @author Velktron * */ +public interface TextureManager extends IGetColumn, IGetCachedColumn, IGetSmpColumn { + + public final static String[] texturelumps = {"TEXTURE1", "TEXTURE2"}; + public final static int NUMTEXLUMPS = texturelumps.length; + public final static int TEXTURE1 = 0; + public final static int TEXTURE2 = 1; + + int TextureNumForName(String texname); + + /**The "num" expected here is the internal flat number, + * not the absolute lump number. So impement accordingly. + * + * @param flatname + * @return + */ + int FlatNumForName(String flatname); -public interface TextureManager extends IGetColumn, IGetCachedColumn,IGetSmpColumn{ - - public final static String[] texturelumps={"TEXTURE1","TEXTURE2"}; - public final static int NUMTEXLUMPS=texturelumps.length; - public final static int TEXTURE1=0; - public final static int TEXTURE2=1; - - int TextureNumForName(String texname); - - - /**The "num" expected here is the internal flat number, - * not the absolute lump number. So impement accordingly. - * - * @param flatname - * @return - */ - int FlatNumForName(String flatname); - @R_Data.C(R_PrecacheLevel) - void PrecacheLevel() throws IOException; - - void GenerateComposite(int tex); - - int getTextureheight(int texnum); - - int getTextureTranslation(int texnum); - - int getFlatTranslation(int flatnum); - - void setTextureTranslation(int texnum, int amount); - - void setFlatTranslation(int flatnum,int amount); - - int CheckTextureNumForName(String texnamem); - - String CheckTextureNameForNum(int texnum); - + void PrecacheLevel() throws IOException; + + void GenerateComposite(int tex); + + int getTextureheight(int texnum); + + int getTextureTranslation(int texnum); + + int getFlatTranslation(int flatnum); + + void setTextureTranslation(int texnum, int amount); + + void setFlatTranslation(int flatnum, int amount); + + int CheckTextureNumForName(String texnamem); + + String CheckTextureNameForNum(int texnum); + int getTexturewidthmask(int tex); - + int getTextureColumnLump(int tex, int col); - + char getTextureColumnOfs(int tex, int col); T[] getTextureComposite(int tex); @@ -65,7 +63,6 @@ public interface TextureManager extends IGetColumn, IGetCachedColumn,IG void InitTextures() throws IOException; //int getFirstFlat(); - int getSkyTextureMid(); int getSkyFlatNum(); @@ -80,30 +77,25 @@ public interface TextureManager extends IGetColumn, IGetCachedColumn,IG void GenerateLookup(int texnum) throws IOException; - - int getFlatLumpNum(int flatnum); + int getFlatLumpNum(int flatnum); - T getRogueColumn(int lump, int column); + T getRogueColumn(int lump, int column); patch_t getMaskedComposite(int tex); - void GenerateMaskedComposite(int texnum); - + /** Return a "sanitized" patch. If data is insufficient, return * a default patch or attempt a partial draw. * * @param patchnum * @return */ - public T getSafeFlat(int flatnum); - column_t GetColumnStruct(int tex, int col); - void setSMPVars(int nUMMASKEDTHREADS); - - } + +} diff --git a/src/rr/UnifiedRenderer.java b/src/rr/UnifiedRenderer.java index 88fe03fb..d17f3afd 100644 --- a/src/rr/UnifiedRenderer.java +++ b/src/rr/UnifiedRenderer.java @@ -2,6 +2,9 @@ import doom.DoomMain; import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import rr.drawfuns.R_DrawColumnBoom; import rr.drawfuns.R_DrawColumnBoomLow; import rr.drawfuns.R_DrawColumnBoomOpt; @@ -16,6 +19,8 @@ public abstract class UnifiedRenderer extends RendererState { + private static final Logger LOGGER = Loggers.getLogger(UnifiedRenderer.class.getName()); + public UnifiedRenderer(DoomMain DOOM) { super(DOOM); this.MySegs = new Segs(this); @@ -57,7 +62,7 @@ public HiColor(DoomMain DOOM) { final int LIGHTLEVELS = colormaps.lightLevels(); final int MAXLIGHTSCALE = colormaps.maxLightScale(); final int MAXLIGHTZ = colormaps.maxLightZ(); - + colormaps.scalelight = new short[LIGHTLEVELS][MAXLIGHTSCALE][]; colormaps.scalelightfixed = new short[MAXLIGHTSCALE][]; colormaps.zlight = new short[LIGHTLEVELS][MAXLIGHTZ][]; @@ -73,7 +78,7 @@ public HiColor(DoomMain DOOM) { @Override protected void InitColormaps() throws IOException { colormaps.colormaps = DOOM.graphicSystem.getColorMap(); - System.out.println("COLORS15 Colormaps: " + colormaps.colormaps.length); + LOGGER.log(Level.FINE, String.format("COLORS15 Colormaps: %d", colormaps.colormaps.length)); // MAES: blurry effect is hardcoded to this colormap. BLURRY_MAP = DOOM.graphicSystem.getBlurryTable(); @@ -123,12 +128,12 @@ public static final class Indexed extends UnifiedRenderer { public Indexed(DoomMain DOOM) { super(DOOM); - + // Init light levels final int LIGHTLEVELS = colormaps.lightLevels(); final int MAXLIGHTSCALE = colormaps.maxLightScale(); final int MAXLIGHTZ = colormaps.maxLightZ(); - + colormaps.scalelight = new byte[LIGHTLEVELS][MAXLIGHTSCALE][]; colormaps.scalelightfixed = new byte[MAXLIGHTSCALE][]; colormaps.zlight = new byte[LIGHTLEVELS][MAXLIGHTZ][]; @@ -199,7 +204,7 @@ public TrueColor(DoomMain DOOM) { final int LIGHTLEVELS = colormaps.lightLevels(); final int MAXLIGHTSCALE = colormaps.maxLightScale(); final int MAXLIGHTZ = colormaps.maxLightZ(); - + colormaps.scalelight = new int[LIGHTLEVELS][MAXLIGHTSCALE][]; colormaps.scalelightfixed = new int[MAXLIGHTSCALE][]; colormaps.zlight = new int[LIGHTLEVELS][MAXLIGHTZ][]; @@ -214,7 +219,7 @@ public TrueColor(DoomMain DOOM) { */ protected void InitColormaps() throws IOException { colormaps.colormaps = DOOM.graphicSystem.getColorMap(); - System.out.println("COLORS32 Colormaps: " + colormaps.colormaps.length); + LOGGER.log(Level.FINE, String.format("COLORS32 Colormaps: %d", colormaps.colormaps.length)); // MAES: blurry effect is hardcoded to this colormap. BLURRY_MAP = DOOM.graphicSystem.getBlurryTable(); diff --git a/src/rr/ViewVars.java b/src/rr/ViewVars.java index a484ea7b..c4340881 100644 --- a/src/rr/ViewVars.java +++ b/src/rr/ViewVars.java @@ -12,20 +12,18 @@ public class ViewVars { public ViewVars(VideoScale vs) { - negonearray = new short[vs.getScreenWidth()]; // MAES: in scaling - screenheightarray = new short[vs.getScreenWidth()];// MAES: in scaling - xtoviewangle = new long[vs.getScreenWidth() + 1]; - C2JUtils.memset(negonearray, (short)-1, negonearray.length); + negonearray = new short[vs.getScreenWidth()]; // MAES: in scaling + screenheightarray = new short[vs.getScreenWidth()];// MAES: in scaling + xtoviewangle = new long[vs.getScreenWidth() + 1]; + C2JUtils.memset(negonearray, (short) -1, negonearray.length); } - - - + // Found in draw_c. Only ever used in renderer. public int windowx; public int windowy; public int width; public int height; - + // MAES: outsiders have no business peeking into this. // Or...well..maybe they do. It's only used to center the "pause" X // position. @@ -33,7 +31,7 @@ public ViewVars(VideoScale vs) { public int scaledwidth; public int centerx; public int centery; - + /** Used to determine the view center and projection in view units fixed_t */ public int centerxfrac, centeryfrac, projection; @@ -51,25 +49,24 @@ public ViewVars(VideoScale vs) { public player_t player; /** Heretic/freeview stuff? */ - public int lookdir; - + // 0 = high, 1 = low. Normally only the menu and the interface can change // that. public int detailshift; - + public int WEAPONADJUST; public int BOBADJUST; - - /** - * constant arrays used for psprite clipping and initializing clipping - */ + + /** + * constant arrays used for psprite clipping and initializing clipping + */ public final short[] negonearray; // MAES: in scaling public short[] screenheightarray;// MAES: in scaling - + /** Mirrors the one in renderer... */ public long[] xtoviewangle; - + public final long PointToAngle(int x, int y) { // MAES: note how we don't use &BITS32 here. That is because // we know that the maximum possible value of tantoangle is angle @@ -78,8 +75,9 @@ public final long PointToAngle(int x, int y) { x -= this.x; y -= this.y; - if ((x == 0) && (y == 0)) + if ((x == 0) && (y == 0)) { return 0; + } if (x >= 0) { // x >=0 @@ -134,16 +132,16 @@ public final long PointToAngle(int x, int y) { // This is actually unreachable. // return 0; } - - public final int getViewWindowX(){ + + public final int getViewWindowX() { return windowx; } - public final int getViewWindowY(){ + public final int getViewWindowY() { return windowy; } - - public final int getScaledViewWidth(){ + + public final int getScaledViewWidth() { return scaledwidth; } diff --git a/src/rr/VisSprites.java b/src/rr/VisSprites.java index b4abc62e..573f923d 100644 --- a/src/rr/VisSprites.java +++ b/src/rr/VisSprites.java @@ -6,10 +6,13 @@ import static data.Tables.ANG45; import static data.Tables.BITS32; import java.util.Arrays; +import java.util.logging.Level; +import java.util.logging.Logger; import static m.fixed_t.FRACBITS; import static m.fixed_t.FRACUNIT; import static m.fixed_t.FixedDiv; import static m.fixed_t.FixedMul; +import mochadoom.Loggers; import p.mobj_t; import static p.mobj_t.MF_SHADOW; import static rr.SceneRenderer.MINZ; @@ -23,10 +26,11 @@ * * @param */ - public final class VisSprites implements IVisSpriteManagement { + private static final Logger LOGGER = Loggers.getLogger(VisSprites.class.getName()); + private final static boolean DEBUG = false; private final static boolean RANGECHECK = false; @@ -34,7 +38,7 @@ public final class VisSprites protected final RendererState rendererState; public VisSprites(RendererState rendererState) { - vissprite_t tmp = new vissprite_t(); + vissprite_t tmp = new vissprite_t<>(); vissprites = C2JUtils.createArrayOfObjects(tmp, MAXVISSPRITES); this.rendererState = rendererState; } @@ -48,18 +52,17 @@ public VisSprites(RendererState rendererState) { // UNUSED // private final vissprite_t unsorted; // private final vissprite_t vsprsortedhead; - // Cache those you get from the sprite manager protected int[] spritewidth, spriteoffset, spritetopoffset; /** * R_AddSprites During BSP traversal, this adds sprites by sector. */ - @Override public void AddSprites(sector_t sec) { - if (DEBUG) - System.out.println("AddSprites"); + if (DEBUG) { + LOGGER.log(Level.FINER, "AddSprites"); + } mobj_t thing; int lightnum; @@ -67,24 +70,27 @@ public void AddSprites(sector_t sec) { // A sector might have been split into several // subsectors during BSP building. // Thus we check whether its already added. - if (sec.validcount == rendererState.getValidCount()) + if (sec.validcount == rendererState.getValidCount()) { return; + } // Well, now it will be done. sec.validcount = rendererState.getValidCount(); lightnum = (sec.lightlevel >> rendererState.colormaps.lightSegShift()) + rendererState.colormaps.extralight; - if (lightnum < 0) + if (lightnum < 0) { rendererState.colormaps.spritelights = rendererState.colormaps.scalelight[0]; - else if (lightnum >= rendererState.colormaps.lightLevels()) + } else if (lightnum >= rendererState.colormaps.lightLevels()) { rendererState.colormaps.spritelights = rendererState.colormaps.scalelight[rendererState.colormaps.lightLevels() - 1]; - else + } else { rendererState.colormaps.spritelights = rendererState.colormaps.scalelight[lightnum]; + } // Handle all things in sector. - for (thing = sec.thinglist; thing != null; thing = (mobj_t) thing.snext) + for (thing = sec.thinglist; thing != null; thing = (mobj_t) thing.snext) { ProjectSprite(thing); + } } /** @@ -123,8 +129,9 @@ protected final void ProjectSprite(mobj_t thing) { tz = gxt - gyt; // thing is behind view plane? - if (tz < MINZ) + if (tz < MINZ) { return; + } /* MAES: so projection/tz gives horizontal scale */ xscale = FixedDiv(rendererState.view.projection, tz); @@ -133,20 +140,23 @@ protected final void ProjectSprite(mobj_t thing) { tx = -(gyt + gxt); // too far off the side? - if (Math.abs(tx) > (tz << 2)) + if (Math.abs(tx) > (tz << 2)) { return; + } // decide which patch to use for sprite relative to player if (RANGECHECK) { - if (thing.mobj_sprite.ordinal() >= rendererState.DOOM.spriteManager.getNumSprites()) + if (thing.mobj_sprite.ordinal() >= rendererState.DOOM.spriteManager.getNumSprites()) { rendererState.DOOM.doomSystem.Error("R_ProjectSprite: invalid sprite number %d ", - thing.mobj_sprite); + thing.mobj_sprite); + } } sprdef = rendererState.DOOM.spriteManager.getSprite(thing.mobj_sprite.ordinal()); if (RANGECHECK) { - if ((thing.mobj_frame & FF_FRAMEMASK) >= sprdef.numframes) + if ((thing.mobj_frame & FF_FRAMEMASK) >= sprdef.numframes) { rendererState.DOOM.doomSystem.Error("R_ProjectSprite: invalid sprite frame %d : %d ", - thing.mobj_sprite, thing.mobj_frame); + thing.mobj_sprite, thing.mobj_frame); + } } sprframe = sprdef.spriteframes[thing.mobj_frame & FF_FRAMEMASK]; @@ -167,15 +177,17 @@ protected final void ProjectSprite(mobj_t thing) { x1 = (rendererState.view.centerxfrac + FixedMul(tx, xscale)) >> FRACBITS; // off the right side? - if (x1 > rendererState.view.width) + if (x1 > rendererState.view.width) { return; + } tx += spritewidth[lump]; x2 = ((rendererState.view.centerxfrac + FixedMul(tx, xscale)) >> FRACBITS) - 1; // off the left side - if (x2 < 0) + if (x2 < 0) { return; + } // store information in a vissprite vis = NewVisSprite(); @@ -202,8 +214,9 @@ protected final void ProjectSprite(mobj_t thing) { vis.xiscale = iscale; } - if (vis.x1 > x1) + if (vis.x1 > x1) { vis.startfrac += vis.xiscale * (vis.x1 - x1); + } vis.patch = lump; // get light level @@ -218,14 +231,13 @@ protected final void ProjectSprite(mobj_t thing) { // full bright vis.colormap = (V) rendererState.colormaps.colormaps[Palettes.COLORMAP_FIXED]; // vis.pcolormap=0; - } - - else { + } else { // diminished light index = xscale >> (rendererState.colormaps.lightScaleShift() - rendererState.view.detailshift); - if (index >= rendererState.colormaps.maxLightScale()) + if (index >= rendererState.colormaps.maxLightScale()) { index = rendererState.colormaps.maxLightScale() - 1; + } vis.colormap = rendererState.colormaps.spritelights[index]; // vis.pcolormap=index; @@ -262,7 +274,6 @@ public void cacheSpriteManager(ISpriteManager SM) { /** * R_ClearSprites Called at frame start. */ - @Override public void ClearSprites() { // vissprite_p = vissprites; @@ -270,27 +281,24 @@ public void ClearSprites() { } // UNUSED private final vissprite_t overflowsprite = new vissprite_t(); - protected final void ResizeSprites() { - vissprites = - C2JUtils.resize(vissprites[0], vissprites, vissprites.length * 2); // Bye - // bye, - // old - // vissprites. + vissprites + = C2JUtils.resize(vissprites[0], vissprites, vissprites.length * 2); // Bye + // bye, + // old + // vissprites. } /** * R_SortVisSprites UNUSED more efficient Comparable sorting + built-in * Arrays.sort function used. */ - @Override public final void SortVisSprites() { Arrays.sort(vissprites, 0, vissprite_p); // Maes: got rid of old vissprite sorting code. Java's is better // Hell, almost anything was better than that. - } @Override @@ -304,10 +312,11 @@ public vissprite_t[] getVisSprites() { } public void resetLimits() { - vissprite_t[] tmp = - C2JUtils.createArrayOfObjects(vissprites[0], MAXVISSPRITES); + vissprite_t[] tmp + = C2JUtils.createArrayOfObjects(vissprites[0], MAXVISSPRITES); System.arraycopy(vissprites, 0, tmp, 0, MAXVISSPRITES); // Now, that was quite a haircut!. - vissprites = tmp; } -} \ No newline at end of file + vissprites = tmp; + } +} diff --git a/src/rr/Visplanes.java b/src/rr/Visplanes.java index 1c2e744f..38f66807 100644 --- a/src/rr/Visplanes.java +++ b/src/rr/Visplanes.java @@ -6,7 +6,10 @@ import static data.Tables.finecosine; import static data.Tables.finesine; import java.util.Arrays; +import java.util.logging.Level; +import java.util.logging.Logger; import static m.fixed_t.FixedDiv; +import mochadoom.Loggers; import utils.C2JUtils; import v.scale.VideoScale; @@ -14,40 +17,39 @@ * This allows more encapsulation and some neat hacks like sharing * visplane data among parallel renderers, without duplicating them. */ - public class Visplanes { - private static final boolean DEBUG2=false; + private static final Logger LOGGER = Loggers.getLogger(Visplanes.class.getName()); + + private static final boolean DEBUG2 = false; protected final ViewVars view; protected final TextureManager TexMan; protected final VideoScale vs; - - public Visplanes(VideoScale vs, ViewVars view, TextureManager TexMan){ + + public Visplanes(VideoScale vs, ViewVars view, TextureManager TexMan) { this.vs = vs; - this.view=view; - this.TexMan=TexMan; + this.view = view; + this.TexMan = TexMan; MAXOPENINGS = vs.getScreenWidth() * 64; openings = new short[MAXOPENINGS]; BLANKCACHEDHEIGHT = new int[vs.getScreenHeight()]; yslope = new int[vs.getScreenHeight()]; } - // HACK: An all zeroes array used for fast clearing of certain visplanes. - public int[] cachedheight,BLANKCACHEDHEIGHT; + public int[] cachedheight, BLANKCACHEDHEIGHT; - /** To treat as fixed_t */ public int basexscale, baseyscale; - + /** To treat at fixed_t */ protected int[] yslope; - + // initially. public int MAXVISPLANES = Limits.MAXVISPLANES; public int MAXOPENINGS; - + /** visplane_t*, treat as indexes into visplanes */ public int lastvisplane, floorplane, ceilingplane; public visplane_t[] visplanes = new visplane_t[MAXVISPLANES]; @@ -59,57 +61,54 @@ public Visplanes(VideoScale vs, ViewVars view, TextureManager TexMan){ public short[] openings; /** Maes: this is supposed to be a pointer inside openings */ public int lastopening; - + protected int skyscale; - /** * Call only after visplanes have been properly resized for resolution. * In case of dynamic resolution changes, the old ones should just be * discarded, as they would be nonsensical. */ - public void initVisplanes() { cachedheight = new int[vs.getScreenHeight()]; Arrays.setAll(visplanes, j -> new visplane_t()); } - - public int getBaseXScale(){ + + public int getBaseXScale() { return basexscale; } - public int getBaseYScale(){ + public int getBaseYScale() { return baseyscale; } - public int getSkyScale(){ + public int getSkyScale() { return skyscale; } - + public void setSkyScale(int i) { - skyscale=i; + skyscale = i; } - - public int getLength(){ + + public int getLength() { return visplanes.length; } - + /** Return the last of visplanes, allocating a new one if needed */ - - public visplane_t allocate(){ + public visplane_t allocate() { if (lastvisplane == visplanes.length) { // visplane overflows could occur at this point. resizeVisplanes(); } - + return visplanes[lastvisplane++]; } - + public final void resizeVisplanes() { // Bye bye, old visplanes. - visplanes = C2JUtils.resize(visplanes[0], visplanes, visplanes.length*2); + visplanes = C2JUtils.resize(visplanes[0], visplanes, visplanes.length * 2); } - + /** * R_FindPlane * @@ -126,7 +125,6 @@ public final void resizeVisplanes() { * @param lightlevel * @return was visplane_t*, returns index into visplanes[] */ - public final int FindPlane(int height, int picnum, int lightlevel) { // System.out.println("\tChecking for visplane merging..."); int check = 0; // visplane_t* @@ -168,12 +166,11 @@ public final int FindPlane(int height, int picnum, int lightlevel) { return check; } - + /** * R_ClearPlanes At begining of frame. * */ - public void ClearPlanes() { int angle; @@ -182,7 +179,6 @@ public void ClearPlanes() { * setting them "just outside" the borders of the screen (-1 and * viewheight). */ - // Point to #1 in visplane list? OK... ?! lastvisplane = 0; @@ -205,7 +201,7 @@ public void ClearPlanes() { basexscale = FixedDiv(finecosine[angle], view.centerxfrac); baseyscale = -FixedDiv(finesine[angle], view.centerxfrac); } - + /** * R_CheckPlane * @@ -214,12 +210,11 @@ public void ClearPlanes() { * Presumably decides if a visplane should be split or not? * */ - public int CheckPlane(int index, int start, int stop) { - if (DEBUG2) - System.out.println("Checkplane " + index + " between " + start - + " and " + stop); + if (DEBUG2) { + LOGGER.log(Level.FINER, String.format("Checkplane %d between %d and %d", index, start, stop)); + } // Interval ? int intrl; @@ -231,8 +226,9 @@ public int CheckPlane(int index, int start, int stop) { // OK, so we check out ONE particular visplane. visplane_t pl = visplanes[index]; - if (DEBUG2) - System.out.println("Checking out plane " + pl); + if (DEBUG2) { + LOGGER.log(Level.FINER, String.format("Checking out plane %s", String.valueOf(pl))); + } int x; @@ -271,7 +267,6 @@ public int CheckPlane(int index, int start, int stop) { // Same as before, for for stop and maxx. // This time, intrh comes before unionh. // - if (stop > pl.maxx) { intrh = pl.maxx; unionh = stop; @@ -283,17 +278,17 @@ public int CheckPlane(int index, int start, int stop) { // An interval is now defined, which is entirely contained in the // visplane. // - // If the value FF is NOT stored ANYWWHERE inside it, we bail out // early - for (x = intrl; x <= intrh; x++) - if (pl.getTop(x) != Character.MAX_VALUE) + for (x = intrl; x <= intrh; x++) { + if (pl.getTop(x) != Character.MAX_VALUE) { break; + } + } // This can only occur if the loop above completes, // else the visplane we were checking has non-visible/clipped // portions within that range: we must split. - if (x > intrh) { // Merge the visplane pl.minx = unionl; @@ -305,8 +300,7 @@ public int CheckPlane(int index, int start, int stop) { // SPLIT: make a new visplane at "last" position, copying materials // and light. - - visplane_t last=allocate(); + visplane_t last = allocate(); last.height = pl.height; last.picnum = pl.picnum; last.lightlevel = pl.lightlevel; @@ -319,11 +313,10 @@ public int CheckPlane(int index, int start, int stop) { pl.clearTop(); // return pl; - // System.out.println("New plane created: "+pl); return lastvisplane - 1; } - + /* /** @@ -332,13 +325,13 @@ public int CheckPlane(int index, int start, int stop) { * convenience, but we can search them in the hashtable too -as a bonus, we * can reuse previously created planes that match newer ones-. */ - /* + /* Hashtable planehash = new Hashtable( 128); visplane_t check = new visplane_t(); - */ + */ - /* + /* protected final int FindPlane2(int height, int picnum, int lightlevel) { // System.out.println("\tChecking for visplane merging..."); // int check=0; // visplane_t* @@ -395,6 +388,5 @@ protected final int FindPlane2(int height, int picnum, int lightlevel) { return checknum; } - */ - + */ } diff --git a/src/rr/base_ratio_t.java b/src/rr/base_ratio_t.java index 81fc2409..00fc881f 100644 --- a/src/rr/base_ratio_t.java +++ b/src/rr/base_ratio_t.java @@ -2,21 +2,21 @@ public class base_ratio_t { - public base_ratio_t(int base_width, int base_height, int psprite_offset, + public base_ratio_t(int base_width, int base_height, int psprite_offset, int multiplier, float gl_ratio) { this.base_width = base_width; this.base_height = base_height; this.psprite_offset = psprite_offset; this.multiplier = multiplier; - this.gl_ratio = (float) (RMUL*gl_ratio); + this.gl_ratio = (float) (RMUL * gl_ratio); } -public int base_width; // Base width (unused) - public int base_height; // Base height (used for wall visibility multiplier) - public int psprite_offset; // Psprite offset (needed for "tallscreen" modes) - public int multiplier; // Width or height multiplier - public float gl_ratio; - - public static final double RMUL =1.6d/1.333333d; - -} \ No newline at end of file + public int base_width; // Base width (unused) + public int base_height; // Base height (used for wall visibility multiplier) + public int psprite_offset; // Psprite offset (needed for "tallscreen" modes) + public int multiplier; // Width or height multiplier + public float gl_ratio; + + public static final double RMUL = 1.6d / 1.333333d; + +} diff --git a/src/rr/cliprange_t.java b/src/rr/cliprange_t.java index 07f2d232..b93ef08f 100644 --- a/src/rr/cliprange_t.java +++ b/src/rr/cliprange_t.java @@ -7,15 +7,15 @@ public cliprange_t(int first, int last) { this.last = last; } - public cliprange_t(){ - + public cliprange_t() { + } - + public int first; public int last; - - public void copy(cliprange_t from){ - this.first=from.first; - this.last=from.last; + + public void copy(cliprange_t from) { + this.first = from.first; + this.last = from.last; } } diff --git a/src/rr/column_t.java b/src/rr/column_t.java index ec55b78b..a95a7ddf 100644 --- a/src/rr/column_t.java +++ b/src/rr/column_t.java @@ -2,7 +2,6 @@ import java.io.IOException; import java.nio.ByteBuffer; - import utils.C2JUtils; import w.CacheableDoomObject; @@ -12,95 +11,90 @@ * some stuff to make my life easier. * */ +public class column_t implements CacheableDoomObject { -public class column_t implements CacheableDoomObject{ - /** Static buffers used during I/O. * There's ABSO-FUCKING-LUTELY no reason to manipulate them externally!!! * I'M NOT KIDDING!!!11!! */ - - private static final int[] guesspostofs=new int[256]; - private static final short[] guesspostlens=new short[256]; - private static final short[] guesspostdeltas=new short[256]; - - + private static final int[] guesspostofs = new int[256]; + private static final short[] guesspostlens = new short[256]; + private static final short[] guesspostdeltas = new short[256]; + // MAES: there are useless, since the renderer is using raw byte data anyway, and the per-post // data is available in the special arrays. // public short topdelta; // -1 is the last post in a column (actually 0xFF, since this was unsigned???) // public short length; // length data bytes follows (actually add +2) - //public column_t[] posts; // This is quite tricky to read. + //public column_t[] posts; // This is quite tricky to read. /** The RAW data (includes initial header and padding, because no post gets preferential treatment). */ - public byte[] data; + public byte[] data; /** Actual number of posts inside this column. All guesswork is done while loading */ - public int posts; - /** Positions of posts inside the raw data (point at headers) */ - public int[] postofs; - /** Posts lengths, intended as actual drawable pixels. Add +4 to get the whole post length */ - public short[] postlen; - /** Vertical offset of each post. In theory it should be possible to quickly - * clip to the next visible post when drawing a column */ - public short[] postdeltas; - + public int posts; + /** Positions of posts inside the raw data (point at headers) */ + public int[] postofs; + /** Posts lengths, intended as actual drawable pixels. Add +4 to get the whole post length */ + public short[] postlen; + /** Vertical offset of each post. In theory it should be possible to quickly + * clip to the next visible post when drawing a column */ + public short[] postdeltas; + @Override - public void unpack(ByteBuffer buf) throws IOException { - // Mark current position. - buf.mark(); - int skipped=0; - short postlen=0; - int colheight=0; - int len=0; // How long is the WHOLE column, until the final FF? - int postno=0; // Actual number of posts. - int topdelta=0; - int prevdelta=-1; // HACK for DeepSea tall patches. - - // Scan every byte until we encounter an 0xFF which definitively marks the end of a column. - while((topdelta=C2JUtils.toUnsignedByte(buf.get()))!=0xFF){ - - // From the wiki: - // A column's topdelta is compared to the previous column's topdelta - // (or to -1 if there is no previous column in this row). If the new - // topdelta is lesser than the previous, it is interpreted as a tall - // patch and the two values are added together, the sum serving as the - // current column's actual offset. - - int tmp=topdelta; - - if (topdelta { - +public class ColFuncs { + public DoomColumnFunction main; public DoomColumnFunction base; diff --git a/src/rr/drawfuns/ColVars.java b/src/rr/drawfuns/ColVars.java index 97db2606..34afd651 100644 --- a/src/rr/drawfuns/ColVars.java +++ b/src/rr/drawfuns/ColVars.java @@ -6,21 +6,21 @@ * parallelize them. Any questions? * */ +public class ColVars { -public class ColVars { /** when passing dc_source around, also set this */ public T dc_source; public int dc_source_ofs; - + public T dc_translation; public int viewheight; - + /** Used by functions that accept transparency or other special * remapping tables. * */ public T tranmap; - + public int centery; public int dc_iscale; @@ -29,7 +29,7 @@ public class ColVars { public int dc_x; public int dc_yh; public int dc_yl; - + public int dc_flags; /** @@ -39,30 +39,27 @@ public class ColVars { * Now, whether this should be made bytes or shorts or chars or even ints * is debatable. */ - public V dc_colormap; /** Copies all BUT flags */ - - public final void copyFrom(ColVars dcvars) { - this.dc_source=dcvars.dc_source; - this.dc_colormap=dcvars.dc_colormap; - this.dc_source_ofs=dcvars.dc_source_ofs; - this.viewheight=dcvars.viewheight; - this.centery=dcvars.centery; - this.dc_x=dcvars.dc_x; - this.dc_yh=dcvars.dc_yh; - this.dc_yl=dcvars.dc_yl; - this.dc_texturemid=dcvars.dc_texturemid; - this.dc_iscale=dcvars.dc_iscale; - this.dc_texheight=dcvars.dc_texheight; + public final void copyFrom(ColVars dcvars) { + this.dc_source = dcvars.dc_source; + this.dc_colormap = dcvars.dc_colormap; + this.dc_source_ofs = dcvars.dc_source_ofs; + this.viewheight = dcvars.viewheight; + this.centery = dcvars.centery; + this.dc_x = dcvars.dc_x; + this.dc_yh = dcvars.dc_yh; + this.dc_yl = dcvars.dc_yl; + this.dc_texturemid = dcvars.dc_texturemid; + this.dc_iscale = dcvars.dc_iscale; + this.dc_texheight = dcvars.dc_texheight; } - + /** Assigns specific flags */ - public void copyFrom(ColVars dcvars,int flags) { + public void copyFrom(ColVars dcvars, int flags) { this.copyFrom(dcvars); - this.dc_flags=flags; + this.dc_flags = flags; } - } diff --git a/src/rr/drawfuns/ColumnFunction.java b/src/rr/drawfuns/ColumnFunction.java index 4e683a3c..88a3e176 100644 --- a/src/rr/drawfuns/ColumnFunction.java +++ b/src/rr/drawfuns/ColumnFunction.java @@ -5,12 +5,12 @@ * @author velktron * */ +public interface ColumnFunction { -public interface ColumnFunction { public void invoke(); - - public void invoke(ColVars dcvars); - - /** A set of flags that help identifying the type of function */ - public int getFlags(); -} \ No newline at end of file + + public void invoke(ColVars dcvars); + + /** A set of flags that help identifying the type of function */ + public int getFlags(); +} diff --git a/src/rr/drawfuns/DcFlags.java b/src/rr/drawfuns/DcFlags.java index 38afd967..abf607a9 100644 --- a/src/rr/drawfuns/DcFlags.java +++ b/src/rr/drawfuns/DcFlags.java @@ -6,10 +6,10 @@ * @author velktron * */ - public final class DcFlags { - public static final int FUZZY=0x1; - public static final int TRANSLATED=0x2; - public static final int TRANSPARENT=0x4; - public static final int LOW_DETAIL=0x8; + + public static final int FUZZY = 0x1; + public static final int TRANSLATED = 0x2; + public static final int TRANSPARENT = 0x4; + public static final int LOW_DETAIL = 0x8; } diff --git a/src/rr/drawfuns/DoomColumnFunction.java b/src/rr/drawfuns/DoomColumnFunction.java index 9f971749..26724fbf 100644 --- a/src/rr/drawfuns/DoomColumnFunction.java +++ b/src/rr/drawfuns/DoomColumnFunction.java @@ -9,34 +9,33 @@ * * @param */ +public abstract class DoomColumnFunction implements ColumnFunction { -public abstract class DoomColumnFunction implements ColumnFunction{ - - protected final boolean RANGECHECK=false; + protected final boolean RANGECHECK = false; protected final int SCREENWIDTH; protected final int SCREENHEIGHT; - protected ColVars dcvars; + protected ColVars dcvars; protected final V screen; protected final IDoomSystem I; protected final int[] ylookup; protected final int[] columnofs; protected BlurryTable blurryTable; protected int flags; - - public DoomColumnFunction(int sCREENWIDTH, int sCREENHEIGHT,int[] ylookup, - int[] columnofs, ColVars dcvars, V screen,IDoomSystem I) { + + public DoomColumnFunction(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, + int[] columnofs, ColVars dcvars, V screen, IDoomSystem I) { SCREENWIDTH = sCREENWIDTH; SCREENHEIGHT = sCREENHEIGHT; - this.ylookup=ylookup; - this.columnofs=columnofs; + this.ylookup = ylookup; + this.columnofs = columnofs; this.dcvars = dcvars; this.screen = screen; - this.I=I; - this.blurryTable=null; + this.I = I; + this.blurryTable = null; } - - public DoomColumnFunction(int sCREENWIDTH, int sCREENHEIGHT,int[] ylookup, - int[] columnofs, ColVars dcvars, V screen,IDoomSystem I, BlurryTable BLURRY_MAP) { + + public DoomColumnFunction(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, + int[] columnofs, ColVars dcvars, V screen, IDoomSystem I, BlurryTable BLURRY_MAP) { SCREENWIDTH = sCREENWIDTH; SCREENHEIGHT = sCREENHEIGHT; this.ylookup = ylookup; @@ -47,11 +46,12 @@ public DoomColumnFunction(int sCREENWIDTH, int sCREENHEIGHT,int[] ylookup, this.blurryTable = BLURRY_MAP; } - protected final void performRangeCheck(){ - if (dcvars.dc_x >= SCREENWIDTH || dcvars.dc_yl < 0 || dcvars.dc_yh >= SCREENHEIGHT) + protected final void performRangeCheck() { + if (dcvars.dc_x >= SCREENWIDTH || dcvars.dc_yl < 0 || dcvars.dc_yh >= SCREENHEIGHT) { I.Error("R_DrawColumn: %d to %d at %d", dcvars.dc_yl, dcvars.dc_yh, dcvars.dc_x); + } } - + /** * * Use ylookup LUT to avoid multiply with ScreenWidth. @@ -59,7 +59,6 @@ protected final void performRangeCheck(){ * * @return Framebuffer destination address. */ - protected final int computeScreenDest() { return ylookup[dcvars.dc_yl] + columnofs[dcvars.dc_x]; } @@ -73,14 +72,14 @@ protected final int blockyDest2() { } @Override - public final void invoke(ColVars dcvars) { - this.dcvars=dcvars; + public final void invoke(ColVars dcvars) { + this.dcvars = dcvars; invoke(); } - + @Override - public final int getFlags(){ + public final int getFlags() { return this.flags; } - + } diff --git a/src/rr/drawfuns/DoomSpanFunction.java b/src/rr/drawfuns/DoomSpanFunction.java index a4d1410b..c7bb483f 100644 --- a/src/rr/drawfuns/DoomSpanFunction.java +++ b/src/rr/drawfuns/DoomSpanFunction.java @@ -2,29 +2,29 @@ import i.IDoomSystem; -public abstract class DoomSpanFunction implements SpanFunction { - - protected final boolean RANGECHECK=false; +public abstract class DoomSpanFunction implements SpanFunction { + + protected final boolean RANGECHECK = false; protected final int SCREENWIDTH; protected final int SCREENHEIGHT; - protected SpanVars dsvars; + protected SpanVars dsvars; protected final int[] ylookup; protected final int[] columnofs; protected final V screen; protected final IDoomSystem I; - + public DoomSpanFunction(int sCREENWIDTH, int sCREENHEIGHT, - int[] ylookup, int[] columnofs,SpanVars dsvars, V screen,IDoomSystem I) { + int[] ylookup, int[] columnofs, SpanVars dsvars, V screen, IDoomSystem I) { SCREENWIDTH = sCREENWIDTH; SCREENHEIGHT = sCREENHEIGHT; - this.ylookup=ylookup; - this.columnofs=columnofs; + this.ylookup = ylookup; + this.columnofs = columnofs; this.dsvars = dsvars; this.screen = screen; - this.I=I; + this.I = I; } - - protected final void doRangeCheck(){ + + protected final void doRangeCheck() { if (dsvars.ds_x2 < dsvars.ds_x1 || dsvars.ds_x1 < 0 || dsvars.ds_x2 >= SCREENWIDTH || dsvars.ds_y > SCREENHEIGHT) { I.Error("R_DrawSpan: %d to %d at %d", dsvars.ds_x1, dsvars.ds_x2, dsvars.ds_y); @@ -32,9 +32,9 @@ protected final void doRangeCheck(){ } @Override - public final void invoke(SpanVars dsvars) { - this.dsvars=dsvars; + public final void invoke(SpanVars dsvars) { + this.dsvars = dsvars; invoke(); } - + } diff --git a/src/rr/drawfuns/R_DrawColumn.java b/src/rr/drawfuns/R_DrawColumn.java index a67ce475..13218a99 100644 --- a/src/rr/drawfuns/R_DrawColumn.java +++ b/src/rr/drawfuns/R_DrawColumn.java @@ -1,16 +1,15 @@ package rr.drawfuns; -import static m.fixed_t.FRACBITS; import i.IDoomSystem; - - /** - * Adapted from Killough's Boom code. There are optimized as well as - * low-detail versions of it. - * - * @author admin - * - */ +import static m.fixed_t.FRACBITS; +/** + * Adapted from Killough's Boom code. There are optimized as well as + * low-detail versions of it. + * + * @author admin + * + */ /** * A column is a vertical slice/span from a wall texture that, given the * DOOM style restrictions on the view orientation, will always have @@ -18,15 +17,14 @@ * used. It has also been used with Wolfenstein 3D. MAES: this is called * mostly from inside Draw and from an external "Renderer" */ +public final class R_DrawColumn extends DoomColumnFunction { -public final class R_DrawColumn extends DoomColumnFunction { - public R_DrawColumn(int SCREENWIDTH, int SCREENHEIGHT, - int[] ylookup, int[] columnofs, ColVars dcvars, + int[] ylookup, int[] columnofs, ColVars dcvars, short[] screen, IDoomSystem I) { super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); } - + public void invoke() { int count; // byte* dest; @@ -40,12 +38,14 @@ public void invoke() { // colmask = (byte) Math.min(dc_source.length-dc_source_ofs-1,127); // Zero length, column does not exceed a pixel. - if (count <= 0) + if (count <= 0) { return; + } if (RANGECHECK) { - if (dcvars.dc_x >= SCREENWIDTH || dcvars.dc_yl < 0 || dcvars.dc_yh >= SCREENHEIGHT) + if (dcvars.dc_x >= SCREENWIDTH || dcvars.dc_yl < 0 || dcvars.dc_yh >= SCREENHEIGHT) { I.Error("R_DrawColumn: %i to %i at %i", dcvars.dc_yl, dcvars.dc_yh, dcvars.dc_x); + } } // Trying to draw a masked column? Then something gross will happen. @@ -55,7 +55,6 @@ public void invoke() { * count=dc_source.length-dc_source_ofs-1; dc_source_ofs=0; * //dc_yl=dc_yh-count; gross=true; } */ - dest = computeScreenDest(); // Determine scaling, @@ -91,4 +90,4 @@ public void invoke() { } while (count-- > 0); } -} \ No newline at end of file +} diff --git a/src/rr/drawfuns/R_DrawColumnBoom.java b/src/rr/drawfuns/R_DrawColumnBoom.java index 52f31986..de4a141c 100644 --- a/src/rr/drawfuns/R_DrawColumnBoom.java +++ b/src/rr/drawfuns/R_DrawColumnBoom.java @@ -1,7 +1,10 @@ package rr.drawfuns; -import static m.fixed_t.FRACBITS; import i.IDoomSystem; +import java.util.logging.Level; +import java.util.logging.Logger; +import static m.fixed_t.FRACBITS; +import mochadoom.Loggers; /** * Adapted from Killough's Boom code. There are optimized as well as low-detail @@ -9,10 +12,11 @@ * * @author admin */ - public abstract class R_DrawColumnBoom extends DoomColumnFunction { + private static final Logger LOGGER = Loggers.getLogger(R_DrawColumnBoom.class.getName()); + public R_DrawColumnBoom(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, int[] columnofs, ColVars dcvars, V screen, IDoomSystem I) { super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); @@ -37,7 +41,9 @@ public void invoke() { count = dcvars.dc_yh - dcvars.dc_yl + 1; if (count <= 0) // Zero length, column does not exceed a pixel. + { return; + } if (RANGECHECK) { performRangeCheck(); @@ -46,71 +52,71 @@ public void invoke() { dest = computeScreenDest(); // Determine scaling, which is the only mapping to be done. - fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Inner loop that does the actual texture mapping, // e.g. a DDA-lile scaling. // This is as fast as it gets. (Yeah, right!!! -- killough) // // killough 2/1/98: more performance tuning - { final byte[] source = dcvars.dc_source; final short[] colormap = dcvars.dc_colormap; int heightmask = dcvars.dc_texheight - 1; if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 - // -- + // -- // killough { heightmask++; heightmask <<= FRACBITS; - if (frac < 0) + if (frac < 0) { while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) + } else { + while (frac >= heightmask) { frac -= heightmask; + } + } do { // Re-map color indices from wall texture column // using a lighting/special effects LUT. // heightmask is the Tutti-Frutti fix -- killoughdcvars - - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS))]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS))]]; dest += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) + if ((frac += fracstep) >= heightmask) { frac -= heightmask; + } } while (--count > 0); } else { while (count >= 4) // texture height is a power of 2 -- - // killough + // killough { // System.err.println(dest); - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; count -= 4; @@ -118,12 +124,13 @@ public void invoke() { while (count > 0) { try { - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; } catch (Exception e) { - System.err.printf("%s %s %x %x %x\n", colormap, - source, dc_source_ofs, frac, heightmask); + LOGGER.log(Level.WARNING, + String.format("%s %s %x %x %x", colormap, + source, dc_source_ofs, frac, heightmask)); } dest += SCREENWIDTH; frac += fracstep; @@ -153,7 +160,9 @@ public void invoke() { count = dcvars.dc_yh - dcvars.dc_yl + 1; if (count <= 0) // Zero length, column does not exceed a pixel. + { return; + } if (RANGECHECK) { performRangeCheck(); @@ -162,71 +171,71 @@ public void invoke() { dest = computeScreenDest(); // Determine scaling, which is the only mapping to be done. - fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Inner loop that does the actual texture mapping, // e.g. a DDA-lile scaling. // This is as fast as it gets. (Yeah, right!!! -- killough) // // killough 2/1/98: more performance tuning - { final byte[] source = dcvars.dc_source; final byte[] colormap = dcvars.dc_colormap; int heightmask = dcvars.dc_texheight - 1; if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 - // -- + // -- // killough { heightmask++; heightmask <<= FRACBITS; - if (frac < 0) + if (frac < 0) { while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) + } else { + while (frac >= heightmask) { frac -= heightmask; + } + } do { // Re-map color indices from wall texture column // using a lighting/special effects LUT. // heightmask is the Tutti-Frutti fix -- killoughdcvars - - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS))]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS))]]; dest += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) + if ((frac += fracstep) >= heightmask) { frac -= heightmask; + } } while (--count > 0); } else { while (count >= 4) // texture height is a power of 2 -- - // killough + // killough { // System.err.println(dest); - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; count -= 4; @@ -234,12 +243,13 @@ public void invoke() { while (count > 0) { try { - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; } catch (Exception e) { - System.err.printf("%s %s %x %x %x\n", colormap, - source, dc_source_ofs, frac, heightmask); + LOGGER.log(Level.WARNING, + String.format("%s %s %x %x %x\n", colormap, + source, dc_source_ofs, frac, heightmask)); } dest += SCREENWIDTH; frac += fracstep; @@ -269,7 +279,9 @@ public void invoke() { count = dcvars.dc_yh - dcvars.dc_yl + 1; if (count <= 0) // Zero length, column does not exceed a pixel. + { return; + } if (RANGECHECK) { performRangeCheck(); @@ -278,71 +290,71 @@ public void invoke() { dest = computeScreenDest(); // Determine scaling, which is the only mapping to be done. - fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Inner loop that does the actual texture mapping, // e.g. a DDA-lile scaling. // This is as fast as it gets. (Yeah, right!!! -- killough) // // killough 2/1/98: more performance tuning - { final byte[] source = dcvars.dc_source; final int[] colormap = dcvars.dc_colormap; int heightmask = dcvars.dc_texheight - 1; if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 - // -- + // -- // killough { heightmask++; heightmask <<= FRACBITS; - if (frac < 0) + if (frac < 0) { while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) + } else { + while (frac >= heightmask) { frac -= heightmask; + } + } do { // Re-map color indices from wall texture column // using a lighting/special effects LUT. // heightmask is the Tutti-Frutti fix -- killoughdcvars - - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS))]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS))]]; dest += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) + if ((frac += fracstep) >= heightmask) { frac -= heightmask; + } } while (--count > 0); } else { while (count >= 4) // texture height is a power of 2 -- - // killough + // killough { // System.err.println(dest); - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; count -= 4; @@ -350,12 +362,13 @@ public void invoke() { while (count > 0) { try { - screen[dest] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; } catch (Exception e) { - System.err.printf("%s %s %x %x %x\n", colormap, - source, dc_source_ofs, frac, heightmask); + LOGGER.log(Level.WARNING, + String.format("%s %s %x %x %x\n", colormap, + source, dc_source_ofs, frac, heightmask)); } dest += SCREENWIDTH; frac += fracstep; @@ -365,4 +378,4 @@ public void invoke() { } } } -} \ No newline at end of file +} diff --git a/src/rr/drawfuns/R_DrawColumnBoomLow.java b/src/rr/drawfuns/R_DrawColumnBoomLow.java index f0254fef..d2163d47 100644 --- a/src/rr/drawfuns/R_DrawColumnBoomLow.java +++ b/src/rr/drawfuns/R_DrawColumnBoomLow.java @@ -9,7 +9,6 @@ * * @author admin */ - public abstract class R_DrawColumnBoomLow extends DoomColumnFunction { @@ -40,7 +39,9 @@ public void invoke() { dc_source_ofs = dcvars.dc_source_ofs; if (count <= 0) // Zero length, column does not exceed a pixel. + { return; + } if (RANGECHECK) { performRangeCheck(); @@ -53,80 +54,80 @@ public void invoke() { dest2 = blockyDest2(); // Determine scaling, which is the only mapping to be done. - fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Inner loop that does the actual texture mapping, // e.g. a DDA-lile scaling. // This is as fast as it gets. (Yeah, right!!! -- killough) // // killough 2/1/98: more performance tuning - { final byte[] source = dcvars.dc_source; final short[] colormap = dcvars.dc_colormap; int heightmask = dcvars.dc_texheight - 1; if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 - // -- + // -- // killough { heightmask++; heightmask <<= FRACBITS; - if (frac < 0) + if (frac < 0) { while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) + } else { + while (frac >= heightmask) { frac -= heightmask; + } + } do { // Re-map color indices from wall texture column // using a lighting/special effects LUT. // heightmask is the Tutti-Frutti fix -- killough - - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[((frac >> FRACBITS))]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[((frac >> FRACBITS))]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) + if ((frac += fracstep) >= heightmask) { frac -= heightmask; + } } while (--count > 0); } else { while (count >= 4) // texture height is a power of 2 -- - // killough + // killough { - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; @@ -134,10 +135,10 @@ public void invoke() { } while (count > 0) { - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; @@ -168,7 +169,9 @@ public void invoke() { dc_source_ofs = dcvars.dc_source_ofs; if (count <= 0) // Zero length, column does not exceed a pixel. + { return; + } if (RANGECHECK) { performRangeCheck(); @@ -181,80 +184,80 @@ public void invoke() { dest2 = blockyDest2(); // Determine scaling, which is the only mapping to be done. - fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Inner loop that does the actual texture mapping, // e.g. a DDA-lile scaling. // This is as fast as it gets. (Yeah, right!!! -- killough) // // killough 2/1/98: more performance tuning - { final byte[] source = dcvars.dc_source; final byte[] colormap = dcvars.dc_colormap; int heightmask = dcvars.dc_texheight - 1; if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 - // -- + // -- // killough { heightmask++; heightmask <<= FRACBITS; - if (frac < 0) + if (frac < 0) { while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) + } else { + while (frac >= heightmask) { frac -= heightmask; + } + } do { // Re-map color indices from wall texture column // using a lighting/special effects LUT. // heightmask is the Tutti-Frutti fix -- killough - - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[((frac >> FRACBITS))]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[((frac >> FRACBITS))]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) + if ((frac += fracstep) >= heightmask) { frac -= heightmask; + } } while (--count > 0); } else { while (count >= 4) // texture height is a power of 2 -- - // killough + // killough { - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; @@ -262,10 +265,10 @@ public void invoke() { } while (count > 0) { - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; @@ -277,8 +280,7 @@ public void invoke() { } - - public static final class TrueColor + public static final class TrueColor extends R_DrawColumnBoomLow { public TrueColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, @@ -298,7 +300,9 @@ public void invoke() { dc_source_ofs = dcvars.dc_source_ofs; if (count <= 0) // Zero length, column does not exceed a pixel. + { return; + } if (RANGECHECK) { performRangeCheck(); @@ -311,80 +315,80 @@ public void invoke() { dest2 = blockyDest2(); // Determine scaling, which is the only mapping to be done. - fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Inner loop that does the actual texture mapping, // e.g. a DDA-lile scaling. // This is as fast as it gets. (Yeah, right!!! -- killough) // // killough 2/1/98: more performance tuning - { final byte[] source = dcvars.dc_source; final int[] colormap = dcvars.dc_colormap; int heightmask = dcvars.dc_texheight - 1; if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 - // -- + // -- // killough { heightmask++; heightmask <<= FRACBITS; - if (frac < 0) + if (frac < 0) { while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) + } else { + while (frac >= heightmask) { frac -= heightmask; + } + } do { // Re-map color indices from wall texture column // using a lighting/special effects LUT. // heightmask is the Tutti-Frutti fix -- killough - - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[((frac >> FRACBITS))]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[((frac >> FRACBITS))]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) + if ((frac += fracstep) >= heightmask) { frac -= heightmask; + } } while (--count > 0); } else { while (count >= 4) // texture height is a power of 2 -- - // killough + // killough { - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; @@ -392,10 +396,10 @@ public void invoke() { } while (count > 0) { - screen[dest] = - screen[dest2] = - colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = screen[dest2] + = colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; @@ -405,5 +409,5 @@ public void invoke() { } } } - -} \ No newline at end of file + +} diff --git a/src/rr/drawfuns/R_DrawColumnBoomOpt.java b/src/rr/drawfuns/R_DrawColumnBoomOpt.java index 4570388f..63c94580 100644 --- a/src/rr/drawfuns/R_DrawColumnBoomOpt.java +++ b/src/rr/drawfuns/R_DrawColumnBoomOpt.java @@ -9,7 +9,6 @@ * * @author admin */ - public abstract class R_DrawColumnBoomOpt extends DoomColumnFunction { @@ -21,6 +20,7 @@ public R_DrawColumnBoomOpt(int sCREENWIDTH, int sCREENHEIGHT, public static final class HiColor extends R_DrawColumnBoomOpt { + public HiColor(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, int[] columnofs, ColVars dcvars, short[] screen, IDoomSystem I) { @@ -37,7 +37,9 @@ public void invoke() { count = dcvars.dc_yh - dcvars.dc_yl + 1; if (count <= 0) // Zero length, column does not exceed a pixel. + { return; + } if (RANGECHECK) { performRangeCheck(); @@ -46,79 +48,78 @@ public void invoke() { // Framebuffer destination address. // Use ylookup LUT to avoid multiply with ScreenWidth. // Use columnofs LUT for subwindows? - dest = computeScreenDest(); // Determine scaling, which is the only mapping to be done. - fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Inner loop that does the actual texture mapping, // e.g. a DDA-lile scaling. // This is as fast as it gets. (Yeah, right!!! -- killough) // // killough 2/1/98: more performance tuning - { final byte[] source = dcvars.dc_source; final short[] colormap = dcvars.dc_colormap; int heightmask = dcvars.dc_texheight - 1; if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 - // -- + // -- // killough { heightmask++; heightmask <<= FRACBITS; - if (frac < 0) + if (frac < 0) { while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) + } else { + while (frac >= heightmask) { frac -= heightmask; + } + } do { // Re-map color indices from wall texture column // using a lighting/special effects LUT. // heightmask is the Tutti-Frutti fix -- killough - - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS))]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS))]]; dest += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) + if ((frac += fracstep) >= heightmask) { frac -= heightmask; + } } while (--count > 0); } else { while (count >= 4) // texture height is a power of 2 -- - // killough + // killough { // System.err.println(dest); - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; count -= 4; } while (count > 0) { - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; count--; @@ -130,6 +131,7 @@ public void invoke() { public static final class Indexed extends R_DrawColumnBoomOpt { + public Indexed(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, int[] columnofs, ColVars dcvars, byte[] screen, IDoomSystem I) { @@ -146,7 +148,9 @@ public void invoke() { count = dcvars.dc_yh - dcvars.dc_yl + 1; if (count <= 0) // Zero length, column does not exceed a pixel. + { return; + } if (RANGECHECK) { performRangeCheck(); @@ -155,79 +159,78 @@ public void invoke() { // Framebuffer destination address. // Use ylookup LUT to avoid multiply with ScreenWidth. // Use columnofs LUT for subwindows? - dest = computeScreenDest(); // Determine scaling, which is the only mapping to be done. - fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Inner loop that does the actual texture mapping, // e.g. a DDA-lile scaling. // This is as fast as it gets. (Yeah, right!!! -- killough) // // killough 2/1/98: more performance tuning - { final byte[] source = dcvars.dc_source; final byte[] colormap = dcvars.dc_colormap; int heightmask = dcvars.dc_texheight - 1; if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 - // -- + // -- // killough { heightmask++; heightmask <<= FRACBITS; - if (frac < 0) + if (frac < 0) { while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) + } else { + while (frac >= heightmask) { frac -= heightmask; + } + } do { // Re-map color indices from wall texture column // using a lighting/special effects LUT. // heightmask is the Tutti-Frutti fix -- killough - - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS))]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS))]]; dest += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) + if ((frac += fracstep) >= heightmask) { frac -= heightmask; + } } while (--count > 0); } else { while (count >= 4) // texture height is a power of 2 -- - // killough + // killough { // System.err.println(dest); - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; count -= 4; } while (count > 0) { - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; count--; @@ -239,6 +242,7 @@ public void invoke() { public static final class TrueColor extends R_DrawColumnBoomOpt { + public TrueColor(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, int[] columnofs, ColVars dcvars, int[] screen, IDoomSystem I) { @@ -255,7 +259,9 @@ public void invoke() { count = dcvars.dc_yh - dcvars.dc_yl + 1; if (count <= 0) // Zero length, column does not exceed a pixel. + { return; + } if (RANGECHECK) { performRangeCheck(); @@ -264,79 +270,78 @@ public void invoke() { // Framebuffer destination address. // Use ylookup LUT to avoid multiply with ScreenWidth. // Use columnofs LUT for subwindows? - dest = computeScreenDest(); // Determine scaling, which is the only mapping to be done. - fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Inner loop that does the actual texture mapping, // e.g. a DDA-lile scaling. // This is as fast as it gets. (Yeah, right!!! -- killough) // // killough 2/1/98: more performance tuning - { final byte[] source = dcvars.dc_source; final int[] colormap = dcvars.dc_colormap; int heightmask = dcvars.dc_texheight - 1; if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 - // -- + // -- // killough { heightmask++; heightmask <<= FRACBITS; - if (frac < 0) + if (frac < 0) { while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) + } else { + while (frac >= heightmask) { frac -= heightmask; + } + } do { // Re-map color indices from wall texture column // using a lighting/special effects LUT. // heightmask is the Tutti-Frutti fix -- killough - - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS))]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS))]]; dest += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) + if ((frac += fracstep) >= heightmask) { frac -= heightmask; + } } while (--count > 0); } else { while (count >= 4) // texture height is a power of 2 -- - // killough + // killough { // System.err.println(dest); - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; count -= 4; } while (count > 0) { - screen[dest] = - colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] + = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; frac += fracstep; count--; @@ -346,4 +351,4 @@ public void invoke() { } } -} \ No newline at end of file +} diff --git a/src/rr/drawfuns/R_DrawColumnBoomOptLow.java b/src/rr/drawfuns/R_DrawColumnBoomOptLow.java index 4483f0c3..3bc41d68 100644 --- a/src/rr/drawfuns/R_DrawColumnBoomOptLow.java +++ b/src/rr/drawfuns/R_DrawColumnBoomOptLow.java @@ -10,37 +10,37 @@ * @author admin * */ +public abstract class R_DrawColumnBoomOptLow extends DoomColumnFunction { -public abstract class R_DrawColumnBoomOptLow extends DoomColumnFunction { - - public R_DrawColumnBoomOptLow(int SCREENWIDTH, int SCREENHEIGHT, - int[] ylookup, int[] columnofs, ColVars dcvars, - V screen, IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); - this.flags=DcFlags.LOW_DETAIL; - } - - - public static final class HiColor extends R_DrawColumnBoomOptLow{ - - public HiColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, ColVars dcvars, - short[] screen, IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); - } + public R_DrawColumnBoomOptLow(int SCREENWIDTH, int SCREENHEIGHT, + int[] ylookup, int[] columnofs, ColVars dcvars, + V screen, IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); + this.flags = DcFlags.LOW_DETAIL; + } + + public static final class HiColor extends R_DrawColumnBoomOptLow { + + public HiColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, ColVars dcvars, + short[] screen, IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); + } public void invoke() { int count; - int dest,dest2; // killough + int dest, dest2; // killough int frac; // killough final int fracstep; count = dcvars.dc_yh - dcvars.dc_yl + 1; // Assumed to be always zero for optimized draws. //dc_source_ofs=dcvars.dc_source_ofs; - + if (count <= 0) // Zero length, column does not exceed a pixel. + { return; + } if (RANGECHECK) { performRangeCheck(); @@ -51,9 +51,8 @@ public void invoke() { // Use columnofs LUT for subwindows? dest = blockyDest1(); dest2 = blockyDest2(); - - // Determine scaling, which is the only mapping to be done. + // Determine scaling, which is the only mapping to be done. fracstep = dcvars.dc_iscale; frac = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * fracstep; @@ -62,54 +61,55 @@ public void invoke() { // This is as fast as it gets. (Yeah, right!!! -- killough) // // killough 2/1/98: more performance tuning - { final byte[] source = dcvars.dc_source; final short[] colormap = dcvars.dc_colormap; int heightmask = dcvars.dc_texheight - 1; if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 -- - // killough + // killough { heightmask++; heightmask <<= FRACBITS; - if (frac < 0) + if (frac < 0) { while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) + } else { + while (frac >= heightmask) { frac -= heightmask; + } + } do { // Re-map color indices from wall texture column // using a lighting/special effects LUT. // heightmask is the Tutti-Frutti fix -- killough - - screen[dest] = screen[dest2]=colormap[0x00FF & source[((frac >> FRACBITS))]]; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS))]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) + if ((frac += fracstep) >= heightmask) { frac -= heightmask; + } } while (--count > 0); } else { while (count >= 4) // texture height is a power of 2 -- - // killough + // killough { - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; @@ -117,7 +117,7 @@ public void invoke() { } while (count > 0) { - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; @@ -126,221 +126,224 @@ public void invoke() { } } } - } - - public static final class Indexed extends R_DrawColumnBoomOptLow{ - - public Indexed(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, ColVars dcvars, - byte[] screen, IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); - } - - public void invoke() { - int count; - int dest,dest2; // killough - int frac; // killough - final int fracstep; - - count = dcvars.dc_yh - dcvars.dc_yl + 1; - // Assumed to be always zero for optimized draws. - //dc_source_ofs=dcvars.dc_source_ofs; - - if (count <= 0) // Zero length, column does not exceed a pixel. - return; - - if (RANGECHECK) { - performRangeCheck(); - } - - // Framebuffer destination address. - // Use ylookup LUT to avoid multiply with ScreenWidth. - // Use columnofs LUT for subwindows? - dest = blockyDest1(); - dest2 = blockyDest2(); - - // Determine scaling, which is the only mapping to be done. - - fracstep = dcvars.dc_iscale; - frac = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * fracstep; - - // Inner loop that does the actual texture mapping, - // e.g. a DDA-lile scaling. - // This is as fast as it gets. (Yeah, right!!! -- killough) - // - // killough 2/1/98: more performance tuning - - { - final byte[] source = dcvars.dc_source; - final byte[] colormap = dcvars.dc_colormap; - int heightmask = dcvars.dc_texheight - 1; - if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 -- - // killough - { - heightmask++; - heightmask <<= FRACBITS; - - if (frac < 0) - while ((frac += heightmask) < 0) + } + + public static final class Indexed extends R_DrawColumnBoomOptLow { + + public Indexed(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, ColVars dcvars, + byte[] screen, IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); + } + + public void invoke() { + int count; + int dest, dest2; // killough + int frac; // killough + final int fracstep; + + count = dcvars.dc_yh - dcvars.dc_yl + 1; + // Assumed to be always zero for optimized draws. + //dc_source_ofs=dcvars.dc_source_ofs; + + if (count <= 0) // Zero length, column does not exceed a pixel. + { + return; + } + + if (RANGECHECK) { + performRangeCheck(); + } + + // Framebuffer destination address. + // Use ylookup LUT to avoid multiply with ScreenWidth. + // Use columnofs LUT for subwindows? + dest = blockyDest1(); + dest2 = blockyDest2(); + + // Determine scaling, which is the only mapping to be done. + fracstep = dcvars.dc_iscale; + frac = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * fracstep; + + // Inner loop that does the actual texture mapping, + // e.g. a DDA-lile scaling. + // This is as fast as it gets. (Yeah, right!!! -- killough) + // + // killough 2/1/98: more performance tuning + { + final byte[] source = dcvars.dc_source; + final byte[] colormap = dcvars.dc_colormap; + int heightmask = dcvars.dc_texheight - 1; + if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 -- + // killough + { + heightmask++; + heightmask <<= FRACBITS; + + if (frac < 0) { + while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) - frac -= heightmask; - - do { - // Re-map color indices from wall texture column - // using a lighting/special effects LUT. - - // heightmask is the Tutti-Frutti fix -- killough - - screen[dest] = screen[dest2]=colormap[0x00FF & source[((frac >> FRACBITS))]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) - frac -= heightmask; - } while (--count > 0); - } else { - while (count >= 4) // texture height is a power of 2 -- - // killough - { - - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - frac += fracstep; - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - frac += fracstep; - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - frac += fracstep; - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - frac += fracstep; - count -= 4; - } - - while (count > 0) { - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - frac += fracstep; - count--; - } - } - } - } - } - - public static final class TrueColor extends R_DrawColumnBoomOptLow{ - - public TrueColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, ColVars dcvars, - int[] screen, IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); - } - - public void invoke() { - int count; - int dest,dest2; // killough - int frac; // killough - final int fracstep; - - count = dcvars.dc_yh - dcvars.dc_yl + 1; - // Assumed to be always zero for optimized draws. - //dc_source_ofs=dcvars.dc_source_ofs; - - if (count <= 0) // Zero length, column does not exceed a pixel. - return; - - if (RANGECHECK) { - performRangeCheck(); - } - - // Framebuffer destination address. - // Use ylookup LUT to avoid multiply with ScreenWidth. - // Use columnofs LUT for subwindows? - dest = blockyDest1(); - dest2 = blockyDest2(); - - // Determine scaling, which is the only mapping to be done. - - fracstep = dcvars.dc_iscale; - frac = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * fracstep; - - // Inner loop that does the actual texture mapping, - // e.g. a DDA-lile scaling. - // This is as fast as it gets. (Yeah, right!!! -- killough) - // - // killough 2/1/98: more performance tuning - - { - final byte[] source = dcvars.dc_source; - final int[] colormap = dcvars.dc_colormap; - int heightmask = dcvars.dc_texheight - 1; - if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 -- - // killough - { - heightmask++; - heightmask <<= FRACBITS; - - if (frac < 0) - while ((frac += heightmask) < 0) + } else { + while (frac >= heightmask) { + frac -= heightmask; + } + } + + do { + // Re-map color indices from wall texture column + // using a lighting/special effects LUT. + + // heightmask is the Tutti-Frutti fix -- killough + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS))]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + if ((frac += fracstep) >= heightmask) { + frac -= heightmask; + } + } while (--count > 0); + } else { + while (count >= 4) // texture height is a power of 2 -- + // killough + { + + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + frac += fracstep; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + frac += fracstep; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + frac += fracstep; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + frac += fracstep; + count -= 4; + } + + while (count > 0) { + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + frac += fracstep; + count--; + } + } + } + } + } + + public static final class TrueColor extends R_DrawColumnBoomOptLow { + + public TrueColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, ColVars dcvars, + int[] screen, IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); + } + + public void invoke() { + int count; + int dest, dest2; // killough + int frac; // killough + final int fracstep; + + count = dcvars.dc_yh - dcvars.dc_yl + 1; + // Assumed to be always zero for optimized draws. + //dc_source_ofs=dcvars.dc_source_ofs; + + if (count <= 0) // Zero length, column does not exceed a pixel. + { + return; + } + + if (RANGECHECK) { + performRangeCheck(); + } + + // Framebuffer destination address. + // Use ylookup LUT to avoid multiply with ScreenWidth. + // Use columnofs LUT for subwindows? + dest = blockyDest1(); + dest2 = blockyDest2(); + + // Determine scaling, which is the only mapping to be done. + fracstep = dcvars.dc_iscale; + frac = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * fracstep; + + // Inner loop that does the actual texture mapping, + // e.g. a DDA-lile scaling. + // This is as fast as it gets. (Yeah, right!!! -- killough) + // + // killough 2/1/98: more performance tuning + { + final byte[] source = dcvars.dc_source; + final int[] colormap = dcvars.dc_colormap; + int heightmask = dcvars.dc_texheight - 1; + if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 -- + // killough + { + heightmask++; + heightmask <<= FRACBITS; + + if (frac < 0) { + while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) - frac -= heightmask; - - do { - // Re-map color indices from wall texture column - // using a lighting/special effects LUT. - - // heightmask is the Tutti-Frutti fix -- killough - - screen[dest] = screen[dest2]=colormap[0x00FF & source[((frac >> FRACBITS))]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) - frac -= heightmask; - } while (--count > 0); - } else { - while (count >= 4) // texture height is a power of 2 -- - // killough - { - - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - frac += fracstep; - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - frac += fracstep; - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - frac += fracstep; - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - frac += fracstep; - count -= 4; - } - - while (count > 0) { - screen[dest] = screen[dest2]= colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - frac += fracstep; - count--; - } - } - } - } - } - - - } \ No newline at end of file + } else { + while (frac >= heightmask) { + frac -= heightmask; + } + } + + do { + // Re-map color indices from wall texture column + // using a lighting/special effects LUT. + + // heightmask is the Tutti-Frutti fix -- killough + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS))]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + if ((frac += fracstep) >= heightmask) { + frac -= heightmask; + } + } while (--count > 0); + } else { + while (count >= 4) // texture height is a power of 2 -- + // killough + { + + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + frac += fracstep; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + frac += fracstep; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + frac += fracstep; + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + frac += fracstep; + count -= 4; + } + + while (count > 0) { + screen[dest] = screen[dest2] = colormap[0x00FF & source[((frac >> FRACBITS) & heightmask)]]; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + frac += fracstep; + count--; + } + } + } + } + } + +} diff --git a/src/rr/drawfuns/R_DrawColumnBoomSuperOpt.java b/src/rr/drawfuns/R_DrawColumnBoomSuperOpt.java index b96ab4f2..f3b855ad 100644 --- a/src/rr/drawfuns/R_DrawColumnBoomSuperOpt.java +++ b/src/rr/drawfuns/R_DrawColumnBoomSuperOpt.java @@ -3,7 +3,6 @@ import i.IDoomSystem; import static m.fixed_t.FRACBITS; - /** * Adapted from Killough's Boom code. Specially super-optimized version assuming * that dc_source_ofs is always 0, AND that frac>>FRACBITS can be eliminated by @@ -12,103 +11,103 @@ * @author admin * */ - -public final class R_DrawColumnBoomSuperOpt extends DoomColumnFunction { - - public R_DrawColumnBoomSuperOpt(int SCREENWIDTH, int SCREENHEIGHT, - int[] ylookup, int[] columnofs, ColVars dcvars, - short[] screen, IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); - } - - public void invoke() { - int count; - int dest; // killough - int frac; // killough - final int fracstep; - - count = dcvars.dc_yh - dcvars.dc_yl + 1; - - if (count <= 0) // Zero length, column does not exceed a pixel. - return; - - if (RANGECHECK) { - performRangeCheck(); - } - - // Framebuffer destination address. - // Use ylookup LUT to avoid multiply with ScreenWidth. - // Use columnofs LUT for subwindows? - - dest = computeScreenDest(); - - // Determine scaling, which is the only mapping to be done. - - fracstep = dcvars.dc_iscale>>FRACBITS; - frac = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * fracstep; - frac>>=FRACBITS; - - // Inner loop that does the actual texture mapping, - // e.g. a DDA-lile scaling. - // This is as fast as it gets. (Yeah, right!!! -- killough) - // - // killough 2/1/98: more performance tuning - - { - final byte[] source = dcvars.dc_source; - final short[] colormap = dcvars.dc_colormap; - int heightmask = dcvars.dc_texheight - 1; - if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 -- - // killough - { - heightmask++; - heightmask <<= FRACBITS; - - if (frac < 0) - while ((frac += heightmask) < 0) +public final class R_DrawColumnBoomSuperOpt extends DoomColumnFunction { + + public R_DrawColumnBoomSuperOpt(int SCREENWIDTH, int SCREENHEIGHT, + int[] ylookup, int[] columnofs, ColVars dcvars, + short[] screen, IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); + } + + public void invoke() { + int count; + int dest; // killough + int frac; // killough + final int fracstep; + + count = dcvars.dc_yh - dcvars.dc_yl + 1; + + if (count <= 0) // Zero length, column does not exceed a pixel. + { + return; + } + + if (RANGECHECK) { + performRangeCheck(); + } + + // Framebuffer destination address. + // Use ylookup LUT to avoid multiply with ScreenWidth. + // Use columnofs LUT for subwindows? + dest = computeScreenDest(); + + // Determine scaling, which is the only mapping to be done. + fracstep = dcvars.dc_iscale >> FRACBITS; + frac = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * fracstep; + frac >>= FRACBITS; + + // Inner loop that does the actual texture mapping, + // e.g. a DDA-lile scaling. + // This is as fast as it gets. (Yeah, right!!! -- killough) + // + // killough 2/1/98: more performance tuning + { + final byte[] source = dcvars.dc_source; + final short[] colormap = dcvars.dc_colormap; + int heightmask = dcvars.dc_texheight - 1; + if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 -- + // killough + { + heightmask++; + heightmask <<= FRACBITS; + + if (frac < 0) { + while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) - frac -= heightmask; - - do { - // Re-map color indices from wall texture column - // using a lighting/special effects LUT. - - // heightmask is the Tutti-Frutti fix -- killough - - screen[dest] = colormap[0x00FF & source[frac]]; - dest += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) - frac -= heightmask; - } while (--count > 0); - } else { - while (count >= 4) // texture height is a power of 2 -- - // killough - { - // System.err.println(dest); - screen[dest] = colormap[0x00FF & source[frac & heightmask]]; - dest += SCREENWIDTH; - frac += fracstep; - screen[dest] = colormap[0x00FF & source[frac & heightmask]]; - dest += SCREENWIDTH; - frac += fracstep; - screen[dest] = colormap[0x00FF & source[frac & heightmask]]; - dest += SCREENWIDTH; - frac += fracstep; - screen[dest] = colormap[0x00FF & source[frac & heightmask]]; - dest += SCREENWIDTH; - frac += fracstep; - count -= 4; - } - - while (count > 0) { - screen[dest] = colormap[0x00FF & source[frac & heightmask]]; - dest += SCREENWIDTH; - frac += fracstep; - count--; - } - } - } - } - } \ No newline at end of file + } else { + while (frac >= heightmask) { + frac -= heightmask; + } + } + + do { + // Re-map color indices from wall texture column + // using a lighting/special effects LUT. + + // heightmask is the Tutti-Frutti fix -- killough + screen[dest] = colormap[0x00FF & source[frac]]; + dest += SCREENWIDTH; + if ((frac += fracstep) >= heightmask) { + frac -= heightmask; + } + } while (--count > 0); + } else { + while (count >= 4) // texture height is a power of 2 -- + // killough + { + // System.err.println(dest); + screen[dest] = colormap[0x00FF & source[frac & heightmask]]; + dest += SCREENWIDTH; + frac += fracstep; + screen[dest] = colormap[0x00FF & source[frac & heightmask]]; + dest += SCREENWIDTH; + frac += fracstep; + screen[dest] = colormap[0x00FF & source[frac & heightmask]]; + dest += SCREENWIDTH; + frac += fracstep; + screen[dest] = colormap[0x00FF & source[frac & heightmask]]; + dest += SCREENWIDTH; + frac += fracstep; + count -= 4; + } + + while (count > 0) { + screen[dest] = colormap[0x00FF & source[frac & heightmask]]; + dest += SCREENWIDTH; + frac += fracstep; + count--; + } + } + } + } +} diff --git a/src/rr/drawfuns/R_DrawColumnLow.java b/src/rr/drawfuns/R_DrawColumnLow.java index b9f77e79..565e2973 100644 --- a/src/rr/drawfuns/R_DrawColumnLow.java +++ b/src/rr/drawfuns/R_DrawColumnLow.java @@ -3,53 +3,54 @@ import i.IDoomSystem; import static m.fixed_t.FRACBITS; -public final class R_DrawColumnLow extends DoomColumnFunction { - - public R_DrawColumnLow(int SCREENWIDTH, int SCREENHEIGHT, - int[] ylookup, int[] columnofs, ColVars dcvars, - short[] screen, IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); - this.flags=DcFlags.LOW_DETAIL; - } - - public void invoke() { - int count; - // MAES: were pointers. Of course... - int dest, dest2; - final byte[] dc_source=dcvars.dc_source; - final short[] dc_colormap=dcvars.dc_colormap; - final int dc_source_ofs=dcvars.dc_source_ofs; - // Maes: fixed_t never used as such. - int frac; - final int fracstep; - - count = dcvars.dc_yh - dcvars.dc_yl; - - // Zero length. - if (count < 0) - return; - - if (RANGECHECK) { - performRangeCheck(); - } - - // The idea is to draw more than one pixel at a time. - dest = blockyDest1(); - dest2 = blockyDest2(); - - fracstep = dcvars.dc_iscale; - frac = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * fracstep; - // int spot=(frac >>> FRACBITS) & 127; - do { - - // Hack. Does not work correctly. - // MAES: that's good to know. - screen[dest] = screen[dest2] = dc_colormap[0x00FF & dc_source[dc_source_ofs - + ((frac >>> FRACBITS) & 127)]]; - - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - frac += fracstep; - } while (count-- != 0); - } - } \ No newline at end of file +public final class R_DrawColumnLow extends DoomColumnFunction { + + public R_DrawColumnLow(int SCREENWIDTH, int SCREENHEIGHT, + int[] ylookup, int[] columnofs, ColVars dcvars, + short[] screen, IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); + this.flags = DcFlags.LOW_DETAIL; + } + + public void invoke() { + int count; + // MAES: were pointers. Of course... + int dest, dest2; + final byte[] dc_source = dcvars.dc_source; + final short[] dc_colormap = dcvars.dc_colormap; + final int dc_source_ofs = dcvars.dc_source_ofs; + // Maes: fixed_t never used as such. + int frac; + final int fracstep; + + count = dcvars.dc_yh - dcvars.dc_yl; + + // Zero length. + if (count < 0) { + return; + } + + if (RANGECHECK) { + performRangeCheck(); + } + + // The idea is to draw more than one pixel at a time. + dest = blockyDest1(); + dest2 = blockyDest2(); + + fracstep = dcvars.dc_iscale; + frac = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * fracstep; + // int spot=(frac >>> FRACBITS) & 127; + do { + + // Hack. Does not work correctly. + // MAES: that's good to know. + screen[dest] = screen[dest2] = dc_colormap[0x00FF & dc_source[dc_source_ofs + + ((frac >>> FRACBITS) & 127)]]; + + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + frac += fracstep; + } while (count-- != 0); + } +} diff --git a/src/rr/drawfuns/R_DrawColumnUnrolled.java b/src/rr/drawfuns/R_DrawColumnUnrolled.java index bc93d456..72432d3c 100644 --- a/src/rr/drawfuns/R_DrawColumnUnrolled.java +++ b/src/rr/drawfuns/R_DrawColumnUnrolled.java @@ -1,17 +1,17 @@ package rr.drawfuns; + import i.IDoomSystem; /** - * EI VITTU, this gives a clean 25% boost. Da fack... - * - * - * @author admin - * - */ - - public final class R_DrawColumnUnrolled extends DoomColumnFunction { + * EI VITTU, this gives a clean 25% boost. Da fack... + * + * + * @author admin + * + */ +public final class R_DrawColumnUnrolled extends DoomColumnFunction { - /* + /* * That's shit, doesn't help. private final int * SCREENWIDTH2=SCREENWIDTH*2; private final int * SCREENWIDTH3=SCREENWIDTH*3; private final int @@ -20,68 +20,67 @@ public final class R_DrawColumnUnrolled extends DoomColumnFunction dcvars, - short[] screen, IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); - } + */ + public R_DrawColumnUnrolled(int SCREENWIDTH, int SCREENHEIGHT, + int[] ylookup, int[] columnofs, ColVars dcvars, + short[] screen, IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); + } - public void invoke() { - int count,dest; - final byte[] source; - final short[] colormap; - final int dc_source_ofs=dcvars.dc_source_ofs; + public void invoke() { + int count, dest; + final byte[] source; + final short[] colormap; + final int dc_source_ofs = dcvars.dc_source_ofs; - // These are all "unsigned". Watch out for bit shifts! - int frac; - final int fracstep, fracstep2, fracstep3, fracstep4; + // These are all "unsigned". Watch out for bit shifts! + int frac; + final int fracstep, fracstep2, fracstep3, fracstep4; - count = dcvars.dc_yh - dcvars.dc_yl + 1; + count = dcvars.dc_yh - dcvars.dc_yl + 1; - source = dcvars.dc_source; - // dc_source_ofs+=15; // ???? WHY - colormap = dcvars.dc_colormap; - dest = computeScreenDest(); + source = dcvars.dc_source; + // dc_source_ofs+=15; // ???? WHY + colormap = dcvars.dc_colormap; + dest = computeScreenDest(); - fracstep = dcvars.dc_iscale << 9; - frac = (dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * dcvars.dc_iscale) << 9; + fracstep = dcvars.dc_iscale << 9; + frac = (dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * dcvars.dc_iscale) << 9; - fracstep2 = fracstep + fracstep; - fracstep3 = fracstep2 + fracstep; - fracstep4 = fracstep3 + fracstep; + fracstep2 = fracstep + fracstep; + fracstep3 = fracstep2 + fracstep; + fracstep4 = fracstep3 + fracstep; - while (count > 8) { - screen[dest] = colormap[0x00FF & source[dc_source_ofs + frac >>> 25]]; - screen[dest + SCREENWIDTH] = colormap[0x00FF & source[dc_source_ofs - + (frac + fracstep) >>> 25]]; - screen[dest + SCREENWIDTH * 2] = colormap[0x00FF & source[dc_source_ofs - + (frac + fracstep2) >>> 25]]; - screen[dest + SCREENWIDTH * 3] = colormap[0x00FF & source[dc_source_ofs - + (frac + fracstep3) >>> 25]]; + while (count > 8) { + screen[dest] = colormap[0x00FF & source[dc_source_ofs + frac >>> 25]]; + screen[dest + SCREENWIDTH] = colormap[0x00FF & source[dc_source_ofs + + (frac + fracstep) >>> 25]]; + screen[dest + SCREENWIDTH * 2] = colormap[0x00FF & source[dc_source_ofs + + (frac + fracstep2) >>> 25]]; + screen[dest + SCREENWIDTH * 3] = colormap[0x00FF & source[dc_source_ofs + + (frac + fracstep3) >>> 25]]; - frac += fracstep4; + frac += fracstep4; - screen[dest + SCREENWIDTH * 4] = colormap[0x00FF & source[dc_source_ofs - + frac >>> 25]]; - screen[dest + SCREENWIDTH * 5] = colormap[0x00FF & source[dc_source_ofs - + (frac + fracstep) >>> 25]]; - screen[dest + SCREENWIDTH * 6] = colormap[0x00FF & source[dc_source_ofs - + (frac + fracstep2) >>> 25]]; - screen[dest + SCREENWIDTH * 7] = colormap[0x00FF & source[dc_source_ofs - + (frac + fracstep3) >>> 25]]; + screen[dest + SCREENWIDTH * 4] = colormap[0x00FF & source[dc_source_ofs + + frac >>> 25]]; + screen[dest + SCREENWIDTH * 5] = colormap[0x00FF & source[dc_source_ofs + + (frac + fracstep) >>> 25]]; + screen[dest + SCREENWIDTH * 6] = colormap[0x00FF & source[dc_source_ofs + + (frac + fracstep2) >>> 25]]; + screen[dest + SCREENWIDTH * 7] = colormap[0x00FF & source[dc_source_ofs + + (frac + fracstep3) >>> 25]]; - frac += fracstep4; - dest += SCREENWIDTH * 8; - count -= 8; - } + frac += fracstep4; + dest += SCREENWIDTH * 8; + count -= 8; + } - while (count > 0) { - screen[dest] = colormap[0x00FF & source[dc_source_ofs + frac >>> 25]]; - dest += SCREENWIDTH; - frac += fracstep; - count--; - } - } - } \ No newline at end of file + while (count > 0) { + screen[dest] = colormap[0x00FF & source[dc_source_ofs + frac >>> 25]]; + dest += SCREENWIDTH; + frac += fracstep; + count--; + } + } +} diff --git a/src/rr/drawfuns/R_DrawFuzzColumn.java b/src/rr/drawfuns/R_DrawFuzzColumn.java index 22215a13..e311d146 100644 --- a/src/rr/drawfuns/R_DrawFuzzColumn.java +++ b/src/rr/drawfuns/R_DrawFuzzColumn.java @@ -32,18 +32,18 @@ public abstract class R_DrawFuzzColumn extends DoomColumnFunction { public R_DrawFuzzColumn( - int SCREENWIDTH, int SCREENHEIGHT, - int[] ylookup, int[] columnofs, ColVars dcvars, - V screen, IDoomSystem I, BlurryTable BLURRY_MAP + int SCREENWIDTH, int SCREENHEIGHT, + int[] ylookup, int[] columnofs, ColVars dcvars, + V screen, IDoomSystem I, BlurryTable BLURRY_MAP ) { this(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); this.blurryTable = BLURRY_MAP; } public R_DrawFuzzColumn( - int SCREENWIDTH, int SCREENHEIGHT, - int[] ylookup, int[] columnofs, ColVars dcvars, - V screen, IDoomSystem I + int SCREENWIDTH, int SCREENHEIGHT, + int[] ylookup, int[] columnofs, ColVars dcvars, + V screen, IDoomSystem I ) { super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); this.flags = DcFlags.FUZZY; @@ -51,36 +51,33 @@ public R_DrawFuzzColumn( FUZZOFF = SCREENWIDTH; // Recompute fuzz table - - fuzzoffset = new int[]{ FUZZOFF, -FUZZOFF, FUZZOFF, -FUZZOFF, - FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, - FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, - -FUZZOFF, -FUZZOFF, -FUZZOFF, FUZZOFF, -FUZZOFF, -FUZZOFF, FUZZOFF, - FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, - FUZZOFF, -FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, -FUZZOFF, - -FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, - FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF }; + fuzzoffset = new int[]{FUZZOFF, -FUZZOFF, FUZZOFF, -FUZZOFF, + FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, + FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, + -FUZZOFF, -FUZZOFF, -FUZZOFF, FUZZOFF, -FUZZOFF, -FUZZOFF, FUZZOFF, + FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, + FUZZOFF, -FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, -FUZZOFF, + -FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, + FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF}; FUZZTABLE = fuzzoffset.length; } - protected int fuzzpos; + protected int fuzzpos; protected final int FUZZTABLE; - // // Spectre/Invisibility. // - protected final int FUZZOFF; protected final int[] fuzzoffset; public static final class Indexed extends R_DrawFuzzColumn { public Indexed( - int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, ColVars dcvars, - byte[] screen, IDoomSystem I, BlurryTable BLURRY_MAP + int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, ColVars dcvars, + byte[] screen, IDoomSystem I, BlurryTable BLURRY_MAP ) { super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I, BLURRY_MAP); } @@ -91,18 +88,21 @@ public void invoke() { int dest; // Adjust borders. Low... - if (dcvars.dc_yl == 0) + if (dcvars.dc_yl == 0) { dcvars.dc_yl = 1; + } // .. and high. - if (dcvars.dc_yh == dcvars.viewheight - 1) + if (dcvars.dc_yh == dcvars.viewheight - 1) { dcvars.dc_yh = dcvars.viewheight - 2; + } count = dcvars.dc_yh - dcvars.dc_yl; // Zero length. - if (count < 0) + if (count < 0) { return; + } if (RANGECHECK) { performRangeCheck(); @@ -123,24 +123,31 @@ public void invoke() { screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); // Clamp table lookup index. - if (++fuzzpos == FUZZTABLE) + if (++fuzzpos == FUZZTABLE) { fuzzpos = 0; + } - dest += SCREENWIDTH; + dest += SCREENWIDTH; - screen[dest] = blurryTable.computePixel(screen[dest+ fuzzoffset[fuzzpos]]); - if (++fuzzpos == FUZZTABLE) fuzzpos = 0; + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } dest += SCREENWIDTH; - screen[dest] = blurryTable.computePixel(screen[dest+ fuzzoffset[fuzzpos]]); - if (++fuzzpos == FUZZTABLE) fuzzpos = 0; + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } dest += SCREENWIDTH; - screen[dest] = blurryTable.computePixel(screen[dest+ fuzzoffset[fuzzpos]]); - if (++fuzzpos == FUZZTABLE) fuzzpos = 0; + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } dest += SCREENWIDTH; - } while ((count-=4) > 4); + } while ((count -= 4) > 4); } if (count > 0) { @@ -152,8 +159,9 @@ public void invoke() { screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); // Clamp table lookup index. - if (++fuzzpos == FUZZTABLE) + if (++fuzzpos == FUZZTABLE) { fuzzpos = 0; + } dest += SCREENWIDTH; } while (count-- > 0); @@ -164,9 +172,9 @@ public void invoke() { public static final class HiColor extends R_DrawFuzzColumn { public HiColor( - int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, ColVars dcvars, - short[] screen, IDoomSystem I, BlurryTable BLURRY_MAP + int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, ColVars dcvars, + short[] screen, IDoomSystem I, BlurryTable BLURRY_MAP ) { super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I, BLURRY_MAP); // TODO Auto-generated constructor stub @@ -178,18 +186,21 @@ public void invoke() { int dest; // Adjust borders. Low... - if (dcvars.dc_yl == 0) + if (dcvars.dc_yl == 0) { dcvars.dc_yl = 1; + } // .. and high. - if (dcvars.dc_yh == dcvars.viewheight - 1) + if (dcvars.dc_yh == dcvars.viewheight - 1) { dcvars.dc_yh = dcvars.viewheight - 2; + } count = dcvars.dc_yh - dcvars.dc_yl; // Zero length. - if (count < 0) + if (count < 0) { return; + } if (RANGECHECK) { super.performRangeCheck(); @@ -211,32 +222,40 @@ public void invoke() { screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); // Clamp table lookup index. - if (++fuzzpos == FUZZTABLE) + if (++fuzzpos == FUZZTABLE) { fuzzpos = 0; + } - dest += SCREENWIDTH; + dest += SCREENWIDTH; screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - if (++fuzzpos == FUZZTABLE) fuzzpos = 0; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } dest += SCREENWIDTH; screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - if (++fuzzpos == FUZZTABLE) fuzzpos = 0; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } dest += SCREENWIDTH; screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - if (++fuzzpos == FUZZTABLE) fuzzpos = 0; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } dest += SCREENWIDTH; - } while ((count-=4) > 4); + } while ((count -= 4) > 4); if (count > 0) { do { screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); // Clamp table lookup index. - if (++fuzzpos == FUZZTABLE) + if (++fuzzpos == FUZZTABLE) { fuzzpos = 0; + } dest += SCREENWIDTH; } while (count-- > 0); @@ -259,18 +278,21 @@ public void invoke() { int dest; // Adjust borders. Low... - if (dcvars.dc_yl == 0) + if (dcvars.dc_yl == 0) { dcvars.dc_yl = 1; + } // .. and high. - if (dcvars.dc_yh == dcvars.viewheight - 1) + if (dcvars.dc_yh == dcvars.viewheight - 1) { dcvars.dc_yh = dcvars.viewheight - 2; + } count = dcvars.dc_yh - dcvars.dc_yl; // Zero length. - if (count < 0) + if (count < 0) { return; + } if (RANGECHECK) { performRangeCheck(); @@ -292,21 +314,28 @@ public void invoke() { screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); // Clamp table lookup index. - if (++fuzzpos == FUZZTABLE) + if (++fuzzpos == FUZZTABLE) { fuzzpos = 0; + } - dest += SCREENWIDTH; + dest += SCREENWIDTH; screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - if (++fuzzpos == FUZZTABLE) fuzzpos = 0; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } dest += SCREENWIDTH; screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - if (++fuzzpos == FUZZTABLE) fuzzpos = 0; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } dest += SCREENWIDTH; screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - if (++fuzzpos == FUZZTABLE) fuzzpos = 0; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } dest += SCREENWIDTH; } while ((count -= 4) > 4); @@ -321,12 +350,13 @@ public void invoke() { screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); // Clamp table lookup index. - if (++fuzzpos == FUZZTABLE) + if (++fuzzpos == FUZZTABLE) { fuzzpos = 0; + } dest += SCREENWIDTH; } while (count-- > 0); } } } -} \ No newline at end of file +} diff --git a/src/rr/drawfuns/R_DrawFuzzColumnLow.java b/src/rr/drawfuns/R_DrawFuzzColumnLow.java index d76c9816..4ff2df07 100644 --- a/src/rr/drawfuns/R_DrawFuzzColumnLow.java +++ b/src/rr/drawfuns/R_DrawFuzzColumnLow.java @@ -29,251 +29,264 @@ */ public abstract class R_DrawFuzzColumnLow extends DoomColumnFunction { - public R_DrawFuzzColumnLow( - int SCREENWIDTH, int SCREENHEIGHT, - int[] ylookup, int[] columnofs, ColVars dcvars, - V screen, IDoomSystem I, BlurryTable BLURRY_MAP + public R_DrawFuzzColumnLow( + int SCREENWIDTH, int SCREENHEIGHT, + int[] ylookup, int[] columnofs, ColVars dcvars, + V screen, IDoomSystem I, BlurryTable BLURRY_MAP ) { - this(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); - this.blurryTable = BLURRY_MAP; - } - - public R_DrawFuzzColumnLow( - int SCREENWIDTH, int SCREENHEIGHT, - int[] ylookup, int[] columnofs, ColVars dcvars, - V screen, IDoomSystem I + this(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); + this.blurryTable = BLURRY_MAP; + } + + public R_DrawFuzzColumnLow( + int SCREENWIDTH, int SCREENHEIGHT, + int[] ylookup, int[] columnofs, ColVars dcvars, + V screen, IDoomSystem I ) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); - this.flags = DcFlags.LOW_DETAIL | DcFlags.FUZZY; + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); + this.flags = DcFlags.LOW_DETAIL | DcFlags.FUZZY; + + FUZZOFF = SCREENWIDTH; + + // Recompute fuzz table + fuzzoffset = new int[]{FUZZOFF, -FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, + FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, + FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, + -FUZZOFF, -FUZZOFF, -FUZZOFF, -FUZZOFF, FUZZOFF, -FUZZOFF, + -FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, + FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, -FUZZOFF, + FUZZOFF, FUZZOFF, -FUZZOFF, -FUZZOFF, -FUZZOFF, -FUZZOFF, + FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, + -FUZZOFF, FUZZOFF}; + } + + protected int fuzzpos; + + // + // Spectre/Invisibility. + // + protected final int FUZZOFF; + protected final int[] fuzzoffset; + + public static final class Indexed extends R_DrawFuzzColumn { + + public Indexed( + int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, ColVars dcvars, + byte[] screen, IDoomSystem I, BlurryTable BLURRY_MAP + ) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I, BLURRY_MAP); + } + + @Override + public void invoke() { + int count; + int dest, dest2; + + // Adjust borders. Low... + if (dcvars.dc_yl == 0) { + dcvars.dc_yl = 1; + } + + // .. and high. + if (dcvars.dc_yh == dcvars.viewheight - 1) { + dcvars.dc_yh = dcvars.viewheight - 2; + } + + count = dcvars.dc_yh - dcvars.dc_yl; + + // Zero length. + if (count < 0) { + return; + } + + if (RANGECHECK) { + performRangeCheck(); + } + + // The idea is to draw more than one pixel at a time. + dest = blockyDest1(); + dest2 = blockyDest2(); + + // Looks like an attempt at dithering, + // using the colormap #6 (of 0-31, a bit + // brighter than average). + if (count > 4) { + do { + // Lookup framebuffer, and retrieve + // a pixel that is either one column + // left or right of the current one. + // Add index from colormap to index. + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + screen[dest2] = screen[dest]; - FUZZOFF = SCREENWIDTH; + // Ironically, "low detail" fuzziness was not really + // low-detail, + // as it normally did full-precision calculations. + // BLURRY_MAP[0x00FF & screen[dest2+ fuzzoffset[fuzzpos]]]; + // Clamp table lookup index. + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } - // Recompute fuzz table + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; - fuzzoffset = new int[] { FUZZOFF, -FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, - FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, - FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, - -FUZZOFF, -FUZZOFF, -FUZZOFF, -FUZZOFF, FUZZOFF, -FUZZOFF, - -FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, - FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, -FUZZOFF, - FUZZOFF, FUZZOFF, -FUZZOFF, -FUZZOFF, -FUZZOFF, -FUZZOFF, - FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, - -FUZZOFF, FUZZOFF }; - } + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + screen[dest2] = screen[dest]; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; - protected int fuzzpos; + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + screen[dest2] = screen[dest]; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; - // - // Spectre/Invisibility. - // + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + screen[dest2] = screen[dest]; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + } while ((count -= 4) > 4); + } - protected final int FUZZOFF; - protected final int[] fuzzoffset; + if (count > 0) { + do { + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + screen[dest2] = screen[dest]; - public static final class Indexed extends R_DrawFuzzColumn { + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } - public Indexed( - int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, ColVars dcvars, - byte[] screen, IDoomSystem I, BlurryTable BLURRY_MAP + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + } while (count-- != 0); + } + } + } + + public static final class HiColor extends R_DrawFuzzColumn { + + public HiColor( + int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, ColVars dcvars, + short[] screen, IDoomSystem I, BlurryTable BLURRY_MAP ) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I, BLURRY_MAP); - } + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I, BLURRY_MAP); + } @Override - public void invoke() { - int count; - int dest, dest2; - - // Adjust borders. Low... - if (dcvars.dc_yl == 0) - dcvars.dc_yl = 1; - - // .. and high. - if (dcvars.dc_yh == dcvars.viewheight - 1) - dcvars.dc_yh = dcvars.viewheight - 2; - - count = dcvars.dc_yh - dcvars.dc_yl; - - // Zero length. - if (count < 0) - return; - - if (RANGECHECK) { - performRangeCheck(); - } - - // The idea is to draw more than one pixel at a time. - dest = blockyDest1(); - dest2 = blockyDest2(); - - // Looks like an attempt at dithering, - // using the colormap #6 (of 0-31, a bit - // brighter than average). - if (count > 4) { - do { - // Lookup framebuffer, and retrieve - // a pixel that is either one column - // left or right of the current one. - // Add index from colormap to index. - screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - screen[dest2] = screen[dest]; - - // Ironically, "low detail" fuzziness was not really - // low-detail, - // as it normally did full-precision calculations. - // BLURRY_MAP[0x00FF & screen[dest2+ fuzzoffset[fuzzpos]]]; - - // Clamp table lookup index. - if (++fuzzpos == FUZZTABLE) - fuzzpos = 0; - - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - - screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - screen[dest2] = screen[dest]; - if (++fuzzpos == FUZZTABLE) - fuzzpos = 0; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - - screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - screen[dest2] = screen[dest]; - if (++fuzzpos == FUZZTABLE) - fuzzpos = 0; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - - screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - screen[dest2] = screen[dest]; - if (++fuzzpos == FUZZTABLE) - fuzzpos = 0; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - } while ((count -= 4) > 4); + public void invoke() { + int count; + int dest, dest2; + + // Adjust borders. Low... + if (dcvars.dc_yl == 0) { + dcvars.dc_yl = 1; } - if (count > 0) { - do { - screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - screen[dest2] = screen[dest]; + // .. and high. + if (dcvars.dc_yh == dcvars.viewheight - 1) { + dcvars.dc_yh = dcvars.viewheight - 2; + } - if (++fuzzpos == FUZZTABLE) - fuzzpos = 0; + count = dcvars.dc_yh - dcvars.dc_yl; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - } while (count-- != 0); + // Zero length. + if (count < 0) { + return; } - } - } - - public static final class HiColor extends R_DrawFuzzColumn { - - public HiColor( - int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, ColVars dcvars, - short[] screen, IDoomSystem I, BlurryTable BLURRY_MAP - ) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I, BLURRY_MAP); - } - @Override - public void invoke() { - int count; - int dest, dest2; + if (RANGECHECK) { + performRangeCheck(); + } - // Adjust borders. Low... - if (dcvars.dc_yl == 0) - dcvars.dc_yl = 1; + // The idea is to draw more than one pixel at a time. + dest = blockyDest1(); + dest2 = blockyDest2(); - // .. and high. - if (dcvars.dc_yh == dcvars.viewheight - 1) - dcvars.dc_yh = dcvars.viewheight - 2; + // Looks like an attempt at dithering, + // using the colormap #6 (of 0-31, a bit + // brighter than average). + if (count > 4) { + do { + // Lookup framebuffer, and retrieve + // a pixel that is either one column + // left or right of the current one. + // Add index from colormap to index. + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + screen[dest2] = screen[dest]; - count = dcvars.dc_yh - dcvars.dc_yl; + // Ironically, "low detail" fuzziness was not really + // low-detail, + // as it normally did full-precision calculations. + // BLURRY_MAP[0x00FF & screen[dest2+ fuzzoffset[fuzzpos]]]; + // Clamp table lookup index. + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } - // Zero length. - if (count < 0) - return; + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; - if (RANGECHECK) { - performRangeCheck(); - } + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + screen[dest2] = screen[dest]; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; - // The idea is to draw more than one pixel at a time. - dest = blockyDest1(); - dest2 = blockyDest2(); - - // Looks like an attempt at dithering, - // using the colormap #6 (of 0-31, a bit - // brighter than average). - if (count > 4) { - do { - // Lookup framebuffer, and retrieve - // a pixel that is either one column - // left or right of the current one. - // Add index from colormap to index. - screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - screen[dest2] = screen[dest]; - - // Ironically, "low detail" fuzziness was not really - // low-detail, - // as it normally did full-precision calculations. - // BLURRY_MAP[0x00FF & screen[dest2+ fuzzoffset[fuzzpos]]]; - - // Clamp table lookup index. - if (++fuzzpos == FUZZTABLE) - fuzzpos = 0; - - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - - screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - screen[dest2] = screen[dest]; - if (++fuzzpos == FUZZTABLE) - fuzzpos = 0; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - - screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - screen[dest2] = screen[dest]; - if (++fuzzpos == FUZZTABLE) - fuzzpos = 0; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - - screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - screen[dest2] = screen[dest]; - if (++fuzzpos == FUZZTABLE) - fuzzpos = 0; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - } while ((count -= 4) > 4); - } + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + screen[dest2] = screen[dest]; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; - if (count > 0) - do { - screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); - screen[dest2] = screen[dest]; + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + screen[dest2] = screen[dest]; + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + } while ((count -= 4) > 4); + } - if (++fuzzpos == FUZZTABLE) - fuzzpos = 0; + if (count > 0) { + do { + screen[dest] = blurryTable.computePixel(screen[dest + fuzzoffset[fuzzpos]]); + screen[dest2] = screen[dest]; - dest += SCREENWIDTH; - dest2 += SCREENWIDTH; - } while (count-- != 0); + if (++fuzzpos == FUZZTABLE) { + fuzzpos = 0; + } + + dest += SCREENWIDTH; + dest2 += SCREENWIDTH; + } while (count-- != 0); + } - } - } + } + } - public static final class TrueColor extends R_DrawFuzzColumn { + public static final class TrueColor extends R_DrawFuzzColumn { public TrueColor( - int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, ColVars dcvars, - int[] screen, IDoomSystem I, BlurryTable BLURRY_MAP + int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, ColVars dcvars, + int[] screen, IDoomSystem I, BlurryTable BLURRY_MAP ) { super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I, BLURRY_MAP); } @@ -284,18 +297,21 @@ public void invoke() { int dest, dest2; // Adjust borders. Low... - if (dcvars.dc_yl == 0) + if (dcvars.dc_yl == 0) { dcvars.dc_yl = 1; + } // .. and high. - if (dcvars.dc_yh == dcvars.viewheight - 1) + if (dcvars.dc_yh == dcvars.viewheight - 1) { dcvars.dc_yh = dcvars.viewheight - 2; + } count = dcvars.dc_yh - dcvars.dc_yl; // Zero length. - if (count < 0) + if (count < 0) { return; + } if (RANGECHECK) { performRangeCheck(); @@ -308,7 +324,7 @@ public void invoke() { // Looks like an attempt at dithering, // using the colormap #6 (of 0-31, a bit // brighter than average). - if (count > 4) + if (count > 4) { do { // Lookup framebuffer, and retrieve // a pixel that is either one column @@ -321,48 +337,54 @@ public void invoke() { // low-detail, // as it normally did full-precision calculations. // BLURRY_MAP[0x00FF & screen[dest2+ fuzzoffset[fuzzpos]]]; - // Clamp table lookup index. - if (++fuzzpos == FUZZTABLE) + if (++fuzzpos == FUZZTABLE) { fuzzpos = 0; + } dest += SCREENWIDTH; dest2 += SCREENWIDTH; screen[dest] = blurryTable.computePixelFast(screen[dest + fuzzoffset[fuzzpos]]); screen[dest2] = screen[dest]; - if (++fuzzpos == FUZZTABLE) + if (++fuzzpos == FUZZTABLE) { fuzzpos = 0; + } dest += SCREENWIDTH; dest2 += SCREENWIDTH; screen[dest] = blurryTable.computePixelFast(screen[dest + fuzzoffset[fuzzpos]]); screen[dest2] = screen[dest]; - if (++fuzzpos == FUZZTABLE) + if (++fuzzpos == FUZZTABLE) { fuzzpos = 0; + } dest += SCREENWIDTH; dest2 += SCREENWIDTH; screen[dest] = blurryTable.computePixelFast(screen[dest + fuzzoffset[fuzzpos]]); screen[dest2] = screen[dest]; - if (++fuzzpos == FUZZTABLE) + if (++fuzzpos == FUZZTABLE) { fuzzpos = 0; + } dest += SCREENWIDTH; dest2 += SCREENWIDTH; } while ((count -= 4) > 4); + } - if (count > 0) + if (count > 0) { do { screen[dest] = blurryTable.computePixelFast(screen[dest + fuzzoffset[fuzzpos]]); screen[dest2] = screen[dest]; - if (++fuzzpos == FUZZTABLE) + if (++fuzzpos == FUZZTABLE) { fuzzpos = 0; + } dest += SCREENWIDTH; dest2 += SCREENWIDTH; } while (count-- != 0); + } } } -} \ No newline at end of file +} diff --git a/src/rr/drawfuns/R_DrawSpan.java b/src/rr/drawfuns/R_DrawSpan.java index d7d4ed35..a32e0200 100644 --- a/src/rr/drawfuns/R_DrawSpan.java +++ b/src/rr/drawfuns/R_DrawSpan.java @@ -8,162 +8,158 @@ * ds_frac, ds_yfrac, ds_x2, ds_x1, ds_xstep and ds_ystep must be set. * */ - public abstract class R_DrawSpan extends DoomSpanFunction { - public R_DrawSpan(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, - int[] columnofs, SpanVars dsvars, V screen, IDoomSystem I) { - super(sCREENWIDTH, sCREENHEIGHT, ylookup, columnofs, dsvars, screen, I); - // TODO Auto-generated constructor stub - } - - public static final class Indexed extends R_DrawSpan { - - public Indexed(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, SpanVars dsvars, - byte[] screen, IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dsvars, - screen, I); - } - - public void invoke() { - - int f_xfrac; // fixed_t - int f_yfrac; // fixed_t - int dest, count, spot; - final byte[] ds_colormap = dsvars.ds_colormap; - final byte[] ds_source = dsvars.ds_source; - - // System.out.println("R_DrawSpan: "+ds_x1+" to "+ds_x2+" at "+ - // ds_y); - - if (RANGECHECK) { - doRangeCheck(); - // dscount++; - } - - f_xfrac = dsvars.ds_xfrac; - f_yfrac = dsvars.ds_yfrac; - - dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; - - // We do not check for zero spans here? - count = dsvars.ds_x2 - dsvars.ds_x1; - - do { - // Current texture index in u,v. - spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) - + ((f_xfrac >> 16) & 63); - - // Lookup pixel from flat texture tile, - // re-index using light/colormap. - screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; - - // Next step in u,v. - f_xfrac += dsvars.ds_xstep; - f_yfrac += dsvars.ds_ystep; - - } while (count-- > 0); - } - } - - public static final class HiColor extends R_DrawSpan { - - public HiColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, SpanVars dsvars, - short[] screen, IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dsvars, - screen, I); - } - - public void invoke() { - - int f_xfrac; // fixed_t - int f_yfrac; // fixed_t - int dest, count, spot; - final short[] ds_colormap = dsvars.ds_colormap; - final byte[] ds_source = dsvars.ds_source; - - // System.out.println("R_DrawSpan: "+ds_x1+" to "+ds_x2+" at "+ - // ds_y); - - if (RANGECHECK) { - doRangeCheck(); - // dscount++; - } - - f_xfrac = dsvars.ds_xfrac; - f_yfrac = dsvars.ds_yfrac; - - dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; - - // We do not check for zero spans here? - count = dsvars.ds_x2 - dsvars.ds_x1; - - do { - // Current texture index in u,v. - spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) - + ((f_xfrac >> 16) & 63); - - // Lookup pixel from flat texture tile, - // re-index using light/colormap. - screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; - - // Next step in u,v. - f_xfrac += dsvars.ds_xstep; - f_yfrac += dsvars.ds_ystep; - - } while (count-- > 0); - } - } - - public static final class TrueColor extends R_DrawSpan { - - public TrueColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, SpanVars dsvars, int[] screen, - IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dsvars, - screen, I); - } + public R_DrawSpan(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, + int[] columnofs, SpanVars dsvars, V screen, IDoomSystem I) { + super(sCREENWIDTH, sCREENHEIGHT, ylookup, columnofs, dsvars, screen, I); + // TODO Auto-generated constructor stub + } - public void invoke() { + public static final class Indexed extends R_DrawSpan { - int f_xfrac; // fixed_t - int f_yfrac; // fixed_t - int dest, count, spot; - final int[] ds_colormap = dsvars.ds_colormap; - final byte[] ds_source = dsvars.ds_source; + public Indexed(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, SpanVars dsvars, + byte[] screen, IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dsvars, + screen, I); + } - // System.out.println("R_DrawSpan: "+ds_x1+" to "+ds_x2+" at "+ - // ds_y); + public void invoke() { - if (RANGECHECK) { - doRangeCheck(); - // dscount++; - } + int f_xfrac; // fixed_t + int f_yfrac; // fixed_t + int dest, count, spot; + final byte[] ds_colormap = dsvars.ds_colormap; + final byte[] ds_source = dsvars.ds_source; + + // System.out.println("R_DrawSpan: "+ds_x1+" to "+ds_x2+" at "+ + // ds_y); + if (RANGECHECK) { + doRangeCheck(); + // dscount++; + } + + f_xfrac = dsvars.ds_xfrac; + f_yfrac = dsvars.ds_yfrac; - f_xfrac = dsvars.ds_xfrac; - f_yfrac = dsvars.ds_yfrac; + dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; + + // We do not check for zero spans here? + count = dsvars.ds_x2 - dsvars.ds_x1; - dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; + do { + // Current texture index in u,v. + spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) + + ((f_xfrac >> 16) & 63); + + // Lookup pixel from flat texture tile, + // re-index using light/colormap. + screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; + + // Next step in u,v. + f_xfrac += dsvars.ds_xstep; + f_yfrac += dsvars.ds_ystep; + + } while (count-- > 0); + } + } + + public static final class HiColor extends R_DrawSpan { + + public HiColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, SpanVars dsvars, + short[] screen, IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dsvars, + screen, I); + } + + public void invoke() { + + int f_xfrac; // fixed_t + int f_yfrac; // fixed_t + int dest, count, spot; + final short[] ds_colormap = dsvars.ds_colormap; + final byte[] ds_source = dsvars.ds_source; + + // System.out.println("R_DrawSpan: "+ds_x1+" to "+ds_x2+" at "+ + // ds_y); + if (RANGECHECK) { + doRangeCheck(); + // dscount++; + } + + f_xfrac = dsvars.ds_xfrac; + f_yfrac = dsvars.ds_yfrac; + + dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; + + // We do not check for zero spans here? + count = dsvars.ds_x2 - dsvars.ds_x1; + + do { + // Current texture index in u,v. + spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) + + ((f_xfrac >> 16) & 63); + + // Lookup pixel from flat texture tile, + // re-index using light/colormap. + screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; + + // Next step in u,v. + f_xfrac += dsvars.ds_xstep; + f_yfrac += dsvars.ds_ystep; + + } while (count-- > 0); + } + } + + public static final class TrueColor extends R_DrawSpan { - // We do not check for zero spans here? - count = dsvars.ds_x2 - dsvars.ds_x1; + public TrueColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, SpanVars dsvars, int[] screen, + IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dsvars, + screen, I); + } + + public void invoke() { - do { - // Current texture index in u,v. - spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) - + ((f_xfrac >> 16) & 63); + int f_xfrac; // fixed_t + int f_yfrac; // fixed_t + int dest, count, spot; + final int[] ds_colormap = dsvars.ds_colormap; + final byte[] ds_source = dsvars.ds_source; + + // System.out.println("R_DrawSpan: "+ds_x1+" to "+ds_x2+" at "+ + // ds_y); + if (RANGECHECK) { + doRangeCheck(); + // dscount++; + } - // Lookup pixel from flat texture tile, - // re-index using light/colormap. - screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; + f_xfrac = dsvars.ds_xfrac; + f_yfrac = dsvars.ds_yfrac; - // Next step in u,v. - f_xfrac += dsvars.ds_xstep; - f_yfrac += dsvars.ds_ystep; + dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; - } while (count-- > 0); - } - } + // We do not check for zero spans here? + count = dsvars.ds_x2 - dsvars.ds_x1; + + do { + // Current texture index in u,v. + spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) + + ((f_xfrac >> 16) & 63); + + // Lookup pixel from flat texture tile, + // re-index using light/colormap. + screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; + + // Next step in u,v. + f_xfrac += dsvars.ds_xstep; + f_yfrac += dsvars.ds_ystep; + + } while (count-- > 0); + } + } } diff --git a/src/rr/drawfuns/R_DrawSpanLow.java b/src/rr/drawfuns/R_DrawSpanLow.java index 0d06fc49..52a07be3 100644 --- a/src/rr/drawfuns/R_DrawSpanLow.java +++ b/src/rr/drawfuns/R_DrawSpanLow.java @@ -11,58 +11,58 @@ public R_DrawSpanLow(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, } public static final class Indexed - extends R_DrawSpanLow { - - public Indexed(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, - int[] columnofs, SpanVars dsvars, - byte[] screen, IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dsvars, - screen, I); - } - - public void invoke() { - final byte[] ds_source = dsvars.ds_source; - final byte[] ds_colormap = dsvars.ds_colormap; - final int ds_xstep = dsvars.ds_xstep; - final int ds_ystep = dsvars.ds_ystep; - int f_xfrac = dsvars.ds_xfrac; - int f_yfrac = dsvars.ds_yfrac; - int dest; - int count; - int spot; - - if (RANGECHECK) { - doRangeCheck(); - // dscount++; - } - - // MAES: count must be performed before shifting. - count = dsvars.ds_x2 - dsvars.ds_x1; - - // Blocky mode, need to multiply by 2. - dsvars.ds_x1 <<= 1; - dsvars.ds_x2 <<= 1; - - dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; - - do { - spot = - ((f_yfrac >> (16 - 6)) & (63 * 64)) - + ((f_xfrac >> 16) & 63); - // Lowres/blocky mode does it twice, - // while scale is adjusted appropriately. - - screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; - screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; - - f_xfrac += ds_xstep; - f_yfrac += ds_ystep; - - } while (count-- > 0); - - } - } - + extends R_DrawSpanLow { + + public Indexed(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, + int[] columnofs, SpanVars dsvars, + byte[] screen, IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dsvars, + screen, I); + } + + public void invoke() { + final byte[] ds_source = dsvars.ds_source; + final byte[] ds_colormap = dsvars.ds_colormap; + final int ds_xstep = dsvars.ds_xstep; + final int ds_ystep = dsvars.ds_ystep; + int f_xfrac = dsvars.ds_xfrac; + int f_yfrac = dsvars.ds_yfrac; + int dest; + int count; + int spot; + + if (RANGECHECK) { + doRangeCheck(); + // dscount++; + } + + // MAES: count must be performed before shifting. + count = dsvars.ds_x2 - dsvars.ds_x1; + + // Blocky mode, need to multiply by 2. + dsvars.ds_x1 <<= 1; + dsvars.ds_x2 <<= 1; + + dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; + + do { + spot + = ((f_yfrac >> (16 - 6)) & (63 * 64)) + + ((f_xfrac >> 16) & 63); + // Lowres/blocky mode does it twice, + // while scale is adjusted appropriately. + + screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; + screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; + + f_xfrac += ds_xstep; + f_yfrac += ds_ystep; + + } while (count-- > 0); + + } + } + public static final class HiColor extends R_DrawSpanLow { @@ -100,9 +100,9 @@ public void invoke() { dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; do { - spot = - ((f_yfrac >> (16 - 6)) & (63 * 64)) - + ((f_xfrac >> 16) & 63); + spot + = ((f_yfrac >> (16 - 6)) & (63 * 64)) + + ((f_xfrac >> 16) & 63); // Lowres/blocky mode does it twice, // while scale is adjusted appropriately. @@ -154,9 +154,9 @@ public void invoke() { dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; do { - spot = - ((f_yfrac >> (16 - 6)) & (63 * 64)) - + ((f_xfrac >> 16) & 63); + spot + = ((f_yfrac >> (16 - 6)) & (63 * 64)) + + ((f_xfrac >> 16) & 63); // Lowres/blocky mode does it twice, // while scale is adjusted appropriately. @@ -170,4 +170,4 @@ public void invoke() { } } -} \ No newline at end of file +} diff --git a/src/rr/drawfuns/R_DrawSpanUnrolled.java b/src/rr/drawfuns/R_DrawSpanUnrolled.java index 0f688262..1303a511 100644 --- a/src/rr/drawfuns/R_DrawSpanUnrolled.java +++ b/src/rr/drawfuns/R_DrawSpanUnrolled.java @@ -8,9 +8,7 @@ * -> 130 fps with a Mul of 3.0) * */ - -public abstract class R_DrawSpanUnrolled extends DoomSpanFunction { - +public abstract class R_DrawSpanUnrolled extends DoomSpanFunction { public R_DrawSpanUnrolled(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, int[] columnofs, SpanVars dsvars, V screen, IDoomSystem I) { @@ -18,243 +16,236 @@ public R_DrawSpanUnrolled(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, // TODO Auto-generated constructor stub } - public static final class HiColor extends R_DrawSpanUnrolled{ - - - public HiColor(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, - int[] columnofs, SpanVars dsvars, short[] screen, - IDoomSystem I) { - super(sCREENWIDTH, sCREENHEIGHT, ylookup, columnofs, dsvars, screen, I); - // TODO Auto-generated constructor stub - } - - public void invoke() { - int position, step; - final byte[] source; - final short[] colormap; - int dest; - int count; - int spot; - int xtemp; - int ytemp; + public static final class HiColor extends R_DrawSpanUnrolled { - position = ((dsvars.ds_xfrac << 10) & 0xffff0000) - | ((dsvars.ds_yfrac >> 6) & 0xffff); - step = ((dsvars.ds_xstep << 10) & 0xffff0000) | ((dsvars.ds_ystep >> 6) & 0xffff); - source = dsvars.ds_source; - colormap = dsvars.ds_colormap; - dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; - count = dsvars.ds_x2 - dsvars.ds_x1 + 1; - //int rolls = 0; - while (count >= 4) { - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest] = colormap[0x00FF & source[spot]]; - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest + 1] = colormap[0x00FF & source[spot]]; - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest + 2] = colormap[0x00FF & source[spot]]; - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest + 3] = colormap[0x00FF & source[spot]]; - count -= 4; - dest += 4; - - // Half-assed attempt to fix precision by forced periodic - // realignment. + public HiColor(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, + int[] columnofs, SpanVars dsvars, short[] screen, + IDoomSystem I) { + super(sCREENWIDTH, sCREENHEIGHT, ylookup, columnofs, dsvars, screen, I); + // TODO Auto-generated constructor stub + } - /* + public void invoke() { + int position, step; + final byte[] source; + final short[] colormap; + int dest; + int count; + int spot; + int xtemp; + int ytemp; + + position = ((dsvars.ds_xfrac << 10) & 0xffff0000) + | ((dsvars.ds_yfrac >> 6) & 0xffff); + step = ((dsvars.ds_xstep << 10) & 0xffff0000) | ((dsvars.ds_ystep >> 6) & 0xffff); + source = dsvars.ds_source; + colormap = dsvars.ds_colormap; + dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; + count = dsvars.ds_x2 - dsvars.ds_x1 + 1; + //int rolls = 0; + while (count >= 4) { + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest] = colormap[0x00FF & source[spot]]; + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest + 1] = colormap[0x00FF & source[spot]]; + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest + 2] = colormap[0x00FF & source[spot]]; + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest + 3] = colormap[0x00FF & source[spot]]; + count -= 4; + dest += 4; + + // Half-assed attempt to fix precision by forced periodic + // realignment. + + /* * if ((rolls++)%64==0){ position = * ((((rolls*4)*ds_xstep+ds_xfrac) << 10) & 0xffff0000) | * ((((rolls*4)*ds_ystep+ds_yfrac) >> 6) & 0xffff); } - */ - - } - - while (count > 0) { - ytemp = position >> 4; - ytemp = ytemp & 4032; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest++] = colormap[0x00FF & source[spot]]; - count--; - } - } - - } + */ + } + + while (count > 0) { + ytemp = position >> 4; + ytemp = ytemp & 4032; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest++] = colormap[0x00FF & source[spot]]; + count--; + } + } - -public static final class Indexed extends R_DrawSpanUnrolled{ - - - public Indexed(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, - int[] columnofs, SpanVars dsvars, byte[] screen, - IDoomSystem I) { - super(sCREENWIDTH, sCREENHEIGHT, ylookup, columnofs, dsvars, screen, I); - // TODO Auto-generated constructor stub } - public void invoke() { - int position, step; - final byte[] source; - final byte[] colormap; - int dest; - int count; - int spot; - int xtemp; - int ytemp; - - position = ((dsvars.ds_xfrac << 10) & 0xffff0000) - | ((dsvars.ds_yfrac >> 6) & 0xffff); - step = ((dsvars.ds_xstep << 10) & 0xffff0000) | ((dsvars.ds_ystep >> 6) & 0xffff); - source = dsvars.ds_source; - colormap = dsvars.ds_colormap; - dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; - count = dsvars.ds_x2 - dsvars.ds_x1 + 1; - //int rolls = 0; - while (count >= 4) { - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest] = colormap[0x00FF & source[spot]]; - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest + 1] = colormap[0x00FF & source[spot]]; - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest + 2] = colormap[0x00FF & source[spot]]; - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest + 3] = colormap[0x00FF & source[spot]]; - count -= 4; - dest += 4; + public static final class Indexed extends R_DrawSpanUnrolled { - // Half-assed attempt to fix precision by forced periodic - // realignment. + public Indexed(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, + int[] columnofs, SpanVars dsvars, byte[] screen, + IDoomSystem I) { + super(sCREENWIDTH, sCREENHEIGHT, ylookup, columnofs, dsvars, screen, I); + // TODO Auto-generated constructor stub + } - /* + public void invoke() { + int position, step; + final byte[] source; + final byte[] colormap; + int dest; + int count; + int spot; + int xtemp; + int ytemp; + + position = ((dsvars.ds_xfrac << 10) & 0xffff0000) + | ((dsvars.ds_yfrac >> 6) & 0xffff); + step = ((dsvars.ds_xstep << 10) & 0xffff0000) | ((dsvars.ds_ystep >> 6) & 0xffff); + source = dsvars.ds_source; + colormap = dsvars.ds_colormap; + dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; + count = dsvars.ds_x2 - dsvars.ds_x1 + 1; + //int rolls = 0; + while (count >= 4) { + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest] = colormap[0x00FF & source[spot]]; + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest + 1] = colormap[0x00FF & source[spot]]; + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest + 2] = colormap[0x00FF & source[spot]]; + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest + 3] = colormap[0x00FF & source[spot]]; + count -= 4; + dest += 4; + + // Half-assed attempt to fix precision by forced periodic + // realignment. + + /* * if ((rolls++)%64==0){ position = * ((((rolls*4)*ds_xstep+ds_xfrac) << 10) & 0xffff0000) | * ((((rolls*4)*ds_ystep+ds_yfrac) >> 6) & 0xffff); } - */ - - } - - while (count > 0) { - ytemp = position >> 4; - ytemp = ytemp & 4032; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest++] = colormap[0x00FF & source[spot]]; - count--; - } - } - - } - -public static final class TrueColor extends R_DrawSpanUnrolled{ - - - public TrueColor(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, - int[] columnofs, SpanVars dsvars, int[] screen, - IDoomSystem I) { - super(sCREENWIDTH, sCREENHEIGHT, ylookup, columnofs, dsvars, screen, I); - } + */ + } + + while (count > 0) { + ytemp = position >> 4; + ytemp = ytemp & 4032; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest++] = colormap[0x00FF & source[spot]]; + count--; + } + } - public void invoke() { - int position, step; - final byte[] source; - final int[] colormap; - int dest; - int count; - int spot; - int xtemp; - int ytemp; + } - position = ((dsvars.ds_xfrac << 10) & 0xffff0000) - | ((dsvars.ds_yfrac >> 6) & 0xffff); - step = ((dsvars.ds_xstep << 10) & 0xffff0000) | ((dsvars.ds_ystep >> 6) & 0xffff); - source = dsvars.ds_source; - colormap = dsvars.ds_colormap; - dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; - count = dsvars.ds_x2 - dsvars.ds_x1 + 1; - //int rolls = 0; - while (count >= 4) { - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest] = colormap[0x00FF & source[spot]]; - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest + 1] = colormap[0x00FF & source[spot]]; - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest + 2] = colormap[0x00FF & source[spot]]; - ytemp = position >> 4; - ytemp = ytemp & 0xfc0; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest + 3] = colormap[0x00FF & source[spot]]; - count -= 4; - dest += 4; + public static final class TrueColor extends R_DrawSpanUnrolled { - // Half-assed attempt to fix precision by forced periodic - // realignment. + public TrueColor(int sCREENWIDTH, int sCREENHEIGHT, int[] ylookup, + int[] columnofs, SpanVars dsvars, int[] screen, + IDoomSystem I) { + super(sCREENWIDTH, sCREENHEIGHT, ylookup, columnofs, dsvars, screen, I); + } - /* + public void invoke() { + int position, step; + final byte[] source; + final int[] colormap; + int dest; + int count; + int spot; + int xtemp; + int ytemp; + + position = ((dsvars.ds_xfrac << 10) & 0xffff0000) + | ((dsvars.ds_yfrac >> 6) & 0xffff); + step = ((dsvars.ds_xstep << 10) & 0xffff0000) | ((dsvars.ds_ystep >> 6) & 0xffff); + source = dsvars.ds_source; + colormap = dsvars.ds_colormap; + dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; + count = dsvars.ds_x2 - dsvars.ds_x1 + 1; + //int rolls = 0; + while (count >= 4) { + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest] = colormap[0x00FF & source[spot]]; + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest + 1] = colormap[0x00FF & source[spot]]; + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest + 2] = colormap[0x00FF & source[spot]]; + ytemp = position >> 4; + ytemp = ytemp & 0xfc0; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest + 3] = colormap[0x00FF & source[spot]]; + count -= 4; + dest += 4; + + // Half-assed attempt to fix precision by forced periodic + // realignment. + + /* * if ((rolls++)%64==0){ position = * ((((rolls*4)*ds_xstep+ds_xfrac) << 10) & 0xffff0000) | * ((((rolls*4)*ds_ystep+ds_yfrac) >> 6) & 0xffff); } - */ - + */ + } + + while (count > 0) { + ytemp = position >> 4; + ytemp = ytemp & 4032; + xtemp = position >>> 26; + spot = xtemp | ytemp; + position += step; + screen[dest++] = colormap[0x00FF & source[spot]]; + count--; + } } - while (count > 0) { - ytemp = position >> 4; - ytemp = ytemp & 4032; - xtemp = position >>> 26; - spot = xtemp | ytemp; - position += step; - screen[dest++] = colormap[0x00FF & source[spot]]; - count--; - } } - -} } diff --git a/src/rr/drawfuns/R_DrawSpanUnrolled2.java b/src/rr/drawfuns/R_DrawSpanUnrolled2.java index 2abe17d7..89dd577b 100644 --- a/src/rr/drawfuns/R_DrawSpanUnrolled2.java +++ b/src/rr/drawfuns/R_DrawSpanUnrolled2.java @@ -4,93 +4,90 @@ /** An unrolled (4x) rendering loop with full quality */ // public final int dumb=63 * 64; +public final class R_DrawSpanUnrolled2 extends DoomSpanFunction { -public final class R_DrawSpanUnrolled2 extends DoomSpanFunction { - - - public R_DrawSpanUnrolled2(int sCREENWIDTH, int sCREENHEIGHT, - int[] ylookup, int[] columnofs, SpanVars dsvars, + public R_DrawSpanUnrolled2(int sCREENWIDTH, int sCREENHEIGHT, + int[] ylookup, int[] columnofs, SpanVars dsvars, short[] screen, IDoomSystem I) { super(sCREENWIDTH, sCREENHEIGHT, ylookup, columnofs, dsvars, screen, I); // TODO Auto-generated constructor stub } public void invoke() { - final byte[] ds_source= dsvars.ds_source; - final short[] ds_colormap= dsvars.ds_colormap; - final int ds_xstep=dsvars.ds_xstep; - final int ds_ystep=dsvars.ds_ystep; - int f_xfrac; // fixed_t - int f_yfrac; // fixed_t - int dest; - int count; - int spot; - - // System.out.println("R_DrawSpan: "+ds_x1+" to "+ds_x2+" at "+ - // ds_y); - - if (RANGECHECK) { - doRangeCheck(); - // dscount++; - } - - f_xfrac = dsvars.ds_xfrac; - f_yfrac = dsvars.ds_yfrac; - - dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; - - count = dsvars.ds_x2 - dsvars.ds_x1; - while (count >= 4) { - // Current texture index in u,v. - spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) - + ((f_xfrac >> 16) & 63); - - // Lookup pixel from flat texture tile, - // re-index using light/colormap. - screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; - - // Next step in u,v. - f_xfrac += ds_xstep; - f_yfrac += ds_ystep; - - // UNROLL 2 - spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) - + ((f_xfrac >> 16) & 63); - screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; - f_xfrac += ds_xstep; - f_yfrac += ds_ystep; - - // UNROLL 3 - spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) - + ((f_xfrac >> 16) & 63); - screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; - f_xfrac += ds_xstep; - f_yfrac += ds_ystep; - - // UNROLL 4 - spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) - + ((f_xfrac >> 16) & 63); - screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; - f_xfrac += ds_xstep; - f_yfrac += ds_ystep; - - count -= 4; - } - - while (count > 0) { - // Current texture index in u,v. - spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) - + ((f_xfrac >> 16) & 63); - - // Lookup pixel from flat texture tile, - // re-index using light/colormap. - screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; - - // Next step in u,v. - f_xfrac += ds_xstep; - f_yfrac += ds_ystep; - count--; - } - - } + final byte[] ds_source = dsvars.ds_source; + final short[] ds_colormap = dsvars.ds_colormap; + final int ds_xstep = dsvars.ds_xstep; + final int ds_ystep = dsvars.ds_ystep; + int f_xfrac; // fixed_t + int f_yfrac; // fixed_t + int dest; + int count; + int spot; + + // System.out.println("R_DrawSpan: "+ds_x1+" to "+ds_x2+" at "+ + // ds_y); + if (RANGECHECK) { + doRangeCheck(); + // dscount++; + } + + f_xfrac = dsvars.ds_xfrac; + f_yfrac = dsvars.ds_yfrac; + + dest = ylookup[dsvars.ds_y] + columnofs[dsvars.ds_x1]; + + count = dsvars.ds_x2 - dsvars.ds_x1; + while (count >= 4) { + // Current texture index in u,v. + spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) + + ((f_xfrac >> 16) & 63); + + // Lookup pixel from flat texture tile, + // re-index using light/colormap. + screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; + + // Next step in u,v. + f_xfrac += ds_xstep; + f_yfrac += ds_ystep; + + // UNROLL 2 + spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) + + ((f_xfrac >> 16) & 63); + screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; + f_xfrac += ds_xstep; + f_yfrac += ds_ystep; + + // UNROLL 3 + spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) + + ((f_xfrac >> 16) & 63); + screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; + f_xfrac += ds_xstep; + f_yfrac += ds_ystep; + + // UNROLL 4 + spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) + + ((f_xfrac >> 16) & 63); + screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; + f_xfrac += ds_xstep; + f_yfrac += ds_ystep; + + count -= 4; + } + + while (count > 0) { + // Current texture index in u,v. + spot = ((f_yfrac >> (16 - 6)) & (63 * 64)) + + ((f_xfrac >> 16) & 63); + + // Lookup pixel from flat texture tile, + // re-index using light/colormap. + screen[dest++] = ds_colormap[0x00FF & ds_source[spot]]; + + // Next step in u,v. + f_xfrac += ds_xstep; + f_yfrac += ds_ystep; + count--; + } + + } } diff --git a/src/rr/drawfuns/R_DrawTLColumn.java b/src/rr/drawfuns/R_DrawTLColumn.java index 5b2f650e..71bd69c2 100644 --- a/src/rr/drawfuns/R_DrawTLColumn.java +++ b/src/rr/drawfuns/R_DrawTLColumn.java @@ -1,119 +1,122 @@ package rr.drawfuns; -import static m.fixed_t.FRACBITS; -import i.IDoomSystem; - - -public final class R_DrawTLColumn extends DoomColumnFunction { - - public R_DrawTLColumn(int SCREENWIDTH, int SCREENHEIGHT, - int[] ylookup, int[] columnofs, ColVars dcvars, - short[] screen, IDoomSystem I) { - super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); - this.flags=DcFlags.TRANSPARENT; - } - - public void invoke() { - int count; - int dest; // killough - int frac; // killough - final int fracstep; - final int dc_source_ofs=dcvars.dc_source_ofs; - final byte[] tranmap=dcvars.tranmap; - - count = dcvars.dc_yh - dcvars.dc_yl + 1; - - if (count <= 0) // Zero length, column does not exceed a pixel. - return; - - if (RANGECHECK) { - performRangeCheck(); - } - // Framebuffer destination address. - // Use ylookup LUT to avoid multiply with ScreenWidth. - // Use columnofs LUT for subwindows? - - dest = computeScreenDest(); - - // Determine scaling, which is the only mapping to be done. - - fracstep = dcvars.dc_iscale; - frac = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * fracstep; - - // Inner loop that does the actual texture mapping, - // e.g. a DDA-lile scaling. - // This is as fast as it gets. (Yeah, right!!! -- killough) - // - // killough 2/1/98: more performance tuning - - { - final byte[] source = dcvars.dc_source; - final short[] colormap = dcvars.dc_colormap; - int heightmask = dcvars.dc_texheight - 1; - if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 -- - // killough - { - heightmask++; - heightmask <<= FRACBITS; +import i.IDoomSystem; +import static m.fixed_t.FRACBITS; - if (frac < 0) - while ((frac += heightmask) < 0) +public final class R_DrawTLColumn extends DoomColumnFunction { + + public R_DrawTLColumn(int SCREENWIDTH, int SCREENHEIGHT, + int[] ylookup, int[] columnofs, ColVars dcvars, + short[] screen, IDoomSystem I) { + super(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, dcvars, screen, I); + this.flags = DcFlags.TRANSPARENT; + } + + public void invoke() { + int count; + int dest; // killough + int frac; // killough + final int fracstep; + final int dc_source_ofs = dcvars.dc_source_ofs; + final byte[] tranmap = dcvars.tranmap; + + count = dcvars.dc_yh - dcvars.dc_yl + 1; + + if (count <= 0) // Zero length, column does not exceed a pixel. + { + return; + } + + if (RANGECHECK) { + performRangeCheck(); + } + + // Framebuffer destination address. + // Use ylookup LUT to avoid multiply with ScreenWidth. + // Use columnofs LUT for subwindows? + dest = computeScreenDest(); + + // Determine scaling, which is the only mapping to be done. + fracstep = dcvars.dc_iscale; + frac = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) * fracstep; + + // Inner loop that does the actual texture mapping, + // e.g. a DDA-lile scaling. + // This is as fast as it gets. (Yeah, right!!! -- killough) + // + // killough 2/1/98: more performance tuning + { + final byte[] source = dcvars.dc_source; + final short[] colormap = dcvars.dc_colormap; + int heightmask = dcvars.dc_texheight - 1; + if ((dcvars.dc_texheight & heightmask) != 0) // not a power of 2 -- + // killough + { + heightmask++; + heightmask <<= FRACBITS; + + if (frac < 0) { + while ((frac += heightmask) < 0) ; - else - while (frac >= heightmask) - frac -= heightmask; - - do { - // Re-map color indices from wall texture column - // using a lighting/special effects LUT. - // heightmask is the Tutti-Frutti fix -- killough - - screen[dest] = tranmap[0xFF00 - & (screen[dest] << 8) - | (0x00FF & colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]])]; - dest += SCREENWIDTH; - if ((frac += fracstep) >= heightmask) - frac -= heightmask; - } while (--count > 0); - } else { - while ((count -= 4) >= 0) // texture height is a power of 2 - // -- killough - { - // screen[dest] = - // main_tranmap[0xFF00&(screen[dest]<<8)|(0x00FF&colormap[0x00FF&source[dc_source_ofs+((frac>>FRACBITS) - // & heightmask)]])]; - screen[dest] = tranmap[0xFF00 - & (screen[dest] << 8) - | (0x00FF & colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]])]; - dest += SCREENWIDTH; - frac += fracstep; - screen[dest] = tranmap[0xFF00 - & (screen[dest] << 8) - | (0x00FF & colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]])]; - dest += SCREENWIDTH; - frac += fracstep; - screen[dest] = tranmap[0xFF00 - & (screen[dest] << 8) - | (0x00FF & colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]])]; - dest += SCREENWIDTH; - frac += fracstep; - screen[dest] = tranmap[0xFF00 - & (screen[dest] << 8) - | (0x00FF & colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]])]; - dest += SCREENWIDTH; - frac += fracstep; - } - if ((count & 1) != 0) - screen[dest] = tranmap[0xFF00 - & (screen[dest] << 8) - | (0x00FF & colormap[0x00FF & source[dc_source_ofs - + ((frac >> FRACBITS) & heightmask)]])]; - } - } - } - } \ No newline at end of file + } else { + while (frac >= heightmask) { + frac -= heightmask; + } + } + + do { + // Re-map color indices from wall texture column + // using a lighting/special effects LUT. + // heightmask is the Tutti-Frutti fix -- killough + + screen[dest] = tranmap[0xFF00 + & (screen[dest] << 8) + | (0x00FF & colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]])]; + dest += SCREENWIDTH; + if ((frac += fracstep) >= heightmask) { + frac -= heightmask; + } + } while (--count > 0); + } else { + while ((count -= 4) >= 0) // texture height is a power of 2 + // -- killough + { + // screen[dest] = + // main_tranmap[0xFF00&(screen[dest]<<8)|(0x00FF&colormap[0x00FF&source[dc_source_ofs+((frac>>FRACBITS) + // & heightmask)]])]; + screen[dest] = tranmap[0xFF00 + & (screen[dest] << 8) + | (0x00FF & colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]])]; + dest += SCREENWIDTH; + frac += fracstep; + screen[dest] = tranmap[0xFF00 + & (screen[dest] << 8) + | (0x00FF & colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]])]; + dest += SCREENWIDTH; + frac += fracstep; + screen[dest] = tranmap[0xFF00 + & (screen[dest] << 8) + | (0x00FF & colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]])]; + dest += SCREENWIDTH; + frac += fracstep; + screen[dest] = tranmap[0xFF00 + & (screen[dest] << 8) + | (0x00FF & colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]])]; + dest += SCREENWIDTH; + frac += fracstep; + } + if ((count & 1) != 0) { + screen[dest] = tranmap[0xFF00 + & (screen[dest] << 8) + | (0x00FF & colormap[0x00FF & source[dc_source_ofs + + ((frac >> FRACBITS) & heightmask)]])]; + } + } + } + } +} diff --git a/src/rr/drawfuns/R_DrawTranslatedColumn.java b/src/rr/drawfuns/R_DrawTranslatedColumn.java index 444fe565..adf4fd42 100644 --- a/src/rr/drawfuns/R_DrawTranslatedColumn.java +++ b/src/rr/drawfuns/R_DrawTranslatedColumn.java @@ -15,6 +15,7 @@ public R_DrawTranslatedColumn(int SCREENWIDTH, int SCREENHEIGHT, public static final class HiColor extends R_DrawTranslatedColumn { + public HiColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, int[] columnofs, ColVars dcvars, short[] screen, IDoomSystem I) { @@ -34,8 +35,9 @@ public void invoke() { final byte[] dc_translation = dcvars.dc_translation; count = dcvars.dc_yh - dcvars.dc_yl; - if (count < 0) + if (count < 0) { return; + } if (RANGECHECK) { super.performRangeCheck(); @@ -48,65 +50,66 @@ public void invoke() { * dc_yl*80 + (dc_x>>1); } else { outp (SC_INDEX+1,1<<(dc_x&3)); * dest = destview + dc_yl*80 + (dc_x>>2); } */ - // FIXME. As above. dest = computeScreenDest(); // Looks familiar. fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Here we do an additional index re-mapping. // Maes: Unroll by 4 - if (count >= 4) + if (count >= 4) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; } while ((count -= 4) > 4); + } - if (count > 0) + if (count > 0) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; } while (count-- != 0); + } } } @@ -132,8 +135,9 @@ public void invoke() { final byte[] dc_translation = dcvars.dc_translation; count = dcvars.dc_yh - dcvars.dc_yl; - if (count < 0) + if (count < 0) { return; + } if (RANGECHECK) { super.performRangeCheck(); @@ -146,70 +150,72 @@ public void invoke() { * dc_yl*80 + (dc_x>>1); } else { outp (SC_INDEX+1,1<<(dc_x&3)); * dest = destview + dc_yl*80 + (dc_x>>2); } */ - // FIXME. As above. dest = computeScreenDest(); // Looks familiar. fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Here we do an additional index re-mapping. // Maes: Unroll by 4 - if (count >= 4) + if (count >= 4) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; } while ((count -= 4) > 4); + } - if (count > 0) + if (count > 0) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; } while (count-- != 0); + } } } public static final class TrueColor extends R_DrawTranslatedColumn { + public TrueColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, int[] columnofs, ColVars dcvars, int[] screen, IDoomSystem I) { @@ -229,8 +235,9 @@ public void invoke() { final byte[] dc_translation = dcvars.dc_translation; count = dcvars.dc_yh - dcvars.dc_yl; - if (count < 0) + if (count < 0) { return; + } if (RANGECHECK) { super.performRangeCheck(); @@ -243,65 +250,66 @@ public void invoke() { * dc_yl*80 + (dc_x>>1); } else { outp (SC_INDEX+1,1<<(dc_x&3)); * dest = destview + dc_yl*80 + (dc_x>>2); } */ - // FIXME. As above. dest = computeScreenDest(); // Looks familiar. fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Here we do an additional index re-mapping. // Maes: Unroll by 4 - if (count >= 4) + if (count >= 4) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; } while ((count -= 4) > 4); + } - if (count > 0) + if (count > 0) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; frac += fracstep; } while (count-- != 0); + } } } -} \ No newline at end of file +} diff --git a/src/rr/drawfuns/R_DrawTranslatedColumnLow.java b/src/rr/drawfuns/R_DrawTranslatedColumnLow.java index 74ee3773..84db2887 100644 --- a/src/rr/drawfuns/R_DrawTranslatedColumnLow.java +++ b/src/rr/drawfuns/R_DrawTranslatedColumnLow.java @@ -15,6 +15,7 @@ public R_DrawTranslatedColumnLow(int SCREENWIDTH, int SCREENHEIGHT, public static final class HiColor extends R_DrawTranslatedColumnLow { + public HiColor(int SCREENWIDTH, int SCREENHEIGHT, int[] ylookup, int[] columnofs, ColVars dcvars, short[] screen, IDoomSystem I) { @@ -34,8 +35,9 @@ public void invoke() { final byte[] dc_translation = dcvars.dc_translation; count = dcvars.dc_yh - dcvars.dc_yl; - if (count < 0) + if (count < 0) { return; + } if (RANGECHECK) { super.performRangeCheck(); @@ -47,69 +49,71 @@ public void invoke() { // Looks familiar. fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Here we do an additional index re-mapping. // Maes: Unroll by 4 - if (count >= 4) + if (count >= 4) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; } while ((count -= 4) > 4); + } - if (count > 0) + if (count > 0) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; } while (count-- != 0); + } } } @@ -136,8 +140,9 @@ public void invoke() { final byte[] dc_translation = dcvars.dc_translation; count = dcvars.dc_yh - dcvars.dc_yl; - if (count < 0) + if (count < 0) { return; + } if (RANGECHECK) { super.performRangeCheck(); @@ -149,69 +154,71 @@ public void invoke() { // Looks familiar. fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Here we do an additional index re-mapping. // Maes: Unroll by 4 - if (count >= 4) + if (count >= 4) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; } while ((count -= 4) > 4); + } - if (count > 0) + if (count > 0) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; } while (count-- != 0); + } } } @@ -237,8 +244,9 @@ public void invoke() { final byte[] dc_translation = dcvars.dc_translation; count = dcvars.dc_yh - dcvars.dc_yl; - if (count < 0) + if (count < 0) { return; + } if (RANGECHECK) { super.performRangeCheck(); @@ -250,70 +258,72 @@ public void invoke() { // Looks familiar. fracstep = dcvars.dc_iscale; - frac = - dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) - * fracstep; + frac + = dcvars.dc_texturemid + (dcvars.dc_yl - dcvars.centery) + * fracstep; // Here we do an additional index re-mapping. // Maes: Unroll by 4 - if (count >= 4) + if (count >= 4) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; } while ((count -= 4) > 4); + } - if (count > 0) + if (count > 0) { do { // Translation tables are used // to map certain colorramps to other ones, // used with PLAY sprites. // Thus the "green" ramp of the player 0 sprite // is mapped to gray, red, black/indigo. - screen[dest] = - screen[dest2] = - dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs - + (frac >> FRACBITS)]]]; + screen[dest] + = screen[dest2] + = dc_colormap[0x00FF & dc_translation[0xFF & dc_source[dc_source_ofs + + (frac >> FRACBITS)]]]; dest += SCREENWIDTH; dest2 += SCREENWIDTH; frac += fracstep; } while (count-- != 0); + } } } -} \ No newline at end of file +} diff --git a/src/rr/drawfuns/SpanFunction.java b/src/rr/drawfuns/SpanFunction.java index 89163196..fbb5269e 100644 --- a/src/rr/drawfuns/SpanFunction.java +++ b/src/rr/drawfuns/SpanFunction.java @@ -5,10 +5,10 @@ * @author velktron * */ +public interface SpanFunction { -public interface SpanFunction { public void invoke(); - - public void invoke(SpanVars dsvars); -} \ No newline at end of file + public void invoke(SpanVars dsvars); + +} diff --git a/src/rr/drawfuns/SpanVars.java b/src/rr/drawfuns/SpanVars.java index af68419c..82ee33ed 100644 --- a/src/rr/drawfuns/SpanVars.java +++ b/src/rr/drawfuns/SpanVars.java @@ -1,18 +1,18 @@ package rr.drawfuns; -public class SpanVars { +public class SpanVars { public int ds_xfrac; public int ds_yfrac; public int ds_xstep; public T ds_source; - + /** DrawSpan colormap. */ public V ds_colormap; public int ds_y; public int ds_x2; public int ds_x1; public int ds_ystep; - - public DoomSpanFunction spanfunc; + + public DoomSpanFunction spanfunc; } diff --git a/src/rr/drawseg_t.java b/src/rr/drawseg_t.java index 6ad034ae..9109b465 100644 --- a/src/rr/drawseg_t.java +++ b/src/rr/drawseg_t.java @@ -3,112 +3,109 @@ // // ? // - public class drawseg_t { - - public drawseg_t(){ - - } - /** MAES: was pointer. Not array? */ - public seg_t curline; - public int x1, x2; + public drawseg_t() { + + } + + /** MAES: was pointer. Not array? */ + public seg_t curline; + public int x1, x2; - /** fixed_t */ - public int scale1, scale2, scalestep; + /** fixed_t */ + public int scale1, scale2, scalestep; - /** 0=none, 1=bottom, 2=top, 3=both */ - public int silhouette; + /** 0=none, 1=bottom, 2=top, 3=both */ + public int silhouette; - /** do not clip sprites above this (fixed_t) */ - public int bsilheight; + /** do not clip sprites above this (fixed_t) */ + public int bsilheight; - /** do not clip sprites below this (fixed_t) */ - public int tsilheight; - - /** Indexes to lists for sprite clipping, + /** do not clip sprites below this (fixed_t) */ + public int tsilheight; + + /** Indexes to lists for sprite clipping, all three adjusted so [x1] is first value. */ - private int psprtopclip, psprbottomclip, pmaskedtexturecol; - - /** Pointers to the actual lists */ - - private short[] sprtopclip, sprbottomclip, maskedtexturecol; - - ///////////////// Accessor methods to simulate mid-array pointers /////////// - - public void setSprTopClip(short[] array, int index){ - this.sprtopclip=array; - this.psprtopclip=index; - } - - public void setSprBottomClip(short[] array, int index){ - this.sprbottomclip=array; - this.psprbottomclip=index; - } - - public void setMaskedTextureCol(short[] array, int index){ - this.maskedtexturecol=array; - this.pmaskedtexturecol=index; - } - - public short getSprTopClip(int index){ - return this.sprtopclip[this.psprtopclip+index]; - } - - public short getSprBottomClip( int index){ - return this.sprbottomclip[this.psprbottomclip+index]; - } - - public short getMaskedTextureCol(int index){ - return this.maskedtexturecol[this.pmaskedtexturecol+index]; - } - - public short[] getSprTopClipList(){ - return this.sprtopclip; - } - - public short[] getSprBottomClipList(){ - return this.sprbottomclip; - } - - public short[] getMaskedTextureColList(){ - return this.maskedtexturecol; - } - - public int getSprTopClipPointer(){ - return this.psprtopclip; - } - - public int getSprBottomClipPointer(){ - return this.psprbottomclip; - } - - public int getMaskedTextureColPointer(){ - return this.pmaskedtexturecol; - } - - public void setSprTopClipPointer(int index){ - this.psprtopclip=index; - } - - public void setSprBottomClipPointer(int index){ - this.psprbottomclip=index; - } - - public void setMaskedTextureColPointer(int index){ - this.pmaskedtexturecol=index; - } - - public boolean nullSprTopClip(){ - return this.sprtopclip==null; - } - - public boolean nullSprBottomClip(){ - return this.sprbottomclip==null; - } - - public boolean nullMaskedTextureCol(){ - return this.maskedtexturecol==null; - } - + private int psprtopclip, psprbottomclip, pmaskedtexturecol; + + /** Pointers to the actual lists */ + private short[] sprtopclip, sprbottomclip, maskedtexturecol; + + ///////////////// Accessor methods to simulate mid-array pointers /////////// + public void setSprTopClip(short[] array, int index) { + this.sprtopclip = array; + this.psprtopclip = index; + } + + public void setSprBottomClip(short[] array, int index) { + this.sprbottomclip = array; + this.psprbottomclip = index; + } + + public void setMaskedTextureCol(short[] array, int index) { + this.maskedtexturecol = array; + this.pmaskedtexturecol = index; + } + + public short getSprTopClip(int index) { + return this.sprtopclip[this.psprtopclip + index]; + } + + public short getSprBottomClip(int index) { + return this.sprbottomclip[this.psprbottomclip + index]; + } + + public short getMaskedTextureCol(int index) { + return this.maskedtexturecol[this.pmaskedtexturecol + index]; + } + + public short[] getSprTopClipList() { + return this.sprtopclip; + } + + public short[] getSprBottomClipList() { + return this.sprbottomclip; + } + + public short[] getMaskedTextureColList() { + return this.maskedtexturecol; + } + + public int getSprTopClipPointer() { + return this.psprtopclip; + } + + public int getSprBottomClipPointer() { + return this.psprbottomclip; + } + + public int getMaskedTextureColPointer() { + return this.pmaskedtexturecol; + } + + public void setSprTopClipPointer(int index) { + this.psprtopclip = index; + } + + public void setSprBottomClipPointer(int index) { + this.psprbottomclip = index; + } + + public void setMaskedTextureColPointer(int index) { + this.pmaskedtexturecol = index; + } + + public boolean nullSprTopClip() { + return this.sprtopclip == null; + } + + public boolean nullSprBottomClip() { + return this.sprbottomclip == null; + } + + public boolean nullMaskedTextureCol() { + return this.maskedtexturecol == null; + } + } diff --git a/src/rr/flat_t.java b/src/rr/flat_t.java index a5fcf09f..e6a7f5b6 100644 --- a/src/rr/flat_t.java +++ b/src/rr/flat_t.java @@ -2,31 +2,29 @@ import java.io.IOException; import java.nio.ByteBuffer; - import w.CacheableDoomObject; public class flat_t implements CacheableDoomObject { - public static final int FLAT_SIZE=4096; - + public static final int FLAT_SIZE = 4096; + public byte[] data; - public flat_t(){ - this.data=new byte[FLAT_SIZE]; + public flat_t() { + this.data = new byte[FLAT_SIZE]; } - public flat_t(int size){ - this.data=new byte[size]; + public flat_t(int size) { + this.data = new byte[size]; } - @Override public void unpack(ByteBuffer buf) throws IOException { - - //buf.get(this.data); - this.data=buf.array(); + + //buf.get(this.data); + this.data = buf.array(); } diff --git a/src/rr/line_t.java b/src/rr/line_t.java index 7873ebfe..ff09cd0f 100644 --- a/src/rr/line_t.java +++ b/src/rr/line_t.java @@ -13,7 +13,8 @@ import static m.BBox.BOXLEFT; import static m.BBox.BOXRIGHT; import static m.BBox.BOXTOP; -import static m.fixed_t.*; +import static m.fixed_t.FRACBITS; +import static m.fixed_t.FixedMul; import p.Interceptable; import p.Resettable; import s.degenmobj_t; @@ -24,13 +25,12 @@ import w.IReadableDoomObject; /** This is the actual linedef */ - public class line_t implements Interceptable, IReadableDoomObject, IPackableDoomObject, Resettable { - public static final char NO_INDEX=0xFFFF; - + public static final char NO_INDEX = 0xFFFF; + public line_t() { sidenum = new char[2]; bbox = new int[4]; @@ -86,11 +86,11 @@ public line_t() { // From Boom public int tranlump; - + public int id; - + /** killough 4/17/98: improves searches for tags. */ - public int firsttag,nexttag; + public int firsttag, nexttag; /** For Boom stuff, interprets sidenum specially */ public int getSpecialSidenum() { @@ -114,17 +114,13 @@ public void assignVertexValues() { * fixed_t * @return 0 or 1 (false, true) - (front, back) */ - public boolean PointOnLineSide(int x, int y) - - { - + public boolean PointOnLineSide(int x, int y) { - return - (dx==0) ? x <= this.v1x ? this.dy > 0 : this.dy < 0 : - (dy==0) ? y <= this.v1y ? this.dx < 0 : this.dx > 0 : - FixedMul(y-this.v1y, this.dx>>FRACBITS) >= - FixedMul(this.dy>>FRACBITS, x-this.v1x); - /* + return (dx == 0) ? x <= this.v1x ? this.dy > 0 : this.dy < 0 + : (dy == 0) ? y <= this.v1y ? this.dx < 0 : this.dx > 0 + : FixedMul(y - this.v1y, this.dx >> FRACBITS) + >= FixedMul(this.dy >> FRACBITS, x - this.v1x); + /* int dx, dy, left, right; if (this.dx == 0) { if (x <= this.v1x) @@ -163,42 +159,43 @@ public int BoxOnLineSide(int[] tmbox) { boolean p2 = false; switch (this.slopetype) { - // Line perfectly horizontal, box floating "north" of line - case ST_HORIZONTAL: - p1 = tmbox[BOXTOP] > v1y; - p2 = tmbox[BOXBOTTOM] > v1y; - if (dx < 0) { - p1 ^= true; - p2 ^= true; - } - break; - - // Line perfectly vertical, box floating "west" of line - case ST_VERTICAL: - - p1 = tmbox[BOXRIGHT] < v1x; - p2 = tmbox[BOXLEFT] < v1x; - if (dy < 0) { - p1 ^= true; - p2 ^= true; - } - break; - - case ST_POSITIVE: - // Positive slope, both points on one side. - p1 = PointOnLineSide(tmbox[BOXLEFT], tmbox[BOXTOP]); - p2 = PointOnLineSide(tmbox[BOXRIGHT], tmbox[BOXBOTTOM]); - break; - - case ST_NEGATIVE: - // Negative slope, both points (mirrored horizontally) on one side. - p1 = PointOnLineSide(tmbox[BOXRIGHT], tmbox[BOXTOP]); - p2 = PointOnLineSide(tmbox[BOXLEFT], tmbox[BOXBOTTOM]); - break; + // Line perfectly horizontal, box floating "north" of line + case ST_HORIZONTAL: + p1 = tmbox[BOXTOP] > v1y; + p2 = tmbox[BOXBOTTOM] > v1y; + if (dx < 0) { + p1 ^= true; + p2 ^= true; + } + break; + + // Line perfectly vertical, box floating "west" of line + case ST_VERTICAL: + + p1 = tmbox[BOXRIGHT] < v1x; + p2 = tmbox[BOXLEFT] < v1x; + if (dy < 0) { + p1 ^= true; + p2 ^= true; + } + break; + + case ST_POSITIVE: + // Positive slope, both points on one side. + p1 = PointOnLineSide(tmbox[BOXLEFT], tmbox[BOXTOP]); + p2 = PointOnLineSide(tmbox[BOXRIGHT], tmbox[BOXBOTTOM]); + break; + + case ST_NEGATIVE: + // Negative slope, both points (mirrored horizontally) on one side. + p1 = PointOnLineSide(tmbox[BOXRIGHT], tmbox[BOXTOP]); + p2 = PointOnLineSide(tmbox[BOXLEFT], tmbox[BOXBOTTOM]); + break; } - if (p1 == p2) + if (p1 == p2) { return p1 ? 1 : 0; + } // Any other result means non-inclusive crossing. return -1; } @@ -216,42 +213,43 @@ public int BoxOnLineSideInclusive(int[] tmbox) { boolean p2 = false; switch (this.slopetype) { - // Line perfectly horizontal, box floating "north" of line - case ST_HORIZONTAL: - p1 = tmbox[BOXTOP] >= v1y; - p2 = tmbox[BOXBOTTOM] >= v1y; - if (dx < 0) { - p1 ^= true; - p2 ^= true; - } - break; - - // Line perfectly vertical, box floating "west" of line - case ST_VERTICAL: - - p1 = tmbox[BOXRIGHT] <= v1x; - p2 = tmbox[BOXLEFT] <= v1x; - if (dy < 0) { - p1 ^= true; - p2 ^= true; - } - break; - - case ST_POSITIVE: - // Positive slope, both points on one side. - p1 = PointOnLineSide(tmbox[BOXLEFT], tmbox[BOXTOP]); - p2 = PointOnLineSide(tmbox[BOXRIGHT], tmbox[BOXBOTTOM]); - break; - - case ST_NEGATIVE: - // Negative slope, both points (mirrored horizontally) on one side. - p1 = PointOnLineSide(tmbox[BOXRIGHT], tmbox[BOXTOP]); - p2 = PointOnLineSide(tmbox[BOXLEFT], tmbox[BOXBOTTOM]); - break; + // Line perfectly horizontal, box floating "north" of line + case ST_HORIZONTAL: + p1 = tmbox[BOXTOP] >= v1y; + p2 = tmbox[BOXBOTTOM] >= v1y; + if (dx < 0) { + p1 ^= true; + p2 ^= true; + } + break; + + // Line perfectly vertical, box floating "west" of line + case ST_VERTICAL: + + p1 = tmbox[BOXRIGHT] <= v1x; + p2 = tmbox[BOXLEFT] <= v1x; + if (dy < 0) { + p1 ^= true; + p2 ^= true; + } + break; + + case ST_POSITIVE: + // Positive slope, both points on one side. + p1 = PointOnLineSide(tmbox[BOXLEFT], tmbox[BOXTOP]); + p2 = PointOnLineSide(tmbox[BOXRIGHT], tmbox[BOXBOTTOM]); + break; + + case ST_NEGATIVE: + // Negative slope, both points (mirrored horizontally) on one side. + p1 = PointOnLineSide(tmbox[BOXRIGHT], tmbox[BOXTOP]); + p2 = PointOnLineSide(tmbox[BOXLEFT], tmbox[BOXBOTTOM]); + break; } - if (p1 == p2) + if (p1 == p2) { return p1 ? 1 : 0; + } // Any other result means non-inclusive crossing. return -1; } @@ -275,8 +273,8 @@ public sector_t getNextSector(sector_t sec) { } public String toString() { - return (String.format("Line %d Flags: %x Special %d Tag: %d ", this.id,this.flags, - this.special, this.tag)); + return (String.format("Line %d Flags: %x Special %d Tag: %d ", this.id, this.flags, + this.special, this.tag)); } @Override @@ -317,7 +315,7 @@ public void reset() { soundorg = null; tranlump = 0; } - + /** * LUT, motion clipping, walls/grid element // // LineDef attributes. // /** * Solid, is an obstacle. @@ -338,7 +336,6 @@ public void reset() { // Unpegged textures allways have the first row of // the texture at the top pixel of the line for both // top and bottom textures (use next to windows). - /** upper texture unpegged */ public static final int ML_DONTPEGTOP = 8; diff --git a/src/rr/mappatch_t.java b/src/rr/mappatch_t.java index fe3d3523..c70edfb3 100644 --- a/src/rr/mappatch_t.java +++ b/src/rr/mappatch_t.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; - import w.CacheableDoomObject; /** @@ -14,28 +13,27 @@ * into the rectangular texture space using origin * and possibly other attributes. */ - public class mappatch_t implements CacheableDoomObject { - public short originx; - public short originy; - public short patch; - public short stepdir; - public short colormap; - + + public short originx; + public short originy; + public short patch; + public short stepdir; + public short colormap; + @Override public void unpack(ByteBuffer buf) throws IOException { buf.order(ByteOrder.LITTLE_ENDIAN); - originx=buf.getShort(); - originy=buf.getShort(); - patch=buf.getShort(); - stepdir=buf.getShort(); - colormap=buf.getShort(); + originx = buf.getShort(); + originy = buf.getShort(); + patch = buf.getShort(); + stepdir = buf.getShort(); + colormap = buf.getShort(); } public static final int size() { return 10; } - - - }; + +}; diff --git a/src/rr/maptexture_t.java b/src/rr/maptexture_t.java index 04d0260e..d42a8916 100644 --- a/src/rr/maptexture_t.java +++ b/src/rr/maptexture_t.java @@ -15,17 +15,16 @@ * @author MAES * */ +public class maptexture_t implements CacheableDoomObject { -public class maptexture_t implements CacheableDoomObject{ - public String name; - public boolean masked; - public short width; // was signed byte - public short height; // was + public String name; + public boolean masked; + public short width; // was signed byte + public short height; // was //void**t columndirectory; // OBSOLETE (yeah, but we must read a dummy integer here) - public short patchcount; - public mappatch_t[] patches; - - + public short patchcount; + public mappatch_t[] patches; + @Override public void unpack(ByteBuffer buf) throws IOException { buf.order(ByteOrder.LITTLE_ENDIAN); @@ -42,5 +41,5 @@ public void unpack(ByteBuffer buf) throws IOException { patches = malloc(mappatch_t::new, mappatch_t[]::new, patchcount); DoomBuffer.readObjectArray(buf, patches, patchcount); - } -}; \ No newline at end of file + } +}; diff --git a/src/rr/maskdraw_t.java b/src/rr/maskdraw_t.java index 7a83c839..835e63d1 100644 --- a/src/rr/maskdraw_t.java +++ b/src/rr/maskdraw_t.java @@ -11,13 +11,13 @@ * @author Maes * */ - public class maskdraw_t { - public int x1; - public int x2; - - public int column; - public int topclip; - public int bottomclip; - } \ No newline at end of file + public int x1; + public int x2; + + public int column; + public int topclip; + public int bottomclip; + +} diff --git a/src/rr/node_t.java b/src/rr/node_t.java index 57e0477b..3217a634 100644 --- a/src/rr/node_t.java +++ b/src/rr/node_t.java @@ -2,7 +2,7 @@ import doom.SourceCode; import doom.SourceCode.R_Main; -import static doom.SourceCode.R_Main.*; +import static doom.SourceCode.R_Main.R_PointOnSide; import doom.SourceCode.fixed_t; import m.BBox; import m.ISyncLogger; @@ -22,12 +22,12 @@ public class node_t implements Resettable { public node_t() { - bbox = new BBox[] {new BBox(), new BBox()}; + bbox = new BBox[]{new BBox(), new BBox()}; children = new int[2]; } public node_t(int x, int y, int dx, int dy, BBox[] bbox, - int[] children) { + int[] children) { this.x = x; this.y = y; this.dx = dx; @@ -39,13 +39,15 @@ public node_t(int x, int y, int dx, int dy, BBox[] bbox, /** * Partition line. */ - @fixed_t public int x, y, dx, dy; + @fixed_t + public int x, y, dx, dy; /** * Bounding box for each child. */ // Maes: make this into two proper bboxes? - @fixed_t public BBox[] bbox; + @fixed_t + public BBox[] bbox; /** * If NF_SUBSECTOR its a subsector. @@ -68,7 +70,8 @@ public node_t(int x, int y, int dx, int dy, BBox[] bbox, public static int PointOnSide(@fixed_t int x, @fixed_t int y, node_t node) { // MAES: These are used mainly as ints, no need to use fixed_t internally. // fixed_t will only be used as a "pass type", but calculations will be done with ints, preferably. - @fixed_t int dx, dy, left, right; + @fixed_t + int dx, dy, left, right; if (node.dx == 0) { if (x <= node.x) { @@ -120,7 +123,8 @@ public static int PointOnSide(@fixed_t int x, @fixed_t int y, node_t node) { public int PointOnSide(@fixed_t int x, @fixed_t int y) { // MAES: These are used mainly as ints, no need to use fixed_t internally. // fixed_t will only be used as a "pass type", but calculations will be done with ints, preferably. - @fixed_t int lDx, lDy, left, right; + @fixed_t + int lDx, lDy, left, right; if (this.dx == 0) { if (x <= this.x) { @@ -170,10 +174,10 @@ public int PointOnSide(@fixed_t int x, @fixed_t int y) { public int DivlineSide(int x, int y) { int left, right; return (this.dx == 0) ? x == this.x ? 2 : x <= this.x ? eval(this.dy > 0) : eval(this.dy < 0) : (this.dy == 0) - ? (OLDDEMO ? x : y) == this.y ? 2 : y <= this.y ? eval(this.dx < 0) : eval(this.dx > 0) : (this.dy == 0) - ? y == this.y ? 2 : y <= this.y ? eval(this.dx < 0) : eval(this.dx > 0) - : (right = ((y - this.y) >> FRACBITS) * (this.dx >> FRACBITS)) - < (left = ((x - this.x) >> FRACBITS) * (this.dy >> FRACBITS)) ? 0 : right == left ? 2 : 1; + ? (OLDDEMO ? x : y) == this.y ? 2 : y <= this.y ? eval(this.dx < 0) : eval(this.dx > 0) : (this.dy == 0) + ? y == this.y ? 2 : y <= this.y ? eval(this.dx < 0) : eval(this.dx > 0) + : (right = ((y - this.y) >> FRACBITS) * (this.dx >> FRACBITS)) + < (left = ((x - this.x) >> FRACBITS) * (this.dy >> FRACBITS)) ? 0 : right == left ? 2 : 1; } private static final boolean OLDDEMO = Engine.getConfig().equals(Settings.line_of_sight, Settings.LOS.Vanilla); diff --git a/src/rr/pQuickSprite.java b/src/rr/pQuickSprite.java index b1f7829d..9f9cedfd 100644 --- a/src/rr/pQuickSprite.java +++ b/src/rr/pQuickSprite.java @@ -1,57 +1,76 @@ package rr; -public class pQuickSprite{ - public static final void sort(vissprite_t[] c){ - int i,j,left = 0,right = c.length - 1,stack_pointer = -1; +public class pQuickSprite { + + public static final void sort(vissprite_t[] c) { + int i, j, left = 0, right = c.length - 1, stack_pointer = -1; int[] stack = new int[128]; - vissprite_t swap,temp; - while(true){ - if(right - left <= 7){ - for(j=left+1;j<=right;j++){ + vissprite_t swap, temp; + while (true) { + if (right - left <= 7) { + for (j = left + 1; j <= right; j++) { swap = c[j]; - i = j-1; - while(i>=left && c[i].scale>swap.scale) - c[i+1] = c[i--]; - c[i+1] = swap; + i = j - 1; + while (i >= left && c[i].scale > swap.scale) { + c[i + 1] = c[i--]; + } + c[i + 1] = swap; } - if(stack_pointer == -1) + if (stack_pointer == -1) { break; + } right = stack[stack_pointer--]; left = stack[stack_pointer--]; - }else{ + } else { int median = (left + right) >> 1; i = left + 1; j = right; - swap = c[median]; c[median] = c[i]; c[i] = swap; + swap = c[median]; + c[median] = c[i]; + c[i] = swap; /* make sure: c[left] <= c[left+1] <= c[right] */ - if(c[left].scale > c[right].scale){ - swap = c[left]; c[left] = c[right]; c[right] = swap; - }if(c[i].scale>c[right].scale ){ - swap = c[i]; c[i] = c[right]; c[right] = swap; - }if(c[left].scale>c[i].scale){ - swap = c[left]; c[left] = c[i]; c[i] = swap; + if (c[left].scale > c[right].scale) { + swap = c[left]; + c[left] = c[right]; + c[right] = swap; + } + if (c[i].scale > c[right].scale) { + swap = c[i]; + c[i] = c[right]; + c[right] = swap; + } + if (c[left].scale > c[i].scale) { + swap = c[left]; + c[left] = c[i]; + c[i] = swap; } temp = c[i]; - while(true){ - do i++; while(c[i].scaletemp.scale); - if(j < i) + while (true) { + do { + i++; + } while (c[i].scale < temp.scale); + do { + j--; + } while (c[j].scale > temp.scale); + if (j < i) { break; - swap = c[i]; c[i] = c[j]; c[j] = swap; + } + swap = c[i]; + c[i] = c[j]; + c[j] = swap; } c[left + 1] = c[j]; c[j] = temp; - if(right-i+1 >= j-left){ + if (right - i + 1 >= j - left) { stack[++stack_pointer] = i; stack[++stack_pointer] = right; - right = j-1; - }else{ + right = j - 1; + } else { stack[++stack_pointer] = left; - stack[++stack_pointer] = j-1; + stack[++stack_pointer] = j - 1; left = i; } } } } } - \ No newline at end of file diff --git a/src/rr/parallel/AbstractParallelRenderer.java b/src/rr/parallel/AbstractParallelRenderer.java index 9ba422e9..387d1acd 100644 --- a/src/rr/parallel/AbstractParallelRenderer.java +++ b/src/rr/parallel/AbstractParallelRenderer.java @@ -8,8 +8,11 @@ import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Executor; import java.util.concurrent.Executors; +import java.util.logging.Level; +import java.util.logging.Logger; import static m.fixed_t.FRACBITS; import static m.fixed_t.FixedMul; +import mochadoom.Loggers; import rr.PlaneDrawer; import rr.RendererState; import rr.SceneRenderer; @@ -21,9 +24,10 @@ * * @author velktron */ - public abstract class AbstractParallelRenderer extends RendererState implements RWI.Init { + private static final Logger LOGGER = Loggers.getLogger(AbstractParallelRenderer.class.getName()); + public AbstractParallelRenderer(DoomMain DM, int wallthread, int floorthreads, int nummaskedthreads) { super(DM); this.NUMWALLTHREADS = wallthread; @@ -31,7 +35,7 @@ public AbstractParallelRenderer(DoomMain DM, int wallthread, int floorthre this.NUMMASKEDTHREADS = nummaskedthreads; // Prepare the barriers for MAXTHREADS + main thread. drawsegsbarrier = new CyclicBarrier(NUMWALLTHREADS + 1); - visplanebarrier = new CyclicBarrier(NUMFLOORTHREADS + 1); + visplanebarrier = new CyclicBarrier(NUMFLOORTHREADS + 1); maskedbarrier = new CyclicBarrier(NUMMASKEDTHREADS + 1); tp = Executors.newCachedThreadPool(); } @@ -44,7 +48,7 @@ public AbstractParallelRenderer(DoomMain DM, int wallthread, this.NUMMASKEDTHREADS = 1; // Prepare the barriers for MAXTHREADS + main thread. drawsegsbarrier = new CyclicBarrier(NUMWALLTHREADS + 1); - visplanebarrier = new CyclicBarrier(NUMFLOORTHREADS + 1); + visplanebarrier = new CyclicBarrier(NUMFLOORTHREADS + 1); maskedbarrier = new CyclicBarrier(NUMMASKEDTHREADS + 1); tp = Executors.newCachedThreadPool(); } @@ -86,7 +90,6 @@ protected final class ParallelSegs extends SegDrawer implements RWI.Get { * transversed, and then execute those in parallel. Also saves on having * to duplicate way too much status. */ - @Override protected void CompleteColumn() { @@ -105,14 +108,13 @@ protected void CompleteColumn() { /** * Starts the RenderWallExecutors. Sync is EXTERNAL, however. */ - @Override public void CompleteRendering() { for (int i = 0; i < NUMWALLTHREADS; i++) { RWIExec[i].setRange((i * RWIcount) / NUMWALLTHREADS, - ((i + 1) * RWIcount) / NUMWALLTHREADS); + ((i + 1) * RWIcount) / NUMWALLTHREADS); // RWIExec[i].setRange(i%NUMWALLTHREADS,RWIcount,NUMWALLTHREADS); tp.execute(RWIExec[i]); } @@ -135,18 +137,15 @@ public void CompleteRendering() { * variable number of columns and an irregular height profile -> we'd * need to look into visplanes ugh... */ - RenderWallExecutor[] RWIExec; /** Array of "wall" (actually, column) instructions */ - ColVars[] RWI; /** * Increment this as you submit RWIs to the "queue". Remember to reset * to 0 when you have drawn everything! */ - int RWIcount = 0; /** @@ -154,7 +153,6 @@ public void CompleteRendering() { * implementation but ArrayList and pretty much everything in * Collections is way too slow for what we're trying to accomplish. */ - void ResizeRWIBuffer() { ColVars fake = new ColVars<>(); @@ -168,27 +166,26 @@ void ResizeRWIBuffer() { // RWI.length); } - @Override - public ColVars[] getRWI() { - return RWI; - } - - @Override - public void setExecutors(RenderWallExecutor[] RWIExec) { - this.RWIExec=RWIExec; - - } - @Override - public void sync(){ - try { - drawsegsbarrier.await(); - } catch (InterruptedException | BrokenBarrierException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + public ColVars[] getRWI() { + return RWI; + } + + @Override + public void setExecutors(RenderWallExecutor[] RWIExec) { + this.RWIExec = RWIExec; + + } + + @Override + public void sync() { + try { + drawsegsbarrier.await(); + } catch (InterruptedException | BrokenBarrierException e) { + LOGGER.log(Level.SEVERE, "sync failure", e); + } // TODO Auto-generated catch block - } + } } protected final class ParallelPlanes extends PlaneDrawer { @@ -212,9 +209,9 @@ public void DrawPlanes() { // vpw[0].setRange(0,lastvisplane/2); // vpw[1].setRange(lastvisplane/2,lastvisplane); - - for (int i = 0; i < NUMFLOORTHREADS; i++) + for (int i = 0; i < NUMFLOORTHREADS; i++) { tp.execute(vpw[i]); + } } } // End Plane class @@ -239,7 +236,7 @@ protected final class ParallelSegs2 extends SegDrawer { RenderSegExecutor[] RSIExec; final AbstractParallelRenderer APR; - + ParallelSegs2(AbstractParallelRenderer APR) { super(APR); this.APR = APR; @@ -260,43 +257,45 @@ protected void RenderSegLoop() { yl = (topfrac + HEIGHTUNIT - 1) >> HEIGHTBITS; // no space above wall? - if (yl < ceilingclip[rw_x] + 1) + if (yl < ceilingclip[rw_x] + 1) { yl = ceilingclip[rw_x] + 1; + } if (markceiling) { top = ceilingclip[rw_x] + 1; bottom = yl - 1; - if (bottom >= floorclip[rw_x]) + if (bottom >= floorclip[rw_x]) { bottom = floorclip[rw_x] - 1; + } if (top <= bottom) { vp_vars.visplanes[vp_vars.ceilingplane].setTop(rw_x, - (char) top); + (char) top); vp_vars.visplanes[vp_vars.ceilingplane].setBottom(rw_x, - (char) bottom); + (char) bottom); } } yh = bottomfrac >> HEIGHTBITS; - if (yh >= floorclip[rw_x]) + if (yh >= floorclip[rw_x]) { yh = floorclip[rw_x] - 1; + } // System.out.printf("Precompute: rw %d yl %d yh %d\n",rw_x,yl,yh); - // A particular seg has been identified as a floor marker. - if (markfloor) { top = yh + 1; bottom = floorclip[rw_x] - 1; - if (top <= ceilingclip[rw_x]) + if (top <= ceilingclip[rw_x]) { top = ceilingclip[rw_x] + 1; + } if (top <= bottom) { vp_vars.visplanes[vp_vars.floorplane].setTop(rw_x, - (char) top); + (char) top); vp_vars.visplanes[vp_vars.floorplane].setBottom(rw_x, - (char) bottom); + (char) bottom); } } @@ -305,11 +304,11 @@ protected void RenderSegLoop() { // calculate texture offset. Still important to do because // of masked - angle = - Tables.toBAMIndex(rw_centerangle - + (int) APR.view.xtoviewangle[rw_x]); - texturecolumn = - rw_offset - FixedMul(finetangent[angle], rw_distance); + angle + = Tables.toBAMIndex(rw_centerangle + + (int) APR.view.xtoviewangle[rw_x]); + texturecolumn + = rw_offset - FixedMul(finetangent[angle], rw_distance); texturecolumn >>= FRACBITS; } @@ -328,18 +327,21 @@ protected void RenderSegLoop() { mid = pixhigh >> HEIGHTBITS; pixhigh += pixhighstep; - if (mid >= floorclip[rw_x]) + if (mid >= floorclip[rw_x]) { mid = floorclip[rw_x] - 1; + } if (mid >= yl) { APR.dcvars.dc_source = APR.TexMan.GetCachedColumn(toptexture, texturecolumn); ceilingclip[rw_x] = (short) mid; - } else + } else { ceilingclip[rw_x] = (short) (yl - 1); + } } else { // no top wall - if (markceiling) + if (markceiling) { ceilingclip[rw_x] = (short) (yl - 1); + } } if (bottomtexture != 0) { @@ -348,18 +350,21 @@ protected void RenderSegLoop() { pixlow += pixlowstep; // no space above wall? - if (mid <= ceilingclip[rw_x]) + if (mid <= ceilingclip[rw_x]) { mid = ceilingclip[rw_x] + 1; + } if (mid <= yh) { APR.dcvars.dc_source = APR.TexMan.GetCachedColumn(bottomtexture, texturecolumn); floorclip[rw_x] = (short) mid; - } else + } else { floorclip[rw_x] = (short) (yh + 1); + } } else { // no bottom wall - if (markfloor) + if (markfloor) { floorclip[rw_x] = (short) (yh + 1); + } } if (maskedtexture) { @@ -436,7 +441,6 @@ void RenderRSIPipeline() { * implementation but ArrayList and pretty much everything in * Collections is way too slow for what we're trying to accomplish. */ - void ResizeRSIBuffer() { RenderSegInstruction fake = new RenderSegInstruction<>(); // Bye bye, old RSI. @@ -446,7 +450,7 @@ void ResizeRSIBuffer() { RSIExec[i].updateRSI(RSI); } - System.out.println("RWI Buffer resized. Actual capacity " + RSI.length); + LOGGER.log(Level.INFO, String.format("RWI Buffer resized. Actual capacity %d", RSI.length)); } } @@ -482,12 +486,10 @@ public void DrawPlanes() { // / AKA "Render Wall Instruction": instructions that store only a single // column // from a wall - /** * R_InitRSISubsystem Initialize RSIs and RSI Executors. Pegs them to the * RSI, ylookup and screen[0]. */ - // protected abstract void InitRSISubsystem(); /* @@ -507,9 +509,7 @@ public void DrawPlanes() { * screen,visplanebarrier,NUMFLOORTHREADS); detailaware.add((IDetailAware) * vpw[i]); } } */ - /** Creates RMI Executors */ - // protected abstract void InitRMISubsystem(); /* @@ -533,13 +533,12 @@ public void DrawPlanes() { * ,ylookup,columnofs,maskedcvars,screen,I) ); detailaware.add(RMIExec[i]); * } } */ - @Override - public void Init(){ - super.Init(); - InitParallelStuff(); + public void Init() { + super.Init(); + InitParallelStuff(); } - + /** * Any scaling and implementation-specific stuff to do for parallel stuff * should go here. This method is called internally by the public Init(). @@ -547,13 +546,12 @@ public void Init(){ * called this. */ protected abstract void InitParallelStuff(); - + /** Override this in one of the final implementors, if you want it to work */ - @Override - public RenderWallExecutor[] InitRWIExecutors(int num,ColVars[] RWI){ - return null; + public RenderWallExecutor[] InitRWIExecutors(int num, ColVars[] RWI) { + return null; } - - RWI.Get RWIs; + + RWI.Get RWIs; } diff --git a/src/rr/parallel/IGetSmpColumn.java b/src/rr/parallel/IGetSmpColumn.java index 14c603f2..f11839dc 100644 --- a/src/rr/parallel/IGetSmpColumn.java +++ b/src/rr/parallel/IGetSmpColumn.java @@ -8,16 +8,14 @@ * @author Maes * */ - /** * Special version of GetColumn meant to be called concurrently by different * seg rendering threads, identfiex by index. This serves to avoid stomping * on mutual cached textures and causing crashes. * */ - public interface IGetSmpColumn { - column_t GetSmpColumn(int tex, int col,int id); + column_t GetSmpColumn(int tex, int col, int id); } diff --git a/src/rr/parallel/MaskedWorker.java b/src/rr/parallel/MaskedWorker.java index 0e42764e..3d102176 100644 --- a/src/rr/parallel/MaskedWorker.java +++ b/src/rr/parallel/MaskedWorker.java @@ -5,7 +5,12 @@ import static data.Defines.pw_invisibility; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; -import static m.fixed_t.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import static m.fixed_t.FRACBITS; +import static m.fixed_t.FRACUNIT; +import static m.fixed_t.FixedMul; +import mochadoom.Loggers; import static p.mobj_t.MF_TRANSLATION; import p.pspdef_t; import rr.AbstractThings; @@ -21,7 +26,7 @@ import rr.drawfuns.R_DrawTranslatedColumn; import rr.drawfuns.R_DrawTranslatedColumnLow; import rr.drawseg_t; -import static rr.line_t.*; +import static rr.line_t.ML_DONTPEGBOTTOM; import rr.patch_t; import rr.spritedef_t; import rr.spriteframe_t; @@ -39,108 +44,108 @@ * @param * @param */ +public abstract class MaskedWorker extends AbstractThings implements Runnable, IDetailAware { + + private static final Logger LOGGER = Loggers.getLogger(MaskedWorker.class.getName()); + + private final static boolean DEBUG = false; + private final static boolean RANGECHECK = false; -public abstract class MaskedWorker extends AbstractThings implements Runnable, IDetailAware{ - - private final static boolean DEBUG=false; - private final static boolean RANGECHECK=false; - protected final CyclicBarrier barrier; protected final int id; protected final int numthreads; - + //protected ColVars maskedcvars; - public MaskedWorker(VideoScale vs, SceneRenderer R, int id, int numthreads, CyclicBarrier barrier) { - super(vs, R); - // Workers have their own set, not a "pegged" one. - this.colfuncshi=new ColFuncs<>(); - this.colfuncslow=new ColFuncs<>(); - this.maskedcvars=new ColVars<>(); - this.id=id; - this.numthreads=numthreads; - this.barrier=barrier; + super(vs, R); + // Workers have their own set, not a "pegged" one. + this.colfuncshi = new ColFuncs<>(); + this.colfuncslow = new ColFuncs<>(); + this.maskedcvars = new ColVars<>(); + this.id = id; + this.numthreads = numthreads; + this.barrier = barrier; } - + @Override - public final void completeColumn(){ - // Does nothing. Shuts up inheritance - } - - public static final class HiColor extends MaskedWorker{ - - public HiColor(VideoScale vs, SceneRenderer R,int id, - int[] ylookup, int[] columnofs, int numthreads, short[] screen, + public final void completeColumn() { + // Does nothing. Shuts up inheritance + } + + public static final class HiColor extends MaskedWorker { + + public HiColor(VideoScale vs, SceneRenderer R, int id, + int[] ylookup, int[] columnofs, int numthreads, short[] screen, CyclicBarrier barrier, BlurryTable BLURRY_MAP) { - super(vs, R,id,numthreads, barrier); + super(vs, R, id, numthreads, barrier); - // Non-optimized stuff for masked. - colfuncshi.base=colfuncshi.main=colfuncshi.masked=new R_DrawColumnBoom.HiColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); - colfuncslow.masked=new R_DrawColumnBoomLow.HiColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); + // Non-optimized stuff for masked. + colfuncshi.base = colfuncshi.main = colfuncshi.masked = new R_DrawColumnBoom.HiColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); + colfuncslow.masked = new R_DrawColumnBoomLow.HiColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); - // Fuzzy columns. These are also masked. - colfuncshi.fuzz=new R_DrawFuzzColumn.HiColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I,BLURRY_MAP); - colfuncslow.fuzz=new R_DrawFuzzColumnLow.HiColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I,BLURRY_MAP); + // Fuzzy columns. These are also masked. + colfuncshi.fuzz = new R_DrawFuzzColumn.HiColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I, BLURRY_MAP); + colfuncslow.fuzz = new R_DrawFuzzColumnLow.HiColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I, BLURRY_MAP); + + // Translated columns are usually sprites-only. + colfuncshi.trans = new R_DrawTranslatedColumn.HiColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); + colfuncslow.trans = new R_DrawTranslatedColumnLow.HiColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); - // Translated columns are usually sprites-only. - colfuncshi.trans=new R_DrawTranslatedColumn.HiColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); - colfuncslow.trans=new R_DrawTranslatedColumnLow.HiColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); - - colfuncs=colfuncshi; + colfuncs = colfuncshi; + + } - } - } - - public static final class Indexed extends MaskedWorker{ - public Indexed(VideoScale vs, SceneRenderer R,int id, + public static final class Indexed extends MaskedWorker { + + public Indexed(VideoScale vs, SceneRenderer R, int id, int[] ylookup, int[] columnofs, int numthreads, byte[] screen, CyclicBarrier barrier, BlurryTable BLURRY_MAP) { - super(vs, R,id,numthreads, barrier); - colfuncshi.base=colfuncshi.main=colfuncshi.masked=new R_DrawColumnBoom.Indexed(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); - colfuncslow.masked=new R_DrawColumnBoomLow.Indexed(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); + super(vs, R, id, numthreads, barrier); + colfuncshi.base = colfuncshi.main = colfuncshi.masked = new R_DrawColumnBoom.Indexed(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); + colfuncslow.masked = new R_DrawColumnBoomLow.Indexed(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); // Fuzzy columns. These are also masked. - colfuncshi.fuzz=new R_DrawFuzzColumn.Indexed(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I,BLURRY_MAP); - colfuncslow.fuzz=new R_DrawFuzzColumnLow.Indexed(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I,BLURRY_MAP); + colfuncshi.fuzz = new R_DrawFuzzColumn.Indexed(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I, BLURRY_MAP); + colfuncslow.fuzz = new R_DrawFuzzColumnLow.Indexed(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I, BLURRY_MAP); // Translated columns are usually sprites-only. - colfuncshi.trans=new R_DrawTranslatedColumn.Indexed(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); - colfuncslow.trans=new R_DrawTranslatedColumnLow.Indexed(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); - - colfuncs=colfuncshi; + colfuncshi.trans = new R_DrawTranslatedColumn.Indexed(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); + colfuncslow.trans = new R_DrawTranslatedColumnLow.Indexed(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); + + colfuncs = colfuncshi; } - + } - - public static final class TrueColor extends MaskedWorker{ - public TrueColor(VideoScale vs, SceneRenderer R,int id, + public static final class TrueColor extends MaskedWorker { + + public TrueColor(VideoScale vs, SceneRenderer R, int id, int[] ylookup, int[] columnofs, int numthreads, int[] screen, CyclicBarrier barrier, BlurryTable BLURRY_MAP) { - super(vs, R,id,numthreads, barrier); + super(vs, R, id, numthreads, barrier); // Non-optimized stuff for masked. - colfuncshi.base=colfuncshi.main=colfuncshi.masked=new R_DrawColumnBoom.TrueColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); - colfuncslow.masked=new R_DrawColumnBoomLow.TrueColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); + colfuncshi.base = colfuncshi.main = colfuncshi.masked = new R_DrawColumnBoom.TrueColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); + colfuncslow.masked = new R_DrawColumnBoomLow.TrueColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); // Fuzzy columns. These are also masked. - colfuncshi.fuzz=new R_DrawFuzzColumn.TrueColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I,BLURRY_MAP); - colfuncslow.fuzz=new R_DrawFuzzColumnLow.TrueColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I,BLURRY_MAP); + colfuncshi.fuzz = new R_DrawFuzzColumn.TrueColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I, BLURRY_MAP); + colfuncslow.fuzz = new R_DrawFuzzColumnLow.TrueColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I, BLURRY_MAP); // Translated columns are usually sprites-only. - colfuncshi.trans=new R_DrawTranslatedColumn.TrueColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); - colfuncslow.trans=new R_DrawTranslatedColumnLow.TrueColor(vs.getScreenWidth(),vs.getScreenHeight(),ylookup,columnofs,maskedcvars,screen,I); - - colfuncs=colfuncshi; + colfuncshi.trans = new R_DrawTranslatedColumn.TrueColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); + colfuncslow.trans = new R_DrawTranslatedColumnLow.TrueColor(vs.getScreenWidth(), vs.getScreenHeight(), ylookup, columnofs, maskedcvars, screen, I); + + colfuncs = colfuncshi; } - + } - + protected int startx, endx; - + /** * R_DrawVisSprite mfloorclip and mceilingclip should also be set. * @@ -157,17 +162,18 @@ protected final void DrawVisSprite(vissprite_t vis) { patch_t patch; // The sprite may have been partially drawn on another portion of the // screen. - int bias=startx-vis.x1; - if (bias<0) bias=0; // nope, it ain't. - + int bias = startx - vis.x1; + if (bias < 0) { + bias = 0; // nope, it ain't. + } // Trim bounds to zone NOW - int x1=Math.max(startx, vis.x1); - int x2=Math.min(endx,vis.x2); - + int x1 = Math.max(startx, vis.x1); + int x2 = Math.min(endx, vis.x2); + // At this point, the view angle (and patch) has already been // chosen. Go back. patch = W.CachePatchNum(vis.patch + SM.getFirstSpriteLump()); - + maskedcvars.dc_colormap = vis.colormap; // colfunc=glasscolfunc; if (maskedcvars.dc_colormap == null) { @@ -183,14 +189,14 @@ protected final void DrawVisSprite(vissprite_t vis) { maskedcvars.dc_iscale = Math.abs(vis.xiscale) >> view.detailshift; maskedcvars.dc_texturemid = vis.texturemid; // Add bias to compensate for partially drawn sprite which has not been rejected. - frac = vis.startfrac+vis.xiscale*bias; + frac = vis.startfrac + vis.xiscale * bias; spryscale = vis.scale; sprtopscreen = view.centeryfrac - FixedMul(maskedcvars.dc_texturemid, spryscale); // A texture height of 0 means "not tiling" and holds for // all sprite/masked renders. - maskedcvars.dc_texheight=0; - + maskedcvars.dc_texheight = 0; + for (maskedcvars.dc_x = x1; maskedcvars.dc_x <= x2; maskedcvars.dc_x++, frac += vis.xiscale) { texturecolumn = frac >> FRACBITS; if (true) { @@ -199,9 +205,9 @@ protected final void DrawVisSprite(vissprite_t vis) { } } column = patch.columns[texturecolumn]; - + if (column == null) { - System.err.printf("Null column for texturecolumn %d\n", texturecolumn, x1, x2); + LOGGER.log(Level.WARNING, String.format("Null column for texturecolumn %d", texturecolumn)); } else { DrawMaskedColumn(column); } @@ -217,25 +223,26 @@ protected final void DrawVisSprite(vissprite_t vis) { * @param x1 * @param x2 */ - @Override protected final void RenderMaskedSegRange(drawseg_t ds, int x1, int x2) { - - // Trivial rejection - if (ds.x1>endx || ds.x2 endx || ds.x2 < startx) { + return; + } + // Trim bounds to zone NOW - x1=Math.max(startx, x1); - x2=Math.min(endx,x2); - + x1 = Math.max(startx, x1); + x2 = Math.min(endx, x2); + int index; int lightnum; int texnum; - int bias=startx-ds.x1; // Correct for starting outside + int bias = startx - ds.x1; // Correct for starting outside if (bias < 0) { bias = 0; // nope, it ain't. - } + } // System.out.printf("RenderMaskedSegRange from %d to %d\n",x1,x2); // Calculate light table. @@ -249,10 +256,11 @@ protected final void RenderMaskedSegRange(drawseg_t ds, int x1, int x2) { // System.out.print(" for texture "+textures[texnum].name+"\n:"); lightnum = (frontsector.lightlevel >> colormaps.lightSegShift()) + colormaps.extralight; - if (MyBSP.curline.v1y == MyBSP.curline.v2y) + if (MyBSP.curline.v1y == MyBSP.curline.v2y) { lightnum--; - else if (MyBSP.curline.v1x == MyBSP.curline.v2x) + } else if (MyBSP.curline.v1x == MyBSP.curline.v2x) { lightnum++; + } // Killough code. colormaps.walllights = lightnum >= colormaps.lightLevels() ? colormaps.scalelight[colormaps.lightLevels() - 1] @@ -279,15 +287,16 @@ else if (MyBSP.curline.v1x == MyBSP.curline.v2x) - view.z; } else { maskedcvars.dc_texturemid = frontsector.ceilingheight < backsector.ceilingheight - ? frontsector.ceilingheight - : backsector.ceilingheight; - + ? frontsector.ceilingheight + : backsector.ceilingheight; + maskedcvars.dc_texturemid -= view.z; } maskedcvars.dc_texturemid += MyBSP.curline.sidedef.rowoffset; - if (colormaps.fixedcolormap != null) + if (colormaps.fixedcolormap != null) { maskedcvars.dc_colormap = colormaps.fixedcolormap; + } // Texture height must be set at this point. This will trigger // tiling. For sprites, it should be set to 0. @@ -300,8 +309,9 @@ else if (MyBSP.curline.v1x == MyBSP.curline.v2x) if (colormaps.fixedcolormap == null) { index = spryscale >>> colormaps.lightScaleShift(); - if (index >= colormaps.maxLightScale()) + if (index >= colormaps.maxLightScale()) { index = colormaps.maxLightScale() - 1; + } maskedcvars.dc_colormap = colormaps.walllights[index]; } @@ -312,16 +322,16 @@ else if (MyBSP.curline.v1x == MyBSP.curline.v2x) // draw the texture column_t data = TexMan.GetSmpColumn(texnum, - maskedtexturecol[pmaskedtexturecol + maskedcvars.dc_x],id); - + maskedtexturecol[pmaskedtexturecol + maskedcvars.dc_x], id); + DrawMaskedColumn(data); maskedtexturecol[pmaskedtexturecol + maskedcvars.dc_x] = Short.MAX_VALUE; } spryscale += rw_scalestep; } - } - + } + /** * R_DrawPSprite * @@ -331,7 +341,6 @@ else if (MyBSP.curline.v1x == MyBSP.curline.v2x) * Also different than normal implementation. * */ - @Override protected final void DrawPSprite(pspdef_t psp) { @@ -345,7 +354,6 @@ protected final void DrawPSprite(pspdef_t psp) { boolean flip; // - // decide which patch to use (in terms of angle?) if (RANGECHECK) { if (psp.state.sprite.ordinal() >= SM.getNumSprites()) { @@ -354,13 +362,13 @@ protected final void DrawPSprite(pspdef_t psp) { } sprdef = SM.getSprite(psp.state.sprite.ordinal()); - + if (RANGECHECK) { if ((psp.state.frame & FF_FRAMEMASK) >= sprdef.numframes) { I.Error("R_ProjectSprite: invalid sprite frame %d : %d ", psp.state.sprite, psp.state.frame); } } - + sprframe = sprdef.spriteframes[psp.state.frame & FF_FRAMEMASK]; // Base frame for "angle 0" aka viewed from dead-front. @@ -378,20 +386,22 @@ protected final void DrawPSprite(pspdef_t psp) { x1 = (view.centerxfrac + FixedMul(tx, pspritescale)) >> FRACBITS; // off the right side - if (x1 > endx) + if (x1 > endx) { return; + } tx += spritewidth[lump]; x2 = ((view.centerxfrac + FixedMul(tx, pspritescale)) >> FRACBITS) - 1; // off the left side - if (x2 < startx) + if (x2 < startx) { return; + } // store information in a vissprite ? vis = avis; vis.mobjflags = 0; - vis.texturemid = ((BASEYCENTER+view.lookdir) << FRACBITS) + FRACUNIT / 2 + vis.texturemid = ((BASEYCENTER + view.lookdir) << FRACBITS) + FRACUNIT / 2 - (psp.sy - spritetopoffset[lump]); vis.x1 = x1 < startx ? startx : x1; vis.x2 = x2 >= endx ? endx - 1 : x2; @@ -405,8 +415,9 @@ protected final void DrawPSprite(pspdef_t psp) { vis.startfrac = 0; } - if (vis.x1 > x1) + if (vis.x1 > x1) { vis.startfrac += vis.xiscale * (vis.x1 - x1); + } vis.patch = lump; @@ -431,8 +442,7 @@ protected final void DrawPSprite(pspdef_t psp) { //System.out.printf("Weapon draw from %d to %d\n",vis.x1,vis.x2); DrawVisSprite(vis); } - - + /** * R_DrawMasked * @@ -444,7 +454,6 @@ protected final void DrawPSprite(pspdef_t psp) { * * */ - @Override public void run() { // vissprite_t spr; @@ -452,37 +461,33 @@ public void run() { drawseg_t dss; // Sprites should already be sorted for distance - colfunc = colfuncs.masked; // Sprites use fully-masked capable - // function. + // function. // Update view height - - this.maskedcvars.viewheight=view.height; - this.maskedcvars.centery=view.centery; - this.startx=((id*view.width)/numthreads); - this.endx=(((id+1)*view.width)/numthreads); - + this.maskedcvars.viewheight = view.height; + this.maskedcvars.centery = view.centery; + this.startx = ((id * view.width) / numthreads); + this.endx = (((id + 1) * view.width) / numthreads); + // Update thread's own vissprites - - final vissprite_t[] vissprites=VIS.getVisSprites(); - final int numvissprites=VIS.getNumVisSprites(); - + final vissprite_t[] vissprites = VIS.getVisSprites(); + final int numvissprites = VIS.getNumVisSprites(); + //System.out.printf("Sprites to render: %d\n",numvissprites); - // Try drawing all sprites that are on your side of // the screen. Limit by x1 and x2, if you have to. for (int i = 0; i < numvissprites; i++) { DrawSprite(vissprites[i]); } - - //System.out.printf("Segs to render: %d\n",ds_p); + //System.out.printf("Segs to render: %d\n",ds_p); // render any remaining masked mid textures for (ds = seg_vars.ds_p - 1; ds >= 0; ds--) { dss = seg_vars.drawsegs[ds]; - if (!(dss.x1>endx || dss.x2 endx || dss.x2 < startx) && !dss.nullMaskedTextureCol()) { + RenderMaskedSegRange(dss, dss.x1, dss.x2); + } } // draw the psprites on top of everything // but does not draw on side views @@ -491,14 +496,13 @@ public void run() { colfunc = colfuncs.player; DrawPlayerSprites(); colfunc = colfuncs.masked; - + try { barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "MaskedWorker run failure", e); } // TODO Auto-generated catch block } - + } diff --git a/src/rr/parallel/ParallelRenderer.java b/src/rr/parallel/ParallelRenderer.java index c81e4710..0e94839e 100644 --- a/src/rr/parallel/ParallelRenderer.java +++ b/src/rr/parallel/ParallelRenderer.java @@ -3,6 +3,9 @@ import doom.DoomMain; import doom.player_t; import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import rr.SimpleThings; import rr.drawfuns.ColVars; import rr.drawfuns.R_DrawColumnBoom; @@ -30,18 +33,19 @@ * * @author admin */ - public abstract class ParallelRenderer extends AbstractParallelRenderer { + private static final Logger LOGGER = Loggers.getLogger(ParallelRenderer.class.getName()); + public ParallelRenderer(DoomMain DM, int wallthread, int floorthreads, int nummaskedthreads) { super(DM, wallthread, floorthreads, nummaskedthreads); - + // Register parallel seg drawer with list of RWI subsystems. - ParallelSegs tmp= new ParallelSegs(this); + ParallelSegs tmp = new ParallelSegs(this); this.MySegs = tmp; - RWIs= tmp; - + RWIs = tmp; + this.MyThings = new SimpleThings<>(DM.vs, this); //this.MyPlanes = new Planes(this);// new ParallelPlanes(DM.R); @@ -56,8 +60,6 @@ public ParallelRenderer(DoomMain DM) { this(DM, 1, 1, 2); } - - /** * R_RenderView As you can guess, this renders the player view of a * particular player object. In practice, it could render the view of any @@ -66,7 +68,6 @@ public ParallelRenderer(DoomMain DM) { * * @throws IOException */ - public void RenderPlayerView(player_t player) { // Viewing variables are set according to the player's mobj. Interesting @@ -80,7 +81,6 @@ public void RenderPlayerView(player_t player) { * mobj_t crap=(mobj_t)shit; player.mo=crap; } catch (ClassCastException * e){ } } */ - // Clear buffers. MyBSP.ClearClipSegs(); seg_vars.ClearDrawSegs(); @@ -94,7 +94,6 @@ public void RenderPlayerView(player_t player) { MyBSP.RenderBSPNode(DOOM.levelLoader.numnodes - 1); // System.out.printf("Submitted %d RWIs\n",RWIcount); - MySegs.CompleteRendering(); // Check for new console commands. @@ -111,8 +110,6 @@ public void RenderPlayerView(player_t player) { // drawsegsbarrier.await(); // visplanebarrier.await(); - - MyThings.DrawMasked(); // RenderRMIPipeline(); @@ -120,7 +117,6 @@ public void RenderPlayerView(player_t player) { * try { maskedbarrier.await(); } catch (Exception e) { * e.printStackTrace(); } */ - // Check for new console commands. DOOM.gameNetworking.NetUpdate(); } @@ -201,10 +197,10 @@ protected void InitMaskedWorkers() { maskedworkers = new MaskedWorker[NUMMASKEDTHREADS]; for (int i = 0; i < NUMMASKEDTHREADS; i++) { maskedworkers[i] = new MaskedWorker.Indexed( - DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, - screen, maskedbarrier, BLURRY_MAP + DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, + screen, maskedbarrier, BLURRY_MAP ); - + detailaware.add(maskedworkers[i]); // "Peg" to sprite manager. maskedworkers[i].cacheSpriteManager(DOOM.spriteManager); @@ -268,16 +264,13 @@ protected void InitParallelStuff() { * columnofs, ylookup, screen, visplanebarrier, NUMFLOORTHREADS); * //vpw[i].id = i; detailaware.add((IDetailAware) vpw[i]); } } */ - - - /* + /* * TODO: relay to dependent objects. super.initScaling(); * ColVars fake = new ColVars(); RWI = * C2JUtils.createArrayOfObjects(fake, SCREENWIDTH * 3); // Be MUCH more * generous with this one. RMI = C2JUtils.createArrayOfObjects(fake, * SCREENWIDTH * 6); - */ - + */ protected abstract void InitMaskedWorkers(); public static final class HiColor extends ParallelRenderer { @@ -300,10 +293,10 @@ protected void InitMaskedWorkers() { maskedworkers = new MaskedWorker[NUMMASKEDTHREADS]; for (int i = 0; i < NUMMASKEDTHREADS; i++) { maskedworkers[i] = new MaskedWorker.HiColor( - DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, - screen, maskedbarrier, BLURRY_MAP + DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, + screen, maskedbarrier, BLURRY_MAP ); - + detailaware.add(maskedworkers[i]); // "Peg" to sprite manager. maskedworkers[i].cacheSpriteManager(DOOM.spriteManager); @@ -318,7 +311,7 @@ protected void InitMaskedWorkers() { protected void InitColormaps() throws IOException { colormaps.colormaps = DOOM.graphicSystem.getColorMap(); - System.out.println("COLORS15 Colormaps: " + colormaps.colormaps.length); + LOGGER.log(Level.FINE, String.format("COLORS15 Colormaps: %d", colormaps.colormaps.length)); // MAES: blurry effect is hardcoded to this colormap. // Pointless, since we don't use indexes. Instead, a half-brite @@ -432,7 +425,7 @@ protected void InitColormaps() throws IOException { colormaps.colormaps = DOOM.graphicSystem.getColorMap(); - System.out.println("COLORS15 Colormaps: " + colormaps.colormaps.length); + LOGGER.log(Level.FINE, String.format("COLORS15 Colormaps: %d", colormaps.colormaps.length)); // MAES: blurry effect is hardcoded to this colormap. // Pointless, since we don't use indexes. Instead, a half-brite @@ -446,10 +439,10 @@ protected void InitMaskedWorkers() { maskedworkers = new MaskedWorker[NUMMASKEDTHREADS]; for (int i = 0; i < NUMMASKEDTHREADS; i++) { maskedworkers[i] = new MaskedWorker.TrueColor( - DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, screen, - maskedbarrier, BLURRY_MAP + DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, screen, + maskedbarrier, BLURRY_MAP ); - + detailaware.add(maskedworkers[i]); // "Peg" to sprite manager. maskedworkers[i].cacheSpriteManager(DOOM.spriteManager); diff --git a/src/rr/parallel/ParallelRenderer2.java b/src/rr/parallel/ParallelRenderer2.java index e56691e3..9f519013 100644 --- a/src/rr/parallel/ParallelRenderer2.java +++ b/src/rr/parallel/ParallelRenderer2.java @@ -1,12 +1,15 @@ package rr.parallel; -import static data.Limits.*; +import static data.Limits.MAXSEGS; import doom.DoomMain; import doom.player_t; import java.io.IOException; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Executors; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import rr.drawfuns.R_DrawColumnBoom; import rr.drawfuns.R_DrawColumnBoomLow; import rr.drawfuns.R_DrawColumnBoomOpt; @@ -28,14 +31,15 @@ * @author velktron * */ - public abstract class ParallelRenderer2 extends AbstractParallelRenderer { - + + private static final Logger LOGGER = Loggers.getLogger(ParallelRenderer2.class.getName()); + @SuppressWarnings("unchecked") public ParallelRenderer2(DoomMain DOOM, int wallthread, int floorthreads, int nummaskedthreads) { super(DOOM, wallthread, floorthreads, nummaskedthreads); - System.out.println("Parallel Renderer 2 (Seg-based)"); - + LOGGER.log(Level.FINE, "Parallel Renderer 2 (Seg-based)"); + this.MySegs = new ParallelSegs2<>(this); this.MyPlanes = new ParallelPlanes<>(DOOM, this); this.MyThings = new ParallelThings2<>(DOOM.vs, this); @@ -44,15 +48,15 @@ public ParallelRenderer2(DoomMain DOOM, int wallthread, int floorthreads, // Masked workers. ((ParallelThings2) MyThings).maskedworkers = maskedworkers = new MaskedWorker[NUMMASKEDTHREADS]; InitMaskedWorkers(); - + ((ParallelSegs2) MySegs).RSI = malloc(RenderSegInstruction::new, RenderSegInstruction[]::new, MAXSEGS * 3); } - @Override + @Override @SuppressWarnings("unchecked") - protected void InitParallelStuff() { - // Prepare parallel stuff - ((ParallelSegs2) MySegs).RSIExec = new RenderSegExecutor[NUMWALLTHREADS]; + protected void InitParallelStuff() { + // Prepare parallel stuff + ((ParallelSegs2) MySegs).RSIExec = new RenderSegExecutor[NUMWALLTHREADS]; tp = Executors.newFixedThreadPool(NUMWALLTHREADS + NUMFLOORTHREADS); // Prepare the barrier for MAXTHREADS + main thread. //wallbarrier=new CyclicBarrier(NUMWALLTHREADS+1); @@ -67,28 +71,25 @@ protected void InitParallelStuff() { // If using masked threads, set these too. TexMan.setSMPVars(NUMMASKEDTHREADS); - } - - ///////////////////////// The actual rendering calls /////////////////////// - - /** - * R_RenderView - * - * As you can guess, this renders the player view of a particular player object. - * In practice, it could render the view of any mobj too, provided you adapt the - * SetupFrame method (where the viewing variables are set). - * - */ + } + ///////////////////////// The actual rendering calls /////////////////////// + /** + * R_RenderView + * + * As you can guess, this renders the player view of a particular player object. + * In practice, it could render the view of any mobj too, provided you adapt the + * SetupFrame method (where the viewing variables are set). + * + */ @Override @SuppressWarnings("unchecked") - public void RenderPlayerView (player_t player) - { - // Viewing variables are set according to the player's mobj. Interesting hacks like - // free cameras or monster views can be done. - SetupFrame (player); + public void RenderPlayerView(player_t player) { + // Viewing variables are set according to the player's mobj. Interesting hacks like + // free cameras or monster views can be done. + SetupFrame(player); - /* Uncommenting this will result in a very existential experience + /* Uncommenting this will result in a very existential experience if (Math.random()>0.999){ thinker_t shit=P.getRandomThinker(); try { @@ -98,27 +99,25 @@ public void RenderPlayerView (player_t player) } }*/ - - // Clear buffers. - MyBSP.ClearClipSegs(); + // Clear buffers. + MyBSP.ClearClipSegs(); seg_vars.ClearDrawSegs(); vp_vars.ClearPlanes(); - MySegs.ClearClips(); + MySegs.ClearClips(); VIS.ClearSprites(); // Check for new console commands. DOOM.gameNetworking.NetUpdate(); - // The head node is the last node output. - MyBSP.RenderBSPNode(DOOM.levelLoader.numnodes - 1); - + // The head node is the last node output. + MyBSP.RenderBSPNode(DOOM.levelLoader.numnodes - 1); + // RenderRMIPipeline(); /* * try { maskedbarrier.await(); } catch (Exception e) { * e.printStackTrace(); } */ - - ((ParallelSegs2) MySegs).RenderRSIPipeline(); + ((ParallelSegs2) MySegs).RenderRSIPipeline(); // System.out.printf("Submitted %d RSIs\n",RSIcount); MySegs.CompleteRendering(); @@ -126,14 +125,14 @@ public void RenderPlayerView (player_t player) // Check for new console commands. DOOM.gameNetworking.NetUpdate(); - // "Warped floor" fixed, same-height visplane merging fixed. - MyPlanes.DrawPlanes (); + // "Warped floor" fixed, same-height visplane merging fixed. + MyPlanes.DrawPlanes(); - try { - visplanebarrier.await(); - } catch (InterruptedException | BrokenBarrierException e){ - e.printStackTrace(); - } + try { + visplanebarrier.await(); + } catch (InterruptedException | BrokenBarrierException e) { + LOGGER.log(Level.SEVERE, "RenderPlayerView failure", e); + } // Check for new console commands. DOOM.gameNetworking.NetUpdate(); @@ -143,12 +142,11 @@ public void RenderPlayerView (player_t player) // drawsegsbarrier.await(); // visplanebarrier.await(); - - MyThings.DrawMasked(); - } + } abstract protected void InitRSISubsystem(); + /* * { // CATCH: this must be executed AFTER screen is set, and // AFTER we * initialize the RWI themselves, // before V is set (right?) //offsets=new @@ -166,15 +164,11 @@ public void RenderPlayerView (player_t player) * screen,visplanebarrier,NUMFLOORTHREADS); detailaware.add((IDetailAware) * vpw[i]); } } */ - - /** - * R_Init - */ - - //public int detailLevel; - //public int screenblocks=9; // has defa7ult - + * R_Init + */ + //public int detailLevel; + //public int screenblocks=9; // has defa7ult protected abstract void InitMaskedWorkers(); public static final class Indexed extends ParallelRenderer2 { @@ -186,7 +180,7 @@ public Indexed(DoomMain DM, int wallthread, int floorthreads, in colormaps.scalelight = new byte[colormaps.lightLevels()][colormaps.maxLightScale()][]; colormaps.scalelightfixed = new byte[colormaps.maxLightScale()][]; colormaps.zlight = new byte[colormaps.lightLevels()][colormaps.maxLightZ()][]; - + completeInit(); } @@ -221,16 +215,16 @@ protected void InitRSISubsystem() { protected void InitMaskedWorkers() { for (int i = 0; i < NUMMASKEDTHREADS; i++) { maskedworkers[i] = new MaskedWorker.Indexed( - DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, - screen, maskedbarrier, BLURRY_MAP + DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, + screen, maskedbarrier, BLURRY_MAP ); - + detailaware.add(maskedworkers[i]); // "Peg" to sprite manager. maskedworkers[i].cacheSpriteManager(DOOM.spriteManager); } } - + @Override protected void InitColormaps() throws IOException { // Load in the light tables, @@ -240,7 +234,7 @@ protected void InitColormaps() throws IOException { BLURRY_MAP = DOOM.graphicSystem.getBlurryTable(); // colormaps = (byte *)( ((int)colormaps + 255)&~0xff); } - + @Override protected void R_InitDrawingFunctions() { @@ -276,7 +270,7 @@ protected void R_InitDrawingFunctions() { super.R_InitDrawingFunctions(); } } - + public static final class HiColor extends ParallelRenderer2 { public HiColor(DoomMain DM, int wallthread, int floorthreads, int nummaskedthreads) { @@ -321,27 +315,27 @@ protected void InitRSISubsystem() { protected void InitMaskedWorkers() { for (int i = 0; i < NUMMASKEDTHREADS; i++) { maskedworkers[i] = new MaskedWorker.HiColor( - DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, - screen, maskedbarrier, BLURRY_MAP + DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, + screen, maskedbarrier, BLURRY_MAP ); - + detailaware.add(maskedworkers[i]); // "Peg" to sprite manager. maskedworkers[i].cacheSpriteManager(DOOM.spriteManager); } } - + @Override protected void InitColormaps() throws IOException { colormaps.colormaps = DOOM.graphicSystem.getColorMap(); - System.out.println("COLORS15 Colormaps: " + colormaps.colormaps.length); + LOGGER.log(Level.FINE, String.format("COLORS15 Colormaps: %d", colormaps.colormaps.length)); // MAES: blurry effect is hardcoded to this colormap. // Pointless, since we don't use indexes. Instead, a half-brite // processing works just fine. BLURRY_MAP = DOOM.graphicSystem.getBlurryTable(); } - + @Override protected void R_InitDrawingFunctions() { @@ -377,7 +371,7 @@ protected void R_InitDrawingFunctions() { super.R_InitDrawingFunctions(); } } - + public static final class TrueColor extends ParallelRenderer2 { public TrueColor(DoomMain DM, int wallthread, int floorthreads, int nummaskedthreads) { @@ -422,27 +416,27 @@ protected void InitRSISubsystem() { protected void InitMaskedWorkers() { for (int i = 0; i < NUMMASKEDTHREADS; i++) { maskedworkers[i] = new MaskedWorker.TrueColor( - DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, screen, - maskedbarrier, BLURRY_MAP + DOOM.vs, this, i, ylookup, columnofs, NUMMASKEDTHREADS, screen, + maskedbarrier, BLURRY_MAP ); - + detailaware.add(maskedworkers[i]); // "Peg" to sprite manager. maskedworkers[i].cacheSpriteManager(DOOM.spriteManager); } } - + @Override protected void InitColormaps() throws IOException { colormaps.colormaps = DOOM.graphicSystem.getColorMap(); - System.out.println("COLORS15 Colormaps: " + colormaps.colormaps.length); + LOGGER.log(Level.FINE, String.format("COLORS15 Colormaps: %d", colormaps.colormaps.length)); // MAES: blurry effect is hardcoded to this colormap. // Pointless, since we don't use indexes. Instead, a half-brite // processing works just fine. BLURRY_MAP = DOOM.graphicSystem.getBlurryTable(); - } - + } + @Override protected void R_InitDrawingFunctions() { diff --git a/src/rr/parallel/ParallelThings.java b/src/rr/parallel/ParallelThings.java index 07985e8e..53d63579 100644 --- a/src/rr/parallel/ParallelThings.java +++ b/src/rr/parallel/ParallelThings.java @@ -4,6 +4,9 @@ import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Executor; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import rr.AbstractThings; import rr.IDetailAware; import rr.SceneRenderer; @@ -35,16 +38,14 @@ * * @author velktron */ +public abstract class ParallelThings extends AbstractThings { + + private static final Logger LOGGER = Loggers.getLogger(ParallelThings.class.getName()); -public abstract class ParallelThings extends AbstractThings { - // stuff to get from container - - /** Render Masked Instuction subsystem. Essentially, a way to split sprite work * between threads on a column-basis. */ - protected ColVars[] RMI; /** @@ -53,22 +54,22 @@ public abstract class ParallelThings extends AbstractThings { */ protected int RMIcount = 0; - protected RenderMaskedExecutor[] RMIExec; - + protected RenderMaskedExecutor[] RMIExec; + protected final int NUMMASKEDTHREADS; protected final CyclicBarrier maskedbarrier; protected final Executor tp; - + public ParallelThings(VideoScale vs, SceneRenderer R, Executor tp, int numthreads) { super(vs, R); - this.tp=tp; - this.NUMMASKEDTHREADS=numthreads; - this.maskedbarrier=new CyclicBarrier(NUMMASKEDTHREADS+1); + this.tp = tp; + this.NUMMASKEDTHREADS = numthreads; + this.maskedbarrier = new CyclicBarrier(NUMMASKEDTHREADS + 1); } @Override public void DrawMasked() { - + // This just generates the RMI instructions. super.DrawMasked(); // This splits the work among threads and fires them up @@ -77,20 +78,20 @@ public void DrawMasked() { try { // Wait for them to be done. maskedbarrier.await(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (BrokenBarrierException e) { + } catch (InterruptedException | BrokenBarrierException e) { // TODO Auto-generated catch block - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "ParallelThings DrawMasked failure", e); } + // TODO Auto-generated catch block + } @Override public void completeColumn() { - if (view.detailshift == 1) + if (view.detailshift == 1) { flags = DcFlags.LOW_DETAIL; + } // Don't wait to go over if (RMIcount >= RMI.length) { ResizeRMIBuffer(); @@ -104,14 +105,13 @@ public void completeColumn() { } int flags; - - + protected void RenderRMIPipeline() { for (int i = 0; i < NUMMASKEDTHREADS; i++) { RMIExec[i].setRange((i * this.vs.getScreenWidth()) / NUMMASKEDTHREADS, - ((i + 1) * this.vs.getScreenWidth()) / NUMMASKEDTHREADS); + ((i + 1) * this.vs.getScreenWidth()) / NUMMASKEDTHREADS); RMIExec[i].setRMIEnd(RMIcount); // RWIExec[i].setRange(i%NUMWALLTHREADS,RWIcount,NUMWALLTHREADS); tp.execute(RMIExec[i]); @@ -120,11 +120,12 @@ protected void RenderRMIPipeline() { // System.out.println("RWI count"+RWIcount); RMIcount = 0; } - + protected void ResizeRMIBuffer() { - ColVars fake = new ColVars(); - ColVars[] tmp = // TODO Auto-generated constructor stub - C2JUtils.createArrayOfObjects(fake, RMI.length * 2); + ColVars fake = new ColVars<>(); + ColVars[] tmp + = // TODO Auto-generated constructor stub + C2JUtils.createArrayOfObjects(fake, RMI.length * 2); System.arraycopy(RMI, 0, tmp, 0, RMI.length); // Bye bye, old RMI. @@ -133,67 +134,61 @@ protected void ResizeRMIBuffer() { for (int i = 0; i < NUMMASKEDTHREADS; i++) { RMIExec[i].updateRMI(RMI); } - - System.err.println("RMI Buffer resized. Actual capacity " + RMI.length); + + LOGGER.log(Level.FINE, String.format("RMI Buffer resized. Actual capacity %d", RMI.length)); } - - protected abstract void InitRMISubsystem(int[] columnofs, int[] ylookup,V screen, CyclicBarrier - maskedbarrier,BlurryTable BLURRY_MAP, List detailaware); - - public static class Indexed extends ParallelThings{ - public Indexed(VideoScale vs, SceneRenderer R, Executor tp, int numthreads) { + protected abstract void InitRMISubsystem(int[] columnofs, int[] ylookup, V screen, CyclicBarrier maskedbarrier, BlurryTable BLURRY_MAP, List detailaware); + + public static class Indexed extends ParallelThings { + + public Indexed(VideoScale vs, SceneRenderer R, Executor tp, int numthreads) { super(vs, R, tp, numthreads); } - protected void InitRMISubsystem(int[] columnofs, int[] ylookup,byte[] screen, CyclicBarrier - maskedbarrier,BlurryTable BLURRY_MAP, List detailaware) { - for (int i = 0; i < NUMMASKEDTHREADS; i++) { - RMIExec[i] = - new RenderMaskedExecutor.Indexed(vs.getScreenWidth(), vs.getScreenHeight(), columnofs, - ylookup, screen, RMI, maskedbarrier,I,BLURRY_MAP); - - detailaware.add(RMIExec[i]); + protected void InitRMISubsystem(int[] columnofs, int[] ylookup, byte[] screen, CyclicBarrier maskedbarrier, BlurryTable BLURRY_MAP, List detailaware) { + for (int i = 0; i < NUMMASKEDTHREADS; i++) { + RMIExec[i] + = new RenderMaskedExecutor.Indexed(vs.getScreenWidth(), vs.getScreenHeight(), columnofs, + ylookup, screen, RMI, maskedbarrier, I, BLURRY_MAP); + + detailaware.add(RMIExec[i]); } } } - - public static class HiColor extends ParallelThings{ - + + public static class HiColor extends ParallelThings { public HiColor(VideoScale vs, SceneRenderer R, Executor tp, int numthreads) { super(vs, R, tp, numthreads); } - protected void InitRMISubsystem(int[] columnofs, int[] ylookup,short[] screen, CyclicBarrier - maskedbarrier,BlurryTable BLURRY_MAP, List detailaware) { + protected void InitRMISubsystem(int[] columnofs, int[] ylookup, short[] screen, CyclicBarrier maskedbarrier, BlurryTable BLURRY_MAP, List detailaware) { for (int i = 0; i < NUMMASKEDTHREADS; i++) { - RMIExec[i] = - new RenderMaskedExecutor.HiColor(vs.getScreenWidth(), vs.getScreenHeight(), columnofs, - ylookup, screen, RMI, maskedbarrier,I, BLURRY_MAP); - + RMIExec[i] + = new RenderMaskedExecutor.HiColor(vs.getScreenWidth(), vs.getScreenHeight(), columnofs, + ylookup, screen, RMI, maskedbarrier, I, BLURRY_MAP); + detailaware.add(RMIExec[i]); - } } } - -public static class TrueColor extends ParallelThings{ + } + public static class TrueColor extends ParallelThings { public TrueColor(VideoScale vs, SceneRenderer R, Executor tp, int numthreads) { - super(vs, R, tp, numthreads); - } + super(vs, R, tp, numthreads); + } - protected void InitRMISubsystem(int[] columnofs, int[] ylookup,int[] screen, CyclicBarrier - maskedbarrier,BlurryTable BLURRY_MAP, List detailaware) { + protected void InitRMISubsystem(int[] columnofs, int[] ylookup, int[] screen, CyclicBarrier maskedbarrier, BlurryTable BLURRY_MAP, List detailaware) { for (int i = 0; i < NUMMASKEDTHREADS; i++) { - RMIExec[i] = - new RenderMaskedExecutor.TrueColor(vs.getScreenWidth(), vs.getScreenHeight(), columnofs, - ylookup, screen, RMI, maskedbarrier,I, BLURRY_MAP); - + RMIExec[i] + = new RenderMaskedExecutor.TrueColor(vs.getScreenWidth(), vs.getScreenHeight(), columnofs, + ylookup, screen, RMI, maskedbarrier, I, BLURRY_MAP); + detailaware.add(RMIExec[i]); - } } } + } } diff --git a/src/rr/parallel/ParallelThings2.java b/src/rr/parallel/ParallelThings2.java index 820e6809..dd83fe72 100644 --- a/src/rr/parallel/ParallelThings2.java +++ b/src/rr/parallel/ParallelThings2.java @@ -3,6 +3,9 @@ import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Executor; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import rr.IMaskedDrawer; import rr.ISpriteManager; import rr.IVisSpriteManagement; @@ -27,17 +30,18 @@ * @author velktron * */ +public final class ParallelThings2 implements IMaskedDrawer { -public final class ParallelThings2 implements IMaskedDrawer { + private static final Logger LOGGER = Loggers.getLogger(ParallelThings2.class.getName()); - MaskedWorker[] maskedworkers; + MaskedWorker[] maskedworkers; CyclicBarrier maskedbarrier; Executor tp; protected final IVisSpriteManagement VIS; protected final VideoScale vs; - - public ParallelThings2(VideoScale vs, SceneRenderer R) { - this.VIS=R.getVisSpriteManager(); + + public ParallelThings2(VideoScale vs, SceneRenderer R) { + this.VIS = R.getVisSpriteManager(); this.vs = vs; } @@ -52,13 +56,10 @@ public void DrawMasked() { try { maskedbarrier.await(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (BrokenBarrierException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + } catch (InterruptedException | BrokenBarrierException e) { + LOGGER.log(Level.SEVERE, "ParallelThings2 DrawMasked failure", e); } + // TODO Auto-generated catch block } @@ -69,28 +70,32 @@ public void completeColumn() { @Override public void setPspriteScale(int scale) { - for (int i = 0; i < maskedworkers.length; i++) + for (int i = 0; i < maskedworkers.length; i++) { maskedworkers[i].setPspriteScale(scale); + } } @Override public void setPspriteIscale(int scale) { - for (int i = 0; i < maskedworkers.length; i++) + for (int i = 0; i < maskedworkers.length; i++) { maskedworkers[i].setPspriteIscale(scale); + } } @Override public void setDetail(int detailshift) { - for (int i = 0; i < maskedworkers.length; i++) + for (int i = 0; i < maskedworkers.length; i++) { maskedworkers[i].setDetail(detailshift); - + } + } @Override public void cacheSpriteManager(ISpriteManager SM) { - for (int i = 0; i < maskedworkers.length; i++) + for (int i = 0; i < maskedworkers.length; i++) { maskedworkers[i].cacheSpriteManager(SM); - + } + } } diff --git a/src/rr/parallel/RWI.java b/src/rr/parallel/RWI.java index dea03398..faf320f8 100644 --- a/src/rr/parallel/RWI.java +++ b/src/rr/parallel/RWI.java @@ -2,13 +2,17 @@ import rr.drawfuns.ColVars; -public interface RWI { - public interface Init{ - RenderWallExecutor[] InitRWIExecutors(int num,ColVars[] RWI); - } - - public interface Get{ - ColVars[] getRWI(); - void setExecutors(RenderWallExecutor[] RWIExec); - } +public interface RWI { + + public interface Init { + + RenderWallExecutor[] InitRWIExecutors(int num, ColVars[] RWI); + } + + public interface Get { + + ColVars[] getRWI(); + + void setExecutors(RenderWallExecutor[] RWIExec); + } } diff --git a/src/rr/parallel/RenderMaskedExecutor.java b/src/rr/parallel/RenderMaskedExecutor.java index 70d28364..77e1d921 100644 --- a/src/rr/parallel/RenderMaskedExecutor.java +++ b/src/rr/parallel/RenderMaskedExecutor.java @@ -3,6 +3,9 @@ import i.IDoomSystem; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import rr.IDetailAware; import rr.drawfuns.ColVars; import rr.drawfuns.DcFlags; @@ -18,32 +21,33 @@ /** * This is what actual executes the RenderWallInstruction. Essentially it's a * self-contained column rendering function. - * + * * @author velktron */ +public abstract class RenderMaskedExecutor + implements Runnable, IDetailAware { -public abstract class RenderMaskedExecutor - implements Runnable,IDetailAware { + private static final Logger LOGGER = Loggers.getLogger(RenderMaskedExecutor.class.getName()); protected CyclicBarrier barrier; - protected ColVars[] RMI; - + protected ColVars[] RMI; + protected int rmiend; - protected boolean lowdetail=false; - + protected boolean lowdetail = false; + protected int start, end; - protected DoomColumnFunction colfunchi, colfunclow; - protected DoomColumnFunction fuzzfunchi, fuzzfunclow; - protected DoomColumnFunction transfunchi, transfunclow; - - protected DoomColumnFunction colfunc; + protected DoomColumnFunction colfunchi, colfunclow; + protected DoomColumnFunction fuzzfunchi, fuzzfunclow; + protected DoomColumnFunction transfunchi, transfunclow; + + protected DoomColumnFunction colfunc; - public RenderMaskedExecutor(int SCREENWIDTH, int SCREENHEIGHT, - ColVars[] RMI, CyclicBarrier barrier - ) { + public RenderMaskedExecutor(int SCREENWIDTH, int SCREENHEIGHT, + ColVars[] RMI, CyclicBarrier barrier + ) { this.RMI = RMI; this.barrier = barrier; this.SCREENWIDTH = SCREENWIDTH; @@ -56,71 +60,66 @@ public void setRange(int start, int end) { } public void setDetail(int detailshift) { - if (detailshift == 0) - lowdetail=false; - else - lowdetail=true; + lowdetail = detailshift != 0; } public void run() { // System.out.println("Wall executor from "+start +" to "+ end); - int dc_flags=0; - + int dc_flags = 0; + // Check out ALL valid RMIs, but only draw those on YOUR side of the screen. for (int i = 0; i < rmiend; i++) { - - if (RMI[i].dc_x>=start && RMI[i].dc_x<=end){ - // Change function type according to flags. - // No flag change means reusing the last used type - dc_flags=RMI[i].dc_flags; + + if (RMI[i].dc_x >= start && RMI[i].dc_x <= end) { + // Change function type according to flags. + // No flag change means reusing the last used type + dc_flags = RMI[i].dc_flags; //System.err.printf("Flags transition %d\n",dc_flags); - if (lowdetail){ - if ((dc_flags&DcFlags.FUZZY)!=0) - colfunc=fuzzfunclow; - else - if ((dc_flags&DcFlags.TRANSLATED)!=0) - colfunc=transfunclow; - else - colfunc=colfunclow; + if (lowdetail) { + if ((dc_flags & DcFlags.FUZZY) != 0) { + colfunc = fuzzfunclow; + } else if ((dc_flags & DcFlags.TRANSLATED) != 0) { + colfunc = transfunclow; + } else { + colfunc = colfunclow; + } } else { - if ((dc_flags&DcFlags.FUZZY)!=0) - colfunc=fuzzfunchi; - else - if ((dc_flags&DcFlags.TRANSLATED)!=0) - colfunc=transfunchi; - else - colfunc=colfunchi; + if ((dc_flags & DcFlags.FUZZY) != 0) { + colfunc = fuzzfunchi; + } else if ((dc_flags & DcFlags.TRANSLATED) != 0) { + colfunc = transfunchi; + } else { + colfunc = colfunchi; } - - // No need to set shared DCvars, because it's passed with the arg. - colfunc.invoke(RMI[i]); + } + + // No need to set shared DCvars, because it's passed with the arg. + colfunc.invoke(RMI[i]); } } try { barrier.await(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (BrokenBarrierException e) { - e.printStackTrace(); + } catch (InterruptedException | BrokenBarrierException e) { + LOGGER.log(Level.SEVERE, "RenderMaskedExecutor run failure", e); } } - - public void setRMIEnd(int rmiend){ - this.rmiend=rmiend; - } - public void updateRMI(ColVars[] RMI) { + public void setRMIEnd(int rmiend) { + this.rmiend = rmiend; + } + + public void updateRMI(ColVars[] RMI) { this.RMI = RMI; } /////////////// VIDEO SCALE STUFF////////////////////// - protected final int SCREENWIDTH; protected final int SCREENHEIGHT; + /* * protected IVideoScale vs; * @Override public void setVideoScale(IVideoScale vs) { this.vs=vs; } @@ -128,75 +127,73 @@ public void updateRMI(ColVars[] RMI) { * this.SCREENHEIGHT=vs.getScreenHeight(); * this.SCREENWIDTH=vs.getScreenWidth(); } */ - - public static final class HiColor extends RenderMaskedExecutor{ + public static final class HiColor extends RenderMaskedExecutor { public HiColor(int SCREENWIDTH, int SCREENHEIGHT, int[] columnofs, int[] ylookup, short[] screen, ColVars[] RMI, - CyclicBarrier barrier,IDoomSystem I, BlurryTable BLURRY_MAP) { - super(SCREENWIDTH, SCREENHEIGHT,RMI, barrier); - + CyclicBarrier barrier, IDoomSystem I, BlurryTable BLURRY_MAP) { + super(SCREENWIDTH, SCREENHEIGHT, RMI, barrier); + // Regular masked columns - this.colfunc = new R_DrawColumnBoom.HiColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); - this.colfunclow = new R_DrawColumnBoomLow.HiColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); - + this.colfunc = new R_DrawColumnBoom.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); + this.colfunclow = new R_DrawColumnBoomLow.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); + // Fuzzy columns - this.fuzzfunchi= new R_DrawFuzzColumn.HiColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I,BLURRY_MAP); - this.fuzzfunclow =new R_DrawFuzzColumnLow.HiColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I,BLURRY_MAP); + this.fuzzfunchi = new R_DrawFuzzColumn.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I, BLURRY_MAP); + this.fuzzfunclow = new R_DrawFuzzColumnLow.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I, BLURRY_MAP); // Translated columns - this.transfunchi=new R_DrawTranslatedColumn.HiColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); - this.transfunclow= new R_DrawTranslatedColumnLow.HiColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); + this.transfunchi = new R_DrawTranslatedColumn.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); + this.transfunclow = new R_DrawTranslatedColumnLow.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); } - + } - - public static final class Indexed extends RenderMaskedExecutor{ + + public static final class Indexed extends RenderMaskedExecutor { public Indexed(int SCREENWIDTH, int SCREENHEIGHT, int[] columnofs, int[] ylookup, byte[] screen, ColVars[] RMI, - CyclicBarrier barrier,IDoomSystem I, BlurryTable BLURRY_MAP) { - super(SCREENWIDTH, SCREENHEIGHT,RMI, barrier); - + CyclicBarrier barrier, IDoomSystem I, BlurryTable BLURRY_MAP) { + super(SCREENWIDTH, SCREENHEIGHT, RMI, barrier); + // Regular masked columns - this.colfunc = new R_DrawColumnBoom.Indexed(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); - this.colfunclow = new R_DrawColumnBoomLow.Indexed(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); - + this.colfunc = new R_DrawColumnBoom.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); + this.colfunclow = new R_DrawColumnBoomLow.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); + // Fuzzy columns - this.fuzzfunchi= new R_DrawFuzzColumn.Indexed(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I,BLURRY_MAP); - this.fuzzfunclow =new R_DrawFuzzColumnLow.Indexed(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I,BLURRY_MAP); + this.fuzzfunchi = new R_DrawFuzzColumn.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I, BLURRY_MAP); + this.fuzzfunclow = new R_DrawFuzzColumnLow.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I, BLURRY_MAP); // Translated columns - this.transfunchi=new R_DrawTranslatedColumn.Indexed(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); - this.transfunclow= new R_DrawTranslatedColumnLow.Indexed(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); + this.transfunchi = new R_DrawTranslatedColumn.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); + this.transfunclow = new R_DrawTranslatedColumnLow.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); } - + } - - public static final class TrueColor extends RenderMaskedExecutor{ + + public static final class TrueColor extends RenderMaskedExecutor { public TrueColor(int SCREENWIDTH, int SCREENHEIGHT, int[] columnofs, int[] ylookup, int[] screen, ColVars[] RMI, - CyclicBarrier barrier,IDoomSystem I, BlurryTable BLURRY_MAP) { - super(SCREENWIDTH, SCREENHEIGHT,RMI, barrier); - + CyclicBarrier barrier, IDoomSystem I, BlurryTable BLURRY_MAP) { + super(SCREENWIDTH, SCREENHEIGHT, RMI, barrier); + // Regular masked columns - this.colfunc = new R_DrawColumnBoom.TrueColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); - this.colfunclow = new R_DrawColumnBoomLow.TrueColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); - + this.colfunc = new R_DrawColumnBoom.TrueColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); + this.colfunclow = new R_DrawColumnBoomLow.TrueColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); + // Fuzzy columns - this.fuzzfunchi= new R_DrawFuzzColumn.TrueColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I,BLURRY_MAP); - this.fuzzfunclow =new R_DrawFuzzColumnLow.TrueColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I,BLURRY_MAP); + this.fuzzfunchi = new R_DrawFuzzColumn.TrueColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I, BLURRY_MAP); + this.fuzzfunclow = new R_DrawFuzzColumnLow.TrueColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I, BLURRY_MAP); // Translated columns - this.transfunchi=new R_DrawTranslatedColumn.TrueColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); - this.transfunclow= new R_DrawTranslatedColumnLow.TrueColor(SCREENWIDTH,SCREENHEIGHT,ylookup,columnofs,null,screen,I); - + this.transfunchi = new R_DrawTranslatedColumn.TrueColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); + this.transfunclow = new R_DrawTranslatedColumnLow.TrueColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, I); } - + } - + } diff --git a/src/rr/parallel/RenderSegExecutor.java b/src/rr/parallel/RenderSegExecutor.java index a635626a..62b916a5 100644 --- a/src/rr/parallel/RenderSegExecutor.java +++ b/src/rr/parallel/RenderSegExecutor.java @@ -5,15 +5,19 @@ import doom.DoomMain; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; -import static m.fixed_t.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import static m.fixed_t.FRACBITS; +import static m.fixed_t.FixedMul; +import mochadoom.Loggers; import rr.IDetailAware; -import v.tables.LightsAndColors; import rr.TextureManager; import rr.drawfuns.ColVars; import rr.drawfuns.DoomColumnFunction; import rr.drawfuns.R_DrawColumnBoomOpt; import rr.drawfuns.R_DrawColumnBoomOptLow; import rr.visplane_t; +import v.tables.LightsAndColors; /** This is what actual executes the RenderSegInstructions. * * @@ -39,314 +43,301 @@ * @author velktron * */ +public abstract class RenderSegExecutor implements Runnable, IDetailAware { -public abstract class RenderSegExecutor implements Runnable, IDetailAware { + private static final Logger LOGGER = Loggers.getLogger(RenderSegExecutor.class.getName()); - // This needs to be set by the partitioner. - protected int rw_start, rw_end,rsiend; - // These need to be set on creation, and are unchangeable. + // This needs to be set by the partitioner. + protected int rw_start, rw_end, rsiend; + // These need to be set on creation, and are unchangeable. protected final LightsAndColors colormaps; - protected final TextureManager TexMan; - protected final CyclicBarrier barrier; - protected RenderSegInstruction[] RSI; - protected final long[] xtoviewangle; - protected final short[] ceilingclip, floorclip; - - // Each thread should do its own ceiling/floor blanking - protected final short[] BLANKFLOORCLIP; - protected final short[] BLANKCEILINGCLIP; - - protected static final int HEIGHTBITS = 12; - protected static final int HEIGHTUNIT = (1< colfunchi,colfunclow; - protected DoomColumnFunction colfunc; - protected ColVars dcvars; + protected final TextureManager TexMan; + protected final CyclicBarrier barrier; + protected RenderSegInstruction[] RSI; + protected final long[] xtoviewangle; + protected final short[] ceilingclip, floorclip; + + // Each thread should do its own ceiling/floor blanking + protected final short[] BLANKFLOORCLIP; + protected final short[] BLANKCEILINGCLIP; + + protected static final int HEIGHTBITS = 12; + protected static final int HEIGHTUNIT = (1 << HEIGHTBITS); + protected final int id; + + protected DoomColumnFunction colfunchi, colfunclow; + protected DoomColumnFunction colfunc; + protected ColVars dcvars; protected final DoomMain DOOM; - - public RenderSegExecutor(DoomMain DOOM,int id,V screen, - TextureManager texman, - RenderSegInstruction[] RSI, - short[] BLANKCEILINGCLIP, - short[] BLANKFLOORCLIP, - short[] ceilingclip, - short[] floorclip, - int[] columnofs, - long[] xtoviewangle, - int[] ylookup, - visplane_t[] visplanes, - CyclicBarrier barrier, - LightsAndColors colormaps){ - this.id=id; - this.TexMan=texman; - this.RSI=RSI; - this.barrier=barrier; - this.ceilingclip=ceilingclip; - this.floorclip=floorclip; - this.xtoviewangle=xtoviewangle; - this.BLANKCEILINGCLIP=BLANKCEILINGCLIP; - this.BLANKFLOORCLIP=BLANKFLOORCLIP; - this.colormaps=colormaps; - this.DOOM=DOOM; - } - - protected final void ProcessRSI(RenderSegInstruction rsi, int startx,int endx,boolean contained){ - int angle; // angle_t - int index; - int yl; // low - int yh; // hight - int mid; - int pixlow,pixhigh,pixhighstep,pixlowstep; - int rw_scale,topfrac,bottomfrac,bottomstep; - // These are going to be modified A LOT, so we cache them here. - pixhighstep=rsi.pixhighstep; - pixlowstep=rsi.pixlowstep; - bottomstep=rsi.bottomstep; - // We must re-scale it. - int rw_scalestep= rsi.rw_scalestep; - int topstep=rsi.topstep; - int texturecolumn=0; // fixed_t - final int bias; - // Well is entirely contained in our screen zone - // (or the very least it starts in it). - if (contained) bias=0; - // We are continuing a wall that started in another - // screen zone. - else bias=(startx-rsi.rw_x); - // PROBLEM: these must be pre-biased when multithreading. - rw_scale=rsi.rw_scale+bias*rw_scalestep; - topfrac = rsi.topfrac+bias*topstep; - bottomfrac = rsi.bottomfrac+ bias*bottomstep; - pixlow=rsi.pixlow+bias*pixlowstep; - pixhigh=rsi.pixhigh+bias*pixhighstep; - - { - - for ( int rw_x=startx; rw_x < endx ; rw_x++) - { - // mark floor / ceiling areas - yl = (topfrac+HEIGHTUNIT-1)>>HEIGHTBITS; - - // no space above wall? - if (yl < ceilingclip[rw_x]+1) - yl = ceilingclip[rw_x]+1; - - yh = bottomfrac>>HEIGHTBITS; - - if (yh >= floorclip[rw_x]) - yh = floorclip[rw_x]-1; - - // System.out.printf("Thread: rw %d yl %d yh %d\n",rw_x,yl,yh); - - // A particular seg has been identified as a floor marker. - - - // texturecolumn and lighting are independent of wall tiers - if (rsi.segtextured) - { - // calculate texture offset - - - // CAREFUL: a VERY anomalous point in the code. Their sum is supposed - // to give an angle not exceeding 45 degrees (or 0x0FFF after shifting). - // If added with pure unsigned rules, this doesn't hold anymore, - // not even if accounting for overflow. - angle = Tables.toBAMIndex(rsi.rw_centerangle + (int)xtoviewangle[rw_x]); - //angle = (int) (((rw_centerangle + xtoviewangle[rw_x])&BITS31)>>>ANGLETOFINESHIFT); - //angle&=0x1FFF; - - // FIXME: We are accessing finetangent here, the code seems pretty confident - // in that angle won't exceed 4K no matter what. But xtoviewangle - // alone can yield 8K when shifted. - // This usually only overflows if we idclip and look at certain directions - // (probably angles get fucked up), however it seems rare enough to just - // "swallow" the exception. You can eliminate it by anding with 0x1FFF - // if you're so inclined. - - texturecolumn = rsi.rw_offset-FixedMul(finetangent[angle],rsi.rw_distance); - texturecolumn >>= FRACBITS; - // calculate lighting - index = rw_scale>>colormaps.lightScaleShift(); - - - if (index >= colormaps.maxLightScale() ) - index = colormaps.maxLightScale()-1; - - dcvars.dc_colormap = rsi.walllights[index]; - dcvars.dc_x = rw_x; - dcvars.dc_iscale = (int) (0xffffffffL / rw_scale); - } - - // draw the wall tiers - if (rsi.midtexture!=0) - { - // single sided line - dcvars.dc_yl = yl; - dcvars.dc_yh = yh; - dcvars.dc_texheight = TexMan.getTextureheight(rsi.midtexture)>>FRACBITS; // killough - dcvars.dc_texturemid = rsi.rw_midtexturemid; - dcvars.dc_source = TexMan.GetCachedColumn(rsi.midtexture,texturecolumn); - dcvars.dc_source_ofs=0; - colfunc.invoke(); - ceilingclip[rw_x] = (short) rsi.viewheight; - floorclip[rw_x] = -1; - } - else - { - // two sided line - if (rsi.toptexture!=0) - { - // top wall - mid = pixhigh>>HEIGHTBITS; - pixhigh += pixhighstep; - - if (mid >= floorclip[rw_x]) - mid = floorclip[rw_x]-1; - - if (mid >= yl) - { - dcvars.dc_yl = yl; - dcvars.dc_yh = mid; - dcvars.dc_texturemid = rsi.rw_toptexturemid; - dcvars.dc_texheight=TexMan.getTextureheight(rsi.toptexture)>>FRACBITS; - dcvars.dc_source = TexMan.GetCachedColumn(rsi.toptexture,texturecolumn); - //dc_source_ofs=0; - colfunc.invoke(); - ceilingclip[rw_x] = (short) mid; - } - else - ceilingclip[rw_x] = (short) (yl-1); - } // if toptexture - else - { - // no top wall - if (rsi.markceiling) - ceilingclip[rw_x] = (short) (yl-1); - } - - if (rsi.bottomtexture!=0) - { - // bottom wall - mid = (pixlow+HEIGHTUNIT-1)>>HEIGHTBITS; - pixlow += pixlowstep; - - // no space above wall? - if (mid <= ceilingclip[rw_x]) - mid = ceilingclip[rw_x]+1; - - if (mid <= yh) - { - dcvars.dc_yl = mid; - dcvars.dc_yh = yh; - dcvars.dc_texturemid = rsi.rw_bottomtexturemid; - dcvars.dc_texheight=TexMan.getTextureheight(rsi.bottomtexture)>>FRACBITS; - dcvars.dc_source = TexMan.GetCachedColumn(rsi.bottomtexture,texturecolumn); - // dc_source_ofs=0; - colfunc.invoke(); - floorclip[rw_x] = (short) mid; - } - else - floorclip[rw_x] = (short) (yh+1); - - } // end-bottomtexture - else - { - // no bottom wall - if (rsi.markfloor) - floorclip[rw_x] = (short) (yh+1); - } - - } // end-else (two-sided line) - rw_scale += rw_scalestep; - topfrac += topstep; - bottomfrac += bottomstep; - } // end-rw - } // end-block - } - - @Override + + public RenderSegExecutor(DoomMain DOOM, int id, V screen, + TextureManager texman, + RenderSegInstruction[] RSI, + short[] BLANKCEILINGCLIP, + short[] BLANKFLOORCLIP, + short[] ceilingclip, + short[] floorclip, + int[] columnofs, + long[] xtoviewangle, + int[] ylookup, + visplane_t[] visplanes, + CyclicBarrier barrier, + LightsAndColors colormaps) { + this.id = id; + this.TexMan = texman; + this.RSI = RSI; + this.barrier = barrier; + this.ceilingclip = ceilingclip; + this.floorclip = floorclip; + this.xtoviewangle = xtoviewangle; + this.BLANKCEILINGCLIP = BLANKCEILINGCLIP; + this.BLANKFLOORCLIP = BLANKFLOORCLIP; + this.colormaps = colormaps; + this.DOOM = DOOM; + } + + protected final void ProcessRSI(RenderSegInstruction rsi, int startx, int endx, boolean contained) { + int angle; // angle_t + int index; + int yl; // low + int yh; // hight + int mid; + int pixlow, pixhigh, pixhighstep, pixlowstep; + int rw_scale, topfrac, bottomfrac, bottomstep; + // These are going to be modified A LOT, so we cache them here. + pixhighstep = rsi.pixhighstep; + pixlowstep = rsi.pixlowstep; + bottomstep = rsi.bottomstep; + // We must re-scale it. + int rw_scalestep = rsi.rw_scalestep; + int topstep = rsi.topstep; + int texturecolumn = 0; // fixed_t + final int bias; + // Well is entirely contained in our screen zone + // (or the very least it starts in it). + if (contained) { + bias = 0; + } // We are continuing a wall that started in another + // screen zone. + else { + bias = (startx - rsi.rw_x); + } + // PROBLEM: these must be pre-biased when multithreading. + rw_scale = rsi.rw_scale + bias * rw_scalestep; + topfrac = rsi.topfrac + bias * topstep; + bottomfrac = rsi.bottomfrac + bias * bottomstep; + pixlow = rsi.pixlow + bias * pixlowstep; + pixhigh = rsi.pixhigh + bias * pixhighstep; + + { + + for (int rw_x = startx; rw_x < endx; rw_x++) { + // mark floor / ceiling areas + yl = (topfrac + HEIGHTUNIT - 1) >> HEIGHTBITS; + + // no space above wall? + if (yl < ceilingclip[rw_x] + 1) { + yl = ceilingclip[rw_x] + 1; + } + + yh = bottomfrac >> HEIGHTBITS; + + if (yh >= floorclip[rw_x]) { + yh = floorclip[rw_x] - 1; + } + + // System.out.printf("Thread: rw %d yl %d yh %d\n",rw_x,yl,yh); + // A particular seg has been identified as a floor marker. + // texturecolumn and lighting are independent of wall tiers + if (rsi.segtextured) { + // calculate texture offset + + // CAREFUL: a VERY anomalous point in the code. Their sum is supposed + // to give an angle not exceeding 45 degrees (or 0x0FFF after shifting). + // If added with pure unsigned rules, this doesn't hold anymore, + // not even if accounting for overflow. + angle = Tables.toBAMIndex(rsi.rw_centerangle + (int) xtoviewangle[rw_x]); + //angle = (int) (((rw_centerangle + xtoviewangle[rw_x])&BITS31)>>>ANGLETOFINESHIFT); + //angle&=0x1FFF; + + // FIXME: We are accessing finetangent here, the code seems pretty confident + // in that angle won't exceed 4K no matter what. But xtoviewangle + // alone can yield 8K when shifted. + // This usually only overflows if we idclip and look at certain directions + // (probably angles get fucked up), however it seems rare enough to just + // "swallow" the exception. You can eliminate it by anding with 0x1FFF + // if you're so inclined. + texturecolumn = rsi.rw_offset - FixedMul(finetangent[angle], rsi.rw_distance); + texturecolumn >>= FRACBITS; + // calculate lighting + index = rw_scale >> colormaps.lightScaleShift(); + + if (index >= colormaps.maxLightScale()) { + index = colormaps.maxLightScale() - 1; + } + + dcvars.dc_colormap = rsi.walllights[index]; + dcvars.dc_x = rw_x; + dcvars.dc_iscale = (int) (0xffffffffL / rw_scale); + } + + // draw the wall tiers + if (rsi.midtexture != 0) { + // single sided line + dcvars.dc_yl = yl; + dcvars.dc_yh = yh; + dcvars.dc_texheight = TexMan.getTextureheight(rsi.midtexture) >> FRACBITS; // killough + dcvars.dc_texturemid = rsi.rw_midtexturemid; + dcvars.dc_source = TexMan.GetCachedColumn(rsi.midtexture, texturecolumn); + dcvars.dc_source_ofs = 0; + colfunc.invoke(); + ceilingclip[rw_x] = (short) rsi.viewheight; + floorclip[rw_x] = -1; + } else { + // two sided line + if (rsi.toptexture != 0) { + // top wall + mid = pixhigh >> HEIGHTBITS; + pixhigh += pixhighstep; + + if (mid >= floorclip[rw_x]) { + mid = floorclip[rw_x] - 1; + } + + if (mid >= yl) { + dcvars.dc_yl = yl; + dcvars.dc_yh = mid; + dcvars.dc_texturemid = rsi.rw_toptexturemid; + dcvars.dc_texheight = TexMan.getTextureheight(rsi.toptexture) >> FRACBITS; + dcvars.dc_source = TexMan.GetCachedColumn(rsi.toptexture, texturecolumn); + //dc_source_ofs=0; + colfunc.invoke(); + ceilingclip[rw_x] = (short) mid; + } else { + ceilingclip[rw_x] = (short) (yl - 1); + } + } // if toptexture + else { + // no top wall + if (rsi.markceiling) { + ceilingclip[rw_x] = (short) (yl - 1); + } + } + + if (rsi.bottomtexture != 0) { + // bottom wall + mid = (pixlow + HEIGHTUNIT - 1) >> HEIGHTBITS; + pixlow += pixlowstep; + + // no space above wall? + if (mid <= ceilingclip[rw_x]) { + mid = ceilingclip[rw_x] + 1; + } + + if (mid <= yh) { + dcvars.dc_yl = mid; + dcvars.dc_yh = yh; + dcvars.dc_texturemid = rsi.rw_bottomtexturemid; + dcvars.dc_texheight = TexMan.getTextureheight(rsi.bottomtexture) >> FRACBITS; + dcvars.dc_source = TexMan.GetCachedColumn(rsi.bottomtexture, texturecolumn); + // dc_source_ofs=0; + colfunc.invoke(); + floorclip[rw_x] = (short) mid; + } else { + floorclip[rw_x] = (short) (yh + 1); + } + + } // end-bottomtexture + else { + // no bottom wall + if (rsi.markfloor) { + floorclip[rw_x] = (short) (yh + 1); + } + } + + } // end-else (two-sided line) + rw_scale += rw_scalestep; + topfrac += topstep; + bottomfrac += bottomstep; + } // end-rw + } // end-block + } + + @Override public void setDetail(int detailshift) { - if (detailshift == 0) + if (detailshift == 0) { colfunc = colfunchi; - else + } else { colfunc = colfunclow; + } + } + + /** Only called once per screen width change */ + public void setScreenRange(int rwstart, int rwend) { + this.rw_end = rwend; + this.rw_start = rwstart; + } + + /** How many instructions TOTAL are there to wade through. + * Not all will be executed on one thread, except in some rare + * circumstances. + * + * @param rsiend + */ + public void setRSIEnd(int rsiend) { + this.rsiend = rsiend; + } + + public void run() { + + RenderSegInstruction rsi; + + // Each worker blanks its own portion of the floor/ceiling clippers. + System.arraycopy(BLANKFLOORCLIP, rw_start, floorclip, rw_start, rw_end - rw_start); + System.arraycopy(BLANKCEILINGCLIP, rw_start, ceilingclip, rw_start, rw_end - rw_start); + + // For each "SegDraw" instruction... + for (int i = 0; i < rsiend; i++) { + rsi = RSI[i]; + dcvars.centery = RSI[i].centery; + int startx, endx; + // Does a wall actually start in our screen zone? + // If yes, we need no bias, since it was meant for it. + // If the wall started BEFORE our zone, then we + // will need to add a bias to it (see ProcessRSI). + // If its entirely non-contained, ProcessRSI won't be + // called anyway, so we don't need to check for the end. + + boolean contained = (rsi.rw_x >= rw_start); + // Keep to your part of the screen. It's possible that several + // threads will process the same RSI, but different parts of it. + + // Trim stuff that starts before our rw_start position. + startx = Math.max(rsi.rw_x, rw_start); + // Similarly, trim stuff after our rw_end position. + endx = Math.min(rsi.rw_stopx, rw_end); + // Is there anything to actually draw? + if ((endx - startx) > 0) { + ProcessRSI(rsi, startx, endx, contained); + } + } // end-instruction + + try { + barrier.await(); + } catch (InterruptedException | BrokenBarrierException e) { + LOGGER.log(Level.SEVERE, "RenderSegExecutor run failure", e); + } + // TODO Auto-generated catch block + } - - /** Only called once per screen width change */ - public void setScreenRange(int rwstart, int rwend){ - this.rw_end=rwend; - this.rw_start=rwstart; - } - - - /** How many instructions TOTAL are there to wade through. - * Not all will be executed on one thread, except in some rare - * circumstances. - * - * @param rsiend - */ - public void setRSIEnd(int rsiend){ - this.rsiend=rsiend; - } - - public void run() - { - - RenderSegInstruction rsi; - - // Each worker blanks its own portion of the floor/ceiling clippers. - System.arraycopy(BLANKFLOORCLIP,rw_start,floorclip, rw_start,rw_end-rw_start); - System.arraycopy(BLANKCEILINGCLIP,rw_start,ceilingclip, rw_start,rw_end-rw_start); - - // For each "SegDraw" instruction... - for (int i=0;i=rw_start); - // Keep to your part of the screen. It's possible that several - // threads will process the same RSI, but different parts of it. - - // Trim stuff that starts before our rw_start position. - startx=Math.max(rsi.rw_x,rw_start); - // Similarly, trim stuff after our rw_end position. - endx=Math.min(rsi.rw_stopx,rw_end); - // Is there anything to actually draw? - if ((endx-startx)>0) { - ProcessRSI(rsi,startx,endx,contained); - } - } // end-instruction - - try { - barrier.await(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (BrokenBarrierException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - //protected abstract void ProcessRSI(RenderSegInstruction rsi, int startx,int endx,boolean contained); - - - - ////////////////////////////VIDEO SCALE STUFF //////////////////////////////// - public void updateRSI(RenderSegInstruction[] rsi) { - this.RSI=rsi; - } - - public static final class TrueColor extends RenderSegExecutor{ + + //protected abstract void ProcessRSI(RenderSegInstruction rsi, int startx,int endx,boolean contained); + ////////////////////////////VIDEO SCALE STUFF //////////////////////////////// + public void updateRSI(RenderSegInstruction[] rsi) { + this.RSI = rsi; + } + + public static final class TrueColor extends RenderSegExecutor { public TrueColor(DoomMain DOOM, int id, int[] screen, TextureManager texman, @@ -357,13 +348,13 @@ public TrueColor(DoomMain DOOM, int id, super(DOOM, id, screen, texman, RSI, BLANKCEILINGCLIP, BLANKFLOORCLIP, ceilingclip, floorclip, columnofs, xtoviewangle, ylookup, visplanes, barrier, colormaps); - dcvars=new ColVars<>(); - colfunc=colfunchi=new R_DrawColumnBoomOpt.TrueColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(),ylookup,columnofs,dcvars,screen,null ); - colfunclow=new R_DrawColumnBoomOptLow.TrueColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(),ylookup,columnofs,dcvars,screen,null ); + dcvars = new ColVars<>(); + colfunc = colfunchi = new R_DrawColumnBoomOpt.TrueColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, dcvars, screen, null); + colfunclow = new R_DrawColumnBoomOptLow.TrueColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, dcvars, screen, null); } - } - - public static final class HiColor extends RenderSegExecutor{ + } + + public static final class HiColor extends RenderSegExecutor { public HiColor(DoomMain DOOM, int id, short[] screen, TextureManager texman, @@ -374,13 +365,13 @@ public HiColor(DoomMain DOOM, int id, super(DOOM, id, screen, texman, RSI, BLANKCEILINGCLIP, BLANKFLOORCLIP, ceilingclip, floorclip, columnofs, xtoviewangle, ylookup, visplanes, barrier, colormaps); - dcvars=new ColVars<>(); - colfunc=colfunchi=new R_DrawColumnBoomOpt.HiColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(),ylookup,columnofs,dcvars,screen,null ); - colfunclow=new R_DrawColumnBoomOptLow.HiColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(),ylookup,columnofs,dcvars,screen,null ); + dcvars = new ColVars<>(); + colfunc = colfunchi = new R_DrawColumnBoomOpt.HiColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, dcvars, screen, null); + colfunclow = new R_DrawColumnBoomOptLow.HiColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, dcvars, screen, null); } - } - - public static final class Indexed extends RenderSegExecutor{ + } + + public static final class Indexed extends RenderSegExecutor { public Indexed(DoomMain DOOM, int id, byte[] screen, TextureManager texman, @@ -391,12 +382,12 @@ public Indexed(DoomMain DOOM, int id, super(DOOM, id, screen, texman, RSI, BLANKCEILINGCLIP, BLANKFLOORCLIP, ceilingclip, floorclip, columnofs, xtoviewangle, ylookup, visplanes, barrier, colormaps); - dcvars=new ColVars<>(); - colfunc=colfunchi=new R_DrawColumnBoomOpt.Indexed(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(),ylookup,columnofs,dcvars,screen,null ); - colfunclow=new R_DrawColumnBoomOptLow.Indexed(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(),ylookup,columnofs,dcvars,screen,null ); + dcvars = new ColVars<>(); + colfunc = colfunchi = new R_DrawColumnBoomOpt.Indexed(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, dcvars, screen, null); + colfunclow = new R_DrawColumnBoomOptLow.Indexed(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, dcvars, screen, null); } } - + } // $Log: RenderSegExecutor.java,v $ @@ -450,4 +441,4 @@ public Indexed(DoomMain DOOM, int id, // // Revision 1.3 2011/06/07 00:11:11 velktron // Fixed alternate parallel renderer (seg based). No longer deprecated. -// \ No newline at end of file +// diff --git a/src/rr/parallel/RenderSegInstruction.java b/src/rr/parallel/RenderSegInstruction.java index 24e9e387..f12034c6 100644 --- a/src/rr/parallel/RenderSegInstruction.java +++ b/src/rr/parallel/RenderSegInstruction.java @@ -5,19 +5,19 @@ * versions. * */ +public class RenderSegInstruction { -public class RenderSegInstruction { - public int rw_x,rw_stopx; - public int toptexture,midtexture,bottomtexture; - public int pixhigh,pixlow,pixhighstep,pixlowstep, - topfrac, topstep,bottomfrac, bottomstep; - public boolean segtextured,markfloor,markceiling; - public long rw_centerangle; // angle_t - /** fixed_t */ - public int rw_offset,rw_distance,rw_scale, - rw_scalestep,rw_midtexturemid,rw_toptexturemid,rw_bottomtexturemid; - public int viewheight; - V[] walllights; - public int centery; + public int rw_x, rw_stopx; + public int toptexture, midtexture, bottomtexture; + public int pixhigh, pixlow, pixhighstep, pixlowstep, + topfrac, topstep, bottomfrac, bottomstep; + public boolean segtextured, markfloor, markceiling; + public long rw_centerangle; // angle_t + /** fixed_t */ + public int rw_offset, rw_distance, rw_scale, + rw_scalestep, rw_midtexturemid, rw_toptexturemid, rw_bottomtexturemid; + public int viewheight; + V[] walllights; + public int centery; } diff --git a/src/rr/parallel/RenderWallExecutor.java b/src/rr/parallel/RenderWallExecutor.java index e0bd6a72..cd896270 100644 --- a/src/rr/parallel/RenderWallExecutor.java +++ b/src/rr/parallel/RenderWallExecutor.java @@ -2,11 +2,12 @@ import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; - +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import rr.IDetailAware; import rr.drawfuns.ColVars; import rr.drawfuns.DoomColumnFunction; - import rr.drawfuns.R_DrawColumnBoomOpt; import rr.drawfuns.R_DrawColumnBoomOptLow; @@ -16,23 +17,24 @@ * * @author admin */ +public class RenderWallExecutor + implements Runnable, IDetailAware { -public class RenderWallExecutor - implements Runnable,IDetailAware { + private static final Logger LOGGER = Loggers.getLogger(RenderWallExecutor.class.getName()); protected CyclicBarrier barrier; - protected ColVars[] RWI; + protected ColVars[] RWI; protected int start, end; - protected DoomColumnFunction colfunchi, colfunclow; + protected DoomColumnFunction colfunchi, colfunclow; - protected DoomColumnFunction colfunc; + protected DoomColumnFunction colfunc; public RenderWallExecutor(int SCREENWIDTH, int SCREENHEIGHT, int[] columnofs, int[] ylookup, V screen, - ColVars[] RWI, CyclicBarrier barrier) { + ColVars[] RWI, CyclicBarrier barrier) { this.RWI = RWI; this.barrier = barrier; this.SCREENWIDTH = SCREENWIDTH; @@ -46,39 +48,37 @@ public void setRange(int start, int end) { } public void setDetail(int detailshift) { - if (detailshift == 0) + if (detailshift == 0) { colfunc = colfunchi; - else + } else { colfunc = colfunclow; + } } public void run() { // System.out.println("Wall executor from "+start +" to "+ end); - for (int i = start; i < end; i++) { colfunc.invoke(RWI[i]); } try { barrier.await(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (BrokenBarrierException e) { - e.printStackTrace(); + } catch (InterruptedException | BrokenBarrierException e) { + LOGGER.log(Level.SEVERE, "RenderWallExecutor run failure", e); } } - public void updateRWI(ColVars[] RWI) { + public void updateRWI(ColVars[] RWI) { this.RWI = RWI; } /////////////// VIDEO SCALE STUFF////////////////////// - protected final int SCREENWIDTH; protected final int SCREENHEIGHT; + /* * protected IVideoScale vs; * @Override public void setVideoScale(IVideoScale vs) { this.vs=vs; } @@ -86,56 +86,55 @@ public void updateRWI(ColVars[] RWI) { * this.SCREENHEIGHT=vs.getScreenHeight(); * this.SCREENWIDTH=vs.getScreenWidth(); } */ - - public static final class HiColor extends RenderWallExecutor { + public static final class HiColor extends RenderWallExecutor { public HiColor(int SCREENWIDTH, int SCREENHEIGHT, int[] columnofs, int[] ylookup, short[] screen, ColVars[] RWI, CyclicBarrier barrier) { super(SCREENWIDTH, SCREENHEIGHT, columnofs, ylookup, screen, RWI, barrier); - colfunc = - colfunchi = - new R_DrawColumnBoomOpt.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, + colfunc + = colfunchi + = new R_DrawColumnBoomOpt.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, + columnofs, null, screen, null); + colfunclow + = new R_DrawColumnBoomOptLow.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, null); - colfunclow = - new R_DrawColumnBoomOptLow.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, - columnofs, null, screen, null); } - + } - - public static final class Indexed extends RenderWallExecutor { + + public static final class Indexed extends RenderWallExecutor { public Indexed(int SCREENWIDTH, int SCREENHEIGHT, int[] columnofs, int[] ylookup, byte[] screen, ColVars[] RWI, CyclicBarrier barrier) { super(SCREENWIDTH, SCREENHEIGHT, columnofs, ylookup, screen, RWI, barrier); - colfunc = - colfunchi = - new R_DrawColumnBoomOpt.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup, + colfunc + = colfunchi + = new R_DrawColumnBoomOpt.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup, + columnofs, null, screen, null); + colfunclow + = new R_DrawColumnBoomOptLow.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, null); - colfunclow = - new R_DrawColumnBoomOptLow.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup, - columnofs, null, screen, null); } - + } - - public static final class TrueColor extends RenderWallExecutor { + + public static final class TrueColor extends RenderWallExecutor { public TrueColor(int SCREENWIDTH, int SCREENHEIGHT, int[] columnofs, int[] ylookup, int[] screen, ColVars[] RWI, CyclicBarrier barrier) { super(SCREENWIDTH, SCREENHEIGHT, columnofs, ylookup, screen, RWI, barrier); - colfunc = - colfunchi = - new R_DrawColumnBoomOpt.TrueColor(SCREENWIDTH, SCREENHEIGHT, ylookup, + colfunc + = colfunchi + = new R_DrawColumnBoomOpt.TrueColor(SCREENWIDTH, SCREENHEIGHT, ylookup, + columnofs, null, screen, null); + colfunclow + = new R_DrawColumnBoomOptLow.TrueColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, null, screen, null); - colfunclow = - new R_DrawColumnBoomOptLow.TrueColor(SCREENWIDTH, SCREENHEIGHT, ylookup, - columnofs, null, screen, null); } - + } - + } diff --git a/src/rr/parallel/VisplaneWorker.java b/src/rr/parallel/VisplaneWorker.java index 53d54eb7..af66de07 100644 --- a/src/rr/parallel/VisplaneWorker.java +++ b/src/rr/parallel/VisplaneWorker.java @@ -5,7 +5,10 @@ import doom.DoomMain; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; +import java.util.logging.Level; +import java.util.logging.Logger; import static m.fixed_t.FRACBITS; +import mochadoom.Loggers; import rr.IDetailAware; import rr.PlaneDrawer; import rr.SceneRenderer; @@ -29,46 +32,47 @@ * @author velktron * */ +public abstract class VisplaneWorker extends PlaneDrawer implements Runnable, IDetailAware { -public abstract class VisplaneWorker extends PlaneDrawer implements Runnable,IDetailAware{ + private static final Logger LOGGER = Loggers.getLogger(VisplaneWorker.class.getName()); // Private to each thread. protected final int id; protected final int NUMFLOORTHREADS; protected final CyclicBarrier barrier; - + protected int vpw_planeheight; protected V[] vpw_planezlight; - protected int vpw_basexscale,vpw_baseyscale; + protected int vpw_basexscale, vpw_baseyscale; + + protected SpanVars vpw_dsvars; + protected ColVars vpw_dcvars; - protected SpanVars vpw_dsvars; - protected ColVars vpw_dcvars; - // OBVIOUSLY each thread must have its own span functions. - protected DoomSpanFunction vpw_spanfunc; - protected DoomColumnFunction vpw_skyfunc; - protected DoomSpanFunction vpw_spanfunchi; - protected DoomSpanFunction vpw_spanfunclow; - protected DoomColumnFunction vpw_skyfunchi; - protected DoomColumnFunction vpw_skyfunclow; - - public VisplaneWorker(DoomMain DOOM,int id,int SCREENWIDTH, int SCREENHEIGHT, SceneRenderer R,CyclicBarrier visplanebarrier,int NUMFLOORTHREADS) { - super(DOOM, R); - this.barrier=visplanebarrier; - this.id=id; - this.NUMFLOORTHREADS=NUMFLOORTHREADS; + protected DoomSpanFunction vpw_spanfunc; + protected DoomColumnFunction vpw_skyfunc; + protected DoomSpanFunction vpw_spanfunchi; + protected DoomSpanFunction vpw_spanfunclow; + protected DoomColumnFunction vpw_skyfunchi; + protected DoomColumnFunction vpw_skyfunclow; + + public VisplaneWorker(DoomMain DOOM, int id, int SCREENWIDTH, int SCREENHEIGHT, SceneRenderer R, CyclicBarrier visplanebarrier, int NUMFLOORTHREADS) { + super(DOOM, R); + this.barrier = visplanebarrier; + this.id = id; + this.NUMFLOORTHREADS = NUMFLOORTHREADS; } public static final class HiColor extends VisplaneWorker { - public HiColor(DoomMain DOOM,int id, int SCREENWIDTH, int SCREENHEIGHT, SceneRenderer R, + public HiColor(DoomMain DOOM, int id, int SCREENWIDTH, int SCREENHEIGHT, SceneRenderer R, int[] columnofs, int[] ylookup, short[] screen, CyclicBarrier visplanebarrier, int NUMFLOORTHREADS) { super(DOOM, id, SCREENWIDTH, SCREENHEIGHT, R, visplanebarrier, NUMFLOORTHREADS); // Alias to those of Planes. - vpw_dsvars = new SpanVars(); - vpw_dcvars = new ColVars(); + vpw_dsvars = new SpanVars<>(); + vpw_dcvars = new ColVars<>(); vpw_spanfunc = vpw_spanfunchi = new R_DrawSpanUnrolled.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, vpw_dsvars, screen, I); vpw_spanfunclow = new R_DrawSpanLow.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, vpw_dsvars, screen, I); vpw_skyfunc = vpw_skyfunchi = new R_DrawColumnBoomOpt.HiColor(SCREENWIDTH, SCREENHEIGHT, ylookup, columnofs, vpw_dcvars, screen, I); @@ -77,119 +81,108 @@ public HiColor(DoomMain DOOM,int id, int SCREENWIDTH, int SCREEN } } - + public void setDetail(int detailshift) { - if (detailshift == 0){ + if (detailshift == 0) { vpw_spanfunc = vpw_spanfunchi; - vpw_skyfunc= vpw_skyfunchi; - } - else{ + vpw_skyfunc = vpw_skyfunchi; + } else { vpw_spanfunc = vpw_spanfunclow; - vpw_skyfunc =vpw_skyfunclow; + vpw_skyfunc = vpw_skyfunclow; } } - + @Override public void run() { - visplane_t pln=null; //visplane_t + visplane_t pln = null; //visplane_t // These must override the global ones - int light; - int x; - int stop; - int angle; - + int light; + int x; + int stop; + int angle; + // Now it's a good moment to set them. - vpw_basexscale=vpvars.getBaseXScale(); - vpw_baseyscale=vpvars.getBaseYScale(); - + vpw_basexscale = vpvars.getBaseXScale(); + vpw_baseyscale = vpvars.getBaseYScale(); + // TODO: find a better way to split work. As it is, it's very uneven // and merged visplanes in particular are utterly dire. - - for (int pl= this.id; pl pln.maxx) - continue; - - - // sky flat - if (pln.picnum == TexMan.getSkyFlatNum() ) - { - // Cache skytexture stuff here. They aren't going to change while - // being drawn, after all, are they? - int skytexture=TexMan.getSkyTexture(); - // MAES: these must be updated to keep up with screen size changes. - vpw_dcvars.viewheight=view.height; - vpw_dcvars.centery=view.centery; - vpw_dcvars.dc_texheight=TexMan.getTextureheight(skytexture)>>FRACBITS; - vpw_dcvars.dc_iscale = vpvars.getSkyScale()>>view.detailshift; - - vpw_dcvars.dc_colormap = colormap.colormaps[Palettes.COLORMAP_FIXED]; - vpw_dcvars.dc_texturemid = TexMan.getSkyTextureMid(); - for (x=pln.minx ; x <= pln.maxx ; x++) - { - - vpw_dcvars.dc_yl = pln.getTop(x); - vpw_dcvars.dc_yh = pln.getBottom(x); - - if (vpw_dcvars.dc_yl <= vpw_dcvars.dc_yh) - { - angle = (int) (addAngles(view.angle, view.xtoviewangle[x])>>>ANGLETOSKYSHIFT); - vpw_dcvars.dc_x = x; - // Optimized: texheight is going to be the same during normal skies drawing...right? - vpw_dcvars.dc_source = TexMan.GetCachedColumn(TexMan.getSkyTexture(), angle); - vpw_skyfunc.invoke(); - } - } - continue; - } - - // regular flat - vpw_dsvars.ds_source = TexMan.getSafeFlat(pln.picnum); - - vpw_planeheight = Math.abs(pln.height-view.z); - light = (pln.lightlevel >>> colormap.lightSegShift())+colormap.extralight; - - if (light >= colormap.lightLevels()) - light = colormap.lightLevels()-1; - - if (light < 0) - light = 0; - - vpw_planezlight = colormap.zlight[light]; - - // We set those values at the border of a plane's top to a "sentinel" value...ok. - pln.setTop(pln.maxx+1,(char) 0xffff); - pln.setTop(pln.minx-1, (char) 0xffff); - - stop = pln.maxx + 1; - - - for (x=pln.minx ; x<= stop ; x++) { - MakeSpans(x,pln.getTop(x-1), - pln.getBottom(x-1), - pln.getTop(x), - pln.getBottom(x)); + + if (pln.minx > pln.maxx) { + continue; + } + + // sky flat + if (pln.picnum == TexMan.getSkyFlatNum()) { + // Cache skytexture stuff here. They aren't going to change while + // being drawn, after all, are they? + int skytexture = TexMan.getSkyTexture(); + // MAES: these must be updated to keep up with screen size changes. + vpw_dcvars.viewheight = view.height; + vpw_dcvars.centery = view.centery; + vpw_dcvars.dc_texheight = TexMan.getTextureheight(skytexture) >> FRACBITS; + vpw_dcvars.dc_iscale = vpvars.getSkyScale() >> view.detailshift; + + vpw_dcvars.dc_colormap = colormap.colormaps[Palettes.COLORMAP_FIXED]; + vpw_dcvars.dc_texturemid = TexMan.getSkyTextureMid(); + for (x = pln.minx; x <= pln.maxx; x++) { + + vpw_dcvars.dc_yl = pln.getTop(x); + vpw_dcvars.dc_yh = pln.getBottom(x); + + if (vpw_dcvars.dc_yl <= vpw_dcvars.dc_yh) { + angle = (int) (addAngles(view.angle, view.xtoviewangle[x]) >>> ANGLETOSKYSHIFT); + vpw_dcvars.dc_x = x; + // Optimized: texheight is going to be the same during normal skies drawing...right? + vpw_dcvars.dc_source = TexMan.GetCachedColumn(TexMan.getSkyTexture(), angle); + vpw_skyfunc.invoke(); + } + } + continue; + } + + // regular flat + vpw_dsvars.ds_source = TexMan.getSafeFlat(pln.picnum); + + vpw_planeheight = Math.abs(pln.height - view.z); + light = (pln.lightlevel >>> colormap.lightSegShift()) + colormap.extralight; + + if (light >= colormap.lightLevels()) { + light = colormap.lightLevels() - 1; + } + + if (light < 0) { + light = 0; } - - } - // We're done, wait. - - try { - barrier.await(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (BrokenBarrierException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + + vpw_planezlight = colormap.zlight[light]; + + // We set those values at the border of a plane's top to a "sentinel" value...ok. + pln.setTop(pln.maxx + 1, (char) 0xffff); + pln.setTop(pln.minx - 1, (char) 0xffff); + + stop = pln.maxx + 1; + + for (x = pln.minx; x <= stop; x++) { + MakeSpans(x, pln.getTop(x - 1), + pln.getBottom(x - 1), + pln.getTop(x), + pln.getBottom(x)); } - } - - - - - - } \ No newline at end of file + } + // We're done, wait. + + try { + barrier.await(); + } catch (InterruptedException | BrokenBarrierException e) { + LOGGER.log(Level.SEVERE, "VisplaneWorker run failure", e); + } + // TODO Auto-generated catch block + + } + +} diff --git a/src/rr/parallel/VisplaneWorker2.java b/src/rr/parallel/VisplaneWorker2.java index dd9dcad4..cf7b617d 100644 --- a/src/rr/parallel/VisplaneWorker2.java +++ b/src/rr/parallel/VisplaneWorker2.java @@ -5,7 +5,10 @@ import doom.DoomMain; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; +import java.util.logging.Level; +import java.util.logging.Logger; import static m.fixed_t.FRACBITS; +import mochadoom.Loggers; import rr.IDetailAware; import rr.PlaneDrawer; import rr.SceneRenderer; @@ -30,75 +33,76 @@ * * TODO: fix crashes */ +public abstract class VisplaneWorker2 extends PlaneDrawer implements Runnable, IDetailAware { -public abstract class VisplaneWorker2 extends PlaneDrawer implements Runnable, IDetailAware { + private static final Logger LOGGER = Loggers.getLogger(VisplaneWorker2.class.getName()); protected final int id; protected final int NUMFLOORTHREADS; - protected int startvp; + protected int startvp; protected int endvp; protected int vpw_planeheight; protected V[] vpw_planezlight; - protected int vpw_basexscale,vpw_baseyscale; - protected final SpanVars vpw_dsvars; - protected final ColVars vpw_dcvars; - protected DoomSpanFunction vpw_spanfunc; - protected DoomColumnFunction vpw_skyfunc; - protected DoomSpanFunction vpw_spanfunchi; - protected DoomSpanFunction vpw_spanfunclow; - protected DoomColumnFunction vpw_skyfunchi; - protected DoomColumnFunction vpw_skyfunclow; + protected int vpw_basexscale, vpw_baseyscale; + protected final SpanVars vpw_dsvars; + protected final ColVars vpw_dcvars; + protected DoomSpanFunction vpw_spanfunc; + protected DoomColumnFunction vpw_skyfunc; + protected DoomSpanFunction vpw_spanfunchi; + protected DoomSpanFunction vpw_spanfunclow; + protected DoomColumnFunction vpw_skyfunchi; + protected DoomColumnFunction vpw_skyfunclow; protected visplane_t pln; - + public VisplaneWorker2(DoomMain DOOM, SceneRenderer R, int id, CyclicBarrier visplanebarrier, int NUMFLOORTHREADS) { super(DOOM, R); this.barrier = visplanebarrier; this.id = id; // Alias to those of Planes. - vpw_dsvars = new SpanVars(); - vpw_dcvars = new ColVars(); + vpw_dsvars = new SpanVars<>(); + vpw_dcvars = new ColVars<>(); this.NUMFLOORTHREADS = NUMFLOORTHREADS; } - public static class HiColor extends VisplaneWorker2{ + public static class HiColor extends VisplaneWorker2 { - public HiColor(DoomMain DOOM, SceneRenderer R,int id, + public HiColor(DoomMain DOOM, SceneRenderer R, int id, int[] columnofs, int[] ylookup, short[] screen, CyclicBarrier visplanebarrier, int NUMFLOORTHREADS) { - super(DOOM, R,id, visplanebarrier, NUMFLOORTHREADS); - vpw_spanfunc=vpw_spanfunchi=new R_DrawSpanUnrolled.HiColor(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dsvars,screen,I); - vpw_spanfunclow=new R_DrawSpanLow.HiColor(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dsvars,screen,I); - vpw_skyfunc=vpw_skyfunchi=new R_DrawColumnBoomOpt.HiColor(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dcvars,screen,I); - vpw_skyfunclow=new R_DrawColumnBoomOptLow.HiColor(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dcvars,screen,I); + super(DOOM, R, id, visplanebarrier, NUMFLOORTHREADS); + vpw_spanfunc = vpw_spanfunchi = new R_DrawSpanUnrolled.HiColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dsvars, screen, I); + vpw_spanfunclow = new R_DrawSpanLow.HiColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dsvars, screen, I); + vpw_skyfunc = vpw_skyfunchi = new R_DrawColumnBoomOpt.HiColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dcvars, screen, I); + vpw_skyfunclow = new R_DrawColumnBoomOptLow.HiColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dcvars, screen, I); } } - - public static class Indexed extends VisplaneWorker2{ - public Indexed(DoomMain DOOM, SceneRenderer R,int id, + public static class Indexed extends VisplaneWorker2 { + + public Indexed(DoomMain DOOM, SceneRenderer R, int id, int[] columnofs, int[] ylookup, byte[] screen, CyclicBarrier visplanebarrier, int NUMFLOORTHREADS) { - super(DOOM,R,id, visplanebarrier, NUMFLOORTHREADS); - vpw_spanfunc=vpw_spanfunchi=new R_DrawSpanUnrolled.Indexed(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dsvars,screen,I); - vpw_spanfunclow=new R_DrawSpanLow.Indexed(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dsvars,screen,I); - vpw_skyfunc=vpw_skyfunchi=new R_DrawColumnBoomOpt.Indexed(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dcvars,screen,I); - vpw_skyfunclow=new R_DrawColumnBoomOptLow.Indexed(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dcvars,screen,I); + super(DOOM, R, id, visplanebarrier, NUMFLOORTHREADS); + vpw_spanfunc = vpw_spanfunchi = new R_DrawSpanUnrolled.Indexed(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dsvars, screen, I); + vpw_spanfunclow = new R_DrawSpanLow.Indexed(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dsvars, screen, I); + vpw_skyfunc = vpw_skyfunchi = new R_DrawColumnBoomOpt.Indexed(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dcvars, screen, I); + vpw_skyfunclow = new R_DrawColumnBoomOptLow.Indexed(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dcvars, screen, I); } } - - public static class TrueColor extends VisplaneWorker2{ - public TrueColor(DoomMain DOOM, SceneRenderer R,int id, + public static class TrueColor extends VisplaneWorker2 { + + public TrueColor(DoomMain DOOM, SceneRenderer R, int id, int[] columnofs, int[] ylookup, int[] screen, CyclicBarrier visplanebarrier, int NUMFLOORTHREADS) { - super(DOOM, R,id, visplanebarrier, NUMFLOORTHREADS); - vpw_spanfunc=vpw_spanfunchi=new R_DrawSpanUnrolled.TrueColor(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dsvars,screen,I); - vpw_spanfunclow=new R_DrawSpanLow.TrueColor(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dsvars,screen,I); - vpw_skyfunc=vpw_skyfunchi=new R_DrawColumnBoomOpt.TrueColor(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dcvars,screen,I); - vpw_skyfunclow=new R_DrawColumnBoomOptLow.TrueColor(DOOM.vs.getScreenWidth(),DOOM.vs.getScreenHeight(),ylookup,columnofs,vpw_dcvars,screen,I); - } + super(DOOM, R, id, visplanebarrier, NUMFLOORTHREADS); + vpw_spanfunc = vpw_spanfunchi = new R_DrawSpanUnrolled.TrueColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dsvars, screen, I); + vpw_spanfunclow = new R_DrawSpanLow.TrueColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dsvars, screen, I); + vpw_skyfunc = vpw_skyfunchi = new R_DrawColumnBoomOpt.TrueColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dcvars, screen, I); + vpw_skyfunclow = new R_DrawColumnBoomOptLow.TrueColor(DOOM.vs.getScreenWidth(), DOOM.vs.getScreenHeight(), ylookup, columnofs, vpw_dcvars, screen, I); + } } - + @Override public void run() { pln = null; //visplane_t @@ -218,24 +222,23 @@ public void run() { try { barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "VisplaneWorker2 run failure", e); } // TODO Auto-generated catch block } - + private boolean isMarker(int t1) { return ((t1 & visplane_t.SENTINEL) != 0); } - + private int decodeID(int t1) { return (t1 & visplane_t.THREADIDBITS) >> visplane_t.THREADIDSHIFT; } - + private int decodeValue(int t1) { return t1 & visplane_t.THREADVALUEBITS; } - + @Override public void setDetail(int detailshift) { if (detailshift == 0) { @@ -246,7 +249,7 @@ public void setDetail(int detailshift) { vpw_skyfunc = vpw_skyfunclow; } } - + /** * R_MakeSpans * @@ -264,7 +267,6 @@ public void setDetail(int detailshift) { * @param b2 Bottom-right y coord ? * */ - @Override protected final void MakeSpans(int x, int t1, int b1, int t2, int b2) { @@ -282,28 +284,28 @@ protected final void MakeSpans(int x, int t1, int b1, int t2, int b2) { t2 = decodeValue(t2); } } - + super.MakeSpans(x, t1, b1, t2, b2); } - - /** - * R_MapPlane - * - * Called only by R_MakeSpans. - * - * This is where the actual span drawing function is called. - * - * Uses global vars: - * planeheight - * ds_source -> flat data has already been set. - * basexscale -> actual drawing angle and position is computed from these - * baseyscale - * viewx - * viewy - * - * BASIC PRIMITIVE - */ - /* TODO: entirely similar to serial version? + + /** + * R_MapPlane + * + * Called only by R_MakeSpans. + * + * This is where the actual span drawing function is called. + * + * Uses global vars: + * planeheight + * ds_source -> flat data has already been set. + * basexscale -> actual drawing angle and position is computed from these + * baseyscale + * viewx + * viewy + * + * BASIC PRIMITIVE + */ + /* TODO: entirely similar to serial version? private void MapPlane ( int y, @@ -368,8 +370,7 @@ protected final void MakeSpans(int x, int t1, int b1, int t2, int b2) { else vpw_spanfunclow.invoke(); } - */ - - // Private to each thread. - CyclicBarrier barrier; - } + */ + // Private to each thread. + CyclicBarrier barrier; +} diff --git a/src/rr/patch_t.java b/src/rr/patch_t.java index aeaf2fa3..e00f3f54 100644 --- a/src/rr/patch_t.java +++ b/src/rr/patch_t.java @@ -4,7 +4,6 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Hashtable; - import utils.C2JUtils; import w.CacheableDoomObject; import w.DoomBuffer; @@ -14,25 +13,24 @@ //Patches are used for sprites and all masked pictures, //and we compose textures from the TEXTURE1/2 lists //of patches. +public class patch_t implements /*IReadableDoomObject,*/ CacheableDoomObject { -public class patch_t implements /*IReadableDoomObject,*/CacheableDoomObject{ - - /** bounding box size */ - public short width, height; + /** bounding box size */ + public short width, height; /** pixels to the left of origin */ - public short leftoffset; + public short leftoffset; /** pixels below the origin */ - public short topoffset; + public short topoffset; /** This used to be an implicit array pointing to raw posts of data. * TODO: get rid of it? It's never used * only [width] used the [0] is &columnofs[width] */ - public int[] columnofs; + public int[] columnofs; /** The ACTUAL data is here, nicely deserialized (well, almost) */ public column_t[] columns; - + /** Added for debug aid purposes */ public String name; - + /** Synthesizing constructor. * You have to provide the columns yourself, a-posteriori. * @@ -42,19 +40,19 @@ public class patch_t implements /*IReadableDoomObject,*/CacheableDoomObject{ * @param leftoffset * @param topoffset */ - public patch_t(String name, int width, int height, int leftoffset, int topoffset){ - this.name=name; - this.width=(short) width; - this.height=(short) height; - this.leftoffset=(short) leftoffset; - this.columns=new column_t[width]; + public patch_t(String name, int width, int height, int leftoffset, int topoffset) { + this.name = name; + this.width = (short) width; + this.height = (short) height; + this.leftoffset = (short) leftoffset; + this.columns = new column_t[width]; } - - public patch_t(){ - + + public patch_t() { + } - - /* @Override + + /* @Override public void read(DoomFile f) throws IOException{ long pos=f.getFilePointer(); @@ -76,7 +74,6 @@ public void read(DoomFile f) throws IOException{ } }*/ - /** In the C code, reading is "aided", aka they know how long the header + all * posts/columns actually are on disk, and only "deserialize" them when using them. * Here, we strive to keep stuff as elegant and OO as possible, so each column will get @@ -85,7 +82,6 @@ public void read(DoomFile f) throws IOException{ * separate columns at the patch level (an advantage is that it's now easy to address * individual columns). However, column data is still read "raw". */ - @Override public void unpack(ByteBuffer b) throws IOException { @@ -93,70 +89,71 @@ public void unpack(ByteBuffer b) b.position(0); // In ByteBuffers, the order can be conveniently set beforehand :-o b.order(ByteOrder.LITTLE_ENDIAN); - - this.width=b.getShort(); - - this.height=b.getShort(); - this.leftoffset=b.getShort(); - this.topoffset=b.getShort(); + + this.width = b.getShort(); + + this.height = b.getShort(); + this.leftoffset = b.getShort(); + this.topoffset = b.getShort(); // As many columns as width...right??? - this.columnofs=new int[this.width]; - this.columns=new column_t[this.width]; - C2JUtils.initArrayOfObjects( this.columns, column_t.class); - + this.columnofs = new int[this.width]; + this.columns = new column_t[this.width]; + C2JUtils.initArrayOfObjects(this.columns, column_t.class); + // Compute the ACTUAL full-column sizes. - int[] actualsizes=new int[columns.length]; - - for (int i=0;i badColumns=new Hashtable(); - - private static column_t getBadColumn(int size){ - - if (badColumns.get(size)==null){ - column_t tmp=new column_t(); - tmp.data=new byte[size+5]; - for (int i=3;i badColumns = new Hashtable<>(); + + private static column_t getBadColumn(int size) { + + if (badColumns.get(size) == null) { + column_t tmp = new column_t(); + tmp.data = new byte[size + 5]; + for (int i = 3; i < size + 3; i++) { + tmp.data[i] = (byte) (i - 3); + } + + tmp.data[size + 4] = (byte) 0xFF; + tmp.posts = 1; + //tmp.length=(short) size; + //tmp.topdelta=0; + tmp.postofs = new int[]{3}; + tmp.postdeltas = new short[]{0}; + tmp.postlen = new short[]{(short) (size % 256)}; + //tmp.setData(); + badColumns.put(size, tmp); } - - tmp.data[size+4]=(byte) 0xFF; - tmp.posts=1; - //tmp.length=(short) size; - //tmp.topdelta=0; - tmp.postofs=new int[]{3}; - tmp.postdeltas=new short[]{0}; - tmp.postlen=new short[]{(short) (size%256)}; - //tmp.setData(); - badColumns.put(size, tmp); - } - - return badColumns.get(size); - + + return badColumns.get(size); + } - -} \ No newline at end of file + +} diff --git a/src/rr/sector_t.java b/src/rr/sector_t.java index 3df62747..9106a30e 100644 --- a/src/rr/sector_t.java +++ b/src/rr/sector_t.java @@ -10,6 +10,7 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.util.logging.Level; +import java.util.logging.Logger; import m.IRandom; import static m.fixed_t.FRACBITS; import static m.fixed_t.FRACUNIT; @@ -31,6 +32,8 @@ */ public class sector_t implements IReadableDoomObject, IPackableDoomObject, Resettable { + private static final Logger LOGGER = Loggers.getLogger(sector_t.class.getName()); + public ThinkerList TL; public IRandom RND; @@ -90,19 +93,17 @@ public sector_t() { public int id; /** killough 1/30/98: improves searches for tags. */ - public int nexttag,firsttag; + public int nexttag, firsttag; @Override public String toString() { - String str = - String.format("Sector: %d %x %x %d %d %d %d %d", id, floorheight, - ceilingheight, floorpic, ceilingpic, lightlevel, special, // needed? - tag); // needed? + // needed? - return str; + return String.format("Sector: %d %x %x %d %d %d %d %d", id, floorheight, + ceilingheight, floorpic, ceilingpic, lightlevel, special, // needed? + tag); } - // // P_FindLowestFloorSurrounding() // FIND LOWEST FLOOR HEIGHT IN SURROUNDING SECTORS @@ -117,11 +118,13 @@ public int FindLowestFloorSurrounding() { check = this.lines[i]; other = check.getNextSector(this); - if (other == null) + if (other == null) { continue; + } - if (other.floorheight < floor) + if (other.floorheight < floor) { floor = other.floorheight; + } } return floor; } @@ -136,7 +139,6 @@ public int FindLowestFloorSurrounding() { * * @param sec */ - public int FindHighestFloorSurrounding() { int i; line_t check; @@ -150,11 +152,13 @@ public int FindHighestFloorSurrounding() { // The compiler nagged about this being unreachable, with // some older 1.6 JDKs, but that's obviously not true. - if (other == null) + if (other == null) { continue; + } - if (other.floorheight > floor) + if (other.floorheight > floor) { floor = other.floorheight; + } } return floor; } @@ -167,7 +171,6 @@ public int FindHighestFloorSurrounding() { * @param currentheight * @return fixed */ - public int FindNextHighestFloor(int currentheight) { int i; int h; @@ -182,30 +185,35 @@ public int FindNextHighestFloor(int currentheight) { check = this.lines[i]; other = check.getNextSector(this); - if (other == null) + if (other == null) { continue; + } - if (other.floorheight > height) + if (other.floorheight > height) { heightlist[h++] = other.floorheight; + } // Check for overflow. Exit. if (h >= MAX_ADJOINING_SECTORS) { - Loggers.getLogger(sector_t.class.getName()).log(Level.WARNING, - "Sector with more than 20 adjoining sectors\n"); + LOGGER.log(Level.WARNING, + "Sector with more than 20 adjoining sectors"); break; } } // Find lowest height in list - if (h == 0) + if (h == 0) { return currentheight; + } min = heightlist[0]; // Range checking? - for (i = 1; i < h; i++) - if (heightlist[i] < min) + for (i = 1; i < h; i++) { + if (heightlist[i] < min) { min = heightlist[i]; + } + } return min; } @@ -215,14 +223,16 @@ public int FindNextHighestFloor(int currentheight) { // @SourceCode.Exact @P_Spec.C(P_FindLowestCeilingSurrounding) - public @fixed_t int FindLowestCeilingSurrounding() { + public @fixed_t + int FindLowestCeilingSurrounding() { line_t check; sector_t other; int height = MAXINT; for (int i = 0; i < this.linecount; i++) { check = this.lines[i]; - getNextSector: { + getNextSector: + { other = check.getNextSector(this); } @@ -250,11 +260,13 @@ public int FindHighestCeilingSurrounding() { check = this.lines[i]; other = check.getNextSector(this); - if (other == null) + if (other == null) { continue; + } - if (other.ceilingheight > height) + if (other.ceilingheight > height) { height = other.ceilingheight; + } } return height; } @@ -267,7 +279,6 @@ public void read(DataInputStream f) // like to read memory-format sector_t's is from // savegames, and in vanilla savegames, not all info // is saved (or read) from disk. - this.floorheight = DoomIO.readLEShort(f) << FRACBITS; this.ceilingheight = DoomIO.readLEShort(f) << FRACBITS; // MAES: it may be necessary to apply a hack in order to diff --git a/src/rr/seg_t.java b/src/rr/seg_t.java index b8e8c4c2..187adf96 100644 --- a/src/rr/seg_t.java +++ b/src/rr/seg_t.java @@ -2,7 +2,6 @@ import static m.fixed_t.FRACBITS; import static m.fixed_t.FixedMul; - import p.Resettable; /** @@ -10,7 +9,6 @@ * * @author Maes */ - public class seg_t implements Resettable { @@ -27,7 +25,6 @@ public class seg_t public long angle; // MAES: all were single pointers. - public side_t sidedef; public line_t linedef; @@ -79,14 +76,16 @@ public static int PointOnSegSide(int x, int y, seg_t line) { ldy = line.v2y - ly; if (ldx == 0) { - if (x <= lx) + if (x <= lx) { return (ldy > 0) ? 1 : 0; + } return (ldy < 0) ? 1 : 0; } if (ldy == 0) { - if (y <= ly) + if (y <= ly) { return (ldx < 0) ? 1 : 0; + } return (ldx > 0) ? 1 : 0; } @@ -139,14 +138,16 @@ public int PointOnSegSide(int x, int y) { ldy = this.v2y - ly; if (ldx == 0) { - if (x <= lx) + if (x <= lx) { return (ldy > 0) ? 1 : 0; + } return (ldy < 0) ? 1 : 0; } if (ldy == 0) { - if (y <= ly) + if (y <= ly) { return (ldx < 0) ? 1 : 0; + } return (ldx > 0) ? 1 : 0; } @@ -177,8 +178,8 @@ public int PointOnSegSide(int x, int y) { public String toString() { return String .format( - "Seg %d\n\tFrontsector: %s\n\tBacksector: %s\n\tVertexes: %x %x %x %x", - iSegID, frontsector, backsector, v1x, v1y, v2x, v2y); + "Seg %d\n\tFrontsector: %s\n\tBacksector: %s\n\tVertexes: %x %x %x %x", + iSegID, frontsector, backsector, v1x, v1y, v2x, v2y); } @Override diff --git a/src/rr/side_t.java b/src/rr/side_t.java index 9e182e56..443cc412 100644 --- a/src/rr/side_t.java +++ b/src/rr/side_t.java @@ -3,10 +3,8 @@ import java.io.DataInputStream; import java.io.IOException; import java.nio.ByteBuffer; - -import p.Resettable; - import static m.fixed_t.FRACBITS; +import p.Resettable; import w.DoomIO; import w.IPackableDoomObject; import w.IReadableDoomObject; @@ -18,6 +16,7 @@ */ public class side_t implements IReadableDoomObject, IPackableDoomObject, Resettable { + /** (fixed_t) add this to the calculated texture column */ public int textureoffset; diff --git a/src/rr/spritedef_t.java b/src/rr/spritedef_t.java index 4e9b06f8..a995fb02 100644 --- a/src/rr/spritedef_t.java +++ b/src/rr/spritedef_t.java @@ -4,44 +4,41 @@ * A sprite definition: * a number of animation frames. */ - public class spritedef_t { /** the very least, primitive fields won't bomb, * and copy constructors can do their job. */ - public spritedef_t(){ + public spritedef_t() { } - - public spritedef_t(int numframes){ - this.numframes=numframes; - this.spriteframes=new spriteframe_t[numframes]; + + public spritedef_t(int numframes) { + this.numframes = numframes; + this.spriteframes = new spriteframe_t[numframes]; } - - public spritedef_t(spriteframe_t[] frames){ - this.numframes=frames.length; - this.spriteframes=new spriteframe_t[numframes]; + + public spritedef_t(spriteframe_t[] frames) { + this.numframes = frames.length; + this.spriteframes = new spriteframe_t[numframes]; // copy shit over... - for (int i=0;i implements Comparable>{ +public class vissprite_t implements Comparable> { // Doubly linked list. -public vissprite_t prev; -public vissprite_t next; + public vissprite_t prev; + public vissprite_t next; -public int x1; -public int x2; + public int x1; + public int x2; // for line side calculation -public int gx; -public int gy; + public int gx; + public int gy; // global bottom / top for silhouette clipping -public int gz; -public int gzt; + public int gz; + public int gzt; // horizontal position of x1 -public int startfrac; + public int startfrac; -public int scale; + public int scale; // negative if flipped -public int xiscale; + public int xiscale; -public int texturemid; -public int patch; + public int texturemid; + public int patch; -/** for color translation and shadow draw, - * maxbright frames as well. - * - * Use paired with pcolormap; - */ -public V colormap; + /** for color translation and shadow draw, + * maxbright frames as well. + * + * Use paired with pcolormap; + */ + public V colormap; -/* pointer into colormap + /* pointer into colormap public int pcolormap; */ + public long mobjflags; + + /** visspites are sorted by scale */ + @Override + public final int compareTo(vissprite_t o) { + // We only really care if it's drawn before. + if (this.scale > o.scale) { + return 1; + } + if (this.scale < o.scale) { + return -1; + } + return 0; + } + + public String toString() { + return ("Effective drawing position x1: " + x1 + " x2: " + x2 + " scale " + (scale / 65535.0) + " iscale " + (xiscale / 65535.0)); + } -public long mobjflags; - -/** visspites are sorted by scale */ - -@Override -public final int compareTo(vissprite_t o) { - // We only really care if it's drawn before. - if (this.scale> o.scale) return 1; - if (this.scale< o.scale) return -1; - return 0; } - -public String toString(){ - return ("Effective drawing position x1: "+x1 + " x2: "+ x2 +" scale "+(scale/65535.0) +" iscale "+(xiscale/65535.0)); -} - -} \ No newline at end of file diff --git a/src/rr/z_vertex_t.java b/src/rr/z_vertex_t.java index 28ede4f7..60c6962b 100644 --- a/src/rr/z_vertex_t.java +++ b/src/rr/z_vertex_t.java @@ -7,22 +7,22 @@ public class z_vertex_t extends vertex_t { - public z_vertex_t(){ + public z_vertex_t() { super(); } - + /** Notice how we auto-expand to fixed_t */ @Override public void unpack(ByteBuffer buf) throws IOException { buf.order(ByteOrder.LITTLE_ENDIAN); - this.x=buf.getInt(); - this.y=buf.getInt(); - + this.x = buf.getInt(); + this.y = buf.getInt(); + } - + public final static int sizeOf() { return 8; } - + } diff --git a/src/s/AbstractDoomAudio.java b/src/s/AbstractDoomAudio.java index 3a41acf6..c65782f2 100644 --- a/src/s/AbstractDoomAudio.java +++ b/src/s/AbstractDoomAudio.java @@ -11,8 +11,11 @@ import data.sounds.musicenum_t; import data.sounds.sfxenum_t; import doom.DoomMain; +import java.util.logging.Level; +import java.util.logging.Logger; import static m.fixed_t.FRACBITS; import static m.fixed_t.FixedMul; +import mochadoom.Loggers; import p.mobj_t; /** Some stuff that is not implementation dependant @@ -24,289 +27,267 @@ * * * */ +public class AbstractDoomAudio implements IDoomSound { + private static final Logger LOGGER = Loggers.getLogger(AbstractDoomAudio.class.getName()); -public class AbstractDoomAudio implements IDoomSound{ + protected final DoomMain DS; + protected final IMusic IMUS; + protected final ISoundDriver ISND; - protected final DoomMain DS; - protected final IMusic IMUS; - protected final ISoundDriver ISND; + protected final int numChannels; - protected final int numChannels; + protected final static boolean D = false; - protected final static boolean D=false; - - /** the set of channels available. These are "soft" descriptor + /** the set of channels available. These are "soft" descriptor channels, not to be confused with actual hardware audio lines, which are an entirely different concern. - */ - - protected final channel_t[] channels; - - - // These are not used, but should be (menu). - // Maximum volume of a sound effect. - // Internal default is max out of 0-15. - protected int snd_SfxVolume = 15; - - // Maximum volume of music. Useless so far. - protected int snd_MusicVolume = 15; - - // whether songs are mus_paused - protected boolean mus_paused; - - // music currently being played - protected musicinfo_t mus_playing; - - protected int nextcleanup; - - public AbstractDoomAudio(DoomMain DS, int numChannels){ - this.DS = DS; - this.numChannels=numChannels; - this.channels=new channel_t[numChannels]; - this.IMUS=DS.music; - this.ISND=DS.soundDriver; - } - - - - /** Volume, pitch, separation & priority packed for parameter passing */ - - protected class vps_t{ - int volume; - int pitch; - int sep; - int priority; - } - - - /** - * Initializes sound stuff, including volume - * Sets channels, SFX and music volume, - * allocates channel buffer, sets S_sfx lookup. - */ - - public void Init - ( int sfxVolume, - int musicVolume ) - { - int i; - - System.err.printf("S_Init: default sfx volume %d\n", sfxVolume); - - this.snd_SfxVolume=sfxVolume; - this.snd_MusicVolume=musicVolume; - // Whatever these did with DMX, these are rather dummies now. - // MAES: any implementation-dependant channel setup should start here. - ISND.SetChannels(numChannels); - - SetSfxVolume(sfxVolume); - // No music with Linux - another dummy. - // MAES: these must be initialized somewhere, perhaps not here? - IMUS.SetMusicVolume(musicVolume); - - // Allocating the internal channels for mixing - // (the maximum numer of sounds rendered - // simultaneously) within zone memory. - // MAES: already done that in the constructor. - - // Free all channels for use - for (i=0 ; i mus_e3m9) - // mnum -= mus_e3m9; - - ChangeMusic(mnum, true); - - nextcleanup = 15; - } - - private vps_t vps=new vps_t(); - - public void - StartSoundAtVolume - ( ISoundOrigin origin_p, - int sfx_id, - int volume ) - { - - boolean rc; - int sep = 0; // This is set later. - int pitch; - int priority; - sfxinfo_t sfx; - int cnum; - - ISoundOrigin origin = (ISoundOrigin) origin_p; - - - // Debug. - - //if (origin!=null && origin.type!=null) - // System.err.printf( - // "S_StartSoundAtVolume: playing sound %d (%s) from %s %d\n", - // sfx_id, S_sfx[sfx_id].name , origin.type.toString(),origin.hashCode()); - - - // check for bogus sound # - if (sfx_id < 1 || sfx_id > NUMSFX){ - Exception e=new Exception(); - e.printStackTrace(); - DS.doomSystem.Error("Bad sfx #: %d", sfx_id); - } - - sfx = S_sfx[sfx_id]; - - // Initialize sound parameters - if (sfx.link!=null) - { - pitch = sfx.pitch; - priority = sfx.priority; - volume += sfx.volume; - - if (volume < 1) - return; - - if (volume > snd_SfxVolume) - volume = snd_SfxVolume; - } - else - { - pitch = NORM_PITCH; - priority = NORM_PRIORITY; - } - - - // Check to see if it is audible, - // and if not, modify the params - if ((origin!=null) && origin != DS.players[DS.consoleplayer].mo) - { - vps.volume=volume; - vps.pitch=pitch; - vps.sep=sep; - rc = AdjustSoundParams(DS.players[DS.consoleplayer].mo, - origin, vps); - volume=vps.volume; - pitch=vps.pitch; - sep=vps.sep; - - - if ( origin.getX() == DS.players[DS.consoleplayer].mo.x - && origin.getY() == DS.players[DS.consoleplayer].mo.y) - { - sep = NORM_SEP; - } - - if (!rc) { - //System.err.printf("S_StartSoundAtVolume: Sound %d (%s) rejected because: inaudible\n", - // sfx_id, S_sfx[sfx_id].name ); - return; - } - } - else - { - sep = NORM_SEP; - } - - // hacks to vary the sfx pitches - if (sfx_id >= sfxenum_t.sfx_sawup.ordinal() - && sfx_id <= sfxenum_t.sfx_sawhit.ordinal()) - { - pitch += 8 - (DS.random.M_Random()&15); - - if (pitch<0) - pitch = 0; - else if (pitch>255) - pitch = 255; - } - else if (sfx_id != sfxenum_t.sfx_itemup.ordinal() - && sfx_id != sfxenum_t.sfx_tink.ordinal()) - { - pitch += 16 - (DS.random.M_Random()&31); - - if (pitch<0) - pitch = 0; - else if (pitch>255) - pitch = 255; - } - - // kill old sound - StopSound(origin); - - // try to find a channel - cnum = getChannel(origin, sfx); - - if (cnum<0) - return; - - // - // This is supposed to handle the loading/caching. - // For some odd reason, the caching is done nearly - // each time the sound is needed? - // - - // get lumpnum if necessary - if (sfx.lumpnum < 0) // Now, it crosses into specific territory. - sfx.lumpnum = ISND.GetSfxLumpNum(sfx); - - /* + */ + protected final channel_t[] channels; + + // These are not used, but should be (menu). + // Maximum volume of a sound effect. + // Internal default is max out of 0-15. + protected int snd_SfxVolume = 15; + + // Maximum volume of music. Useless so far. + protected int snd_MusicVolume = 15; + + // whether songs are mus_paused + protected boolean mus_paused; + + // music currently being played + protected musicinfo_t mus_playing; + + protected int nextcleanup; + + public AbstractDoomAudio(DoomMain DS, int numChannels) { + this.DS = DS; + this.numChannels = numChannels; + this.channels = new channel_t[numChannels]; + this.IMUS = DS.music; + this.ISND = DS.soundDriver; + } + + /** Volume, pitch, separation & priority packed for parameter passing */ + protected class vps_t { + + int volume; + int pitch; + int sep; + int priority; + } + + /** + * Initializes sound stuff, including volume + * Sets channels, SFX and music volume, + * allocates channel buffer, sets S_sfx lookup. + */ + public void Init(int sfxVolume, + int musicVolume) { + int i; + + LOGGER.log(Level.INFO, String.format("S_Init: default sfx volume %d", sfxVolume)); + + this.snd_SfxVolume = sfxVolume; + this.snd_MusicVolume = musicVolume; + // Whatever these did with DMX, these are rather dummies now. + // MAES: any implementation-dependant channel setup should start here. + ISND.SetChannels(numChannels); + + SetSfxVolume(sfxVolume); + // No music with Linux - another dummy. + // MAES: these must be initialized somewhere, perhaps not here? + IMUS.SetMusicVolume(musicVolume); + + // Allocating the internal channels for mixing + // (the maximum numer of sounds rendered + // simultaneously) within zone memory. + // MAES: already done that in the constructor. + // Free all channels for use + for (i = 0; i < numChannels; i++) { + channels[i] = new channel_t(); + //channels[i].sfxinfo = null; + } + + // no sounds are playing, and they are not mus_paused + mus_paused = false; + + // Note that sounds have not been cached (yet). + for (i = 1; i < S_sfx.length; i++) { + S_sfx[i].lumpnum = S_sfx[i].usefulness = -1; + } + } + + // + // Per level startup code. + // Kills playing sounds at start of level, + // determines music if any, changes music. + // + public void Start() { + int cnum; + int mnum; + + // kill all playing sounds at start of level + // (trust me - a good idea) + for (cnum = 0; cnum < numChannels; cnum++) { + if (channels[cnum].sfxinfo != null) { + StopChannel(cnum); + } + } + + // start new music for the level + mus_paused = false; + + if (DS.isCommercial()) { + mnum = musicenum_t.mus_runnin.ordinal() + DS.gamemap - 1; + } else { + musicenum_t[] spmus + = { + // Song - Who? - Where? + + musicenum_t.mus_e3m4, // American e4m1 + musicenum_t.mus_e3m2, // Romero e4m2 + musicenum_t.mus_e3m3, // Shawn e4m3 + musicenum_t.mus_e1m5, // American e4m4 + musicenum_t.mus_e2m7, // Tim e4m5 + musicenum_t.mus_e2m4, // Romero e4m6 + musicenum_t.mus_e2m6, // J.Anderson e4m7 CHIRON.WAD + musicenum_t.mus_e2m5, // Shawn e4m8 + musicenum_t.mus_e1m9 // Tim e4m9 + }; + + if (DS.gameepisode < 4) { + mnum = musicenum_t.mus_e1m1.ordinal() + (DS.gameepisode - 1) * 9 + DS.gamemap - 1; + } else { + mnum = spmus[DS.gamemap - 1].ordinal(); + } + } + + // HACK FOR COMMERCIAL + // if (commercial && mnum > mus_e3m9) + // mnum -= mus_e3m9; + ChangeMusic(mnum, true); + + nextcleanup = 15; + } + + private vps_t vps = new vps_t(); + + public void + StartSoundAtVolume(ISoundOrigin origin_p, + int sfx_id, + int volume) { + + boolean rc; + int sep = 0; // This is set later. + int pitch; + int priority; + sfxinfo_t sfx; + int cnum; + + ISoundOrigin origin = (ISoundOrigin) origin_p; + + // Debug. + //if (origin!=null && origin.type!=null) + // System.err.printf( + // "S_StartSoundAtVolume: playing sound %d (%s) from %s %d\n", + // sfx_id, S_sfx[sfx_id].name , origin.type.toString(),origin.hashCode()); + // check for bogus sound # + if (sfx_id < 1 || sfx_id > NUMSFX) { + DS.doomSystem.Error("Bad sfx #: %d", sfx_id); + } + + sfx = S_sfx[sfx_id]; + + // Initialize sound parameters + if (sfx.link != null) { + pitch = sfx.pitch; + priority = sfx.priority; + volume += sfx.volume; + + if (volume < 1) { + return; + } + + if (volume > snd_SfxVolume) { + volume = snd_SfxVolume; + } + } else { + pitch = NORM_PITCH; + priority = NORM_PRIORITY; + } + + // Check to see if it is audible, + // and if not, modify the params + if ((origin != null) && origin != DS.players[DS.consoleplayer].mo) { + vps.volume = volume; + vps.pitch = pitch; + vps.sep = sep; + rc = AdjustSoundParams(DS.players[DS.consoleplayer].mo, + origin, vps); + volume = vps.volume; + pitch = vps.pitch; + sep = vps.sep; + + if (origin.getX() == DS.players[DS.consoleplayer].mo.x + && origin.getY() == DS.players[DS.consoleplayer].mo.y) { + sep = NORM_SEP; + } + + if (!rc) { + //System.err.printf("S_StartSoundAtVolume: Sound %d (%s) rejected because: inaudible\n", + // sfx_id, S_sfx[sfx_id].name ); + return; + } + } else { + sep = NORM_SEP; + } + + // hacks to vary the sfx pitches + if (sfx_id >= sfxenum_t.sfx_sawup.ordinal() + && sfx_id <= sfxenum_t.sfx_sawhit.ordinal()) { + pitch += 8 - (DS.random.M_Random() & 15); + + if (pitch < 0) { + pitch = 0; + } else if (pitch > 255) { + pitch = 255; + } + } else if (sfx_id != sfxenum_t.sfx_itemup.ordinal() + && sfx_id != sfxenum_t.sfx_tink.ordinal()) { + pitch += 16 - (DS.random.M_Random() & 31); + + if (pitch < 0) { + pitch = 0; + } else if (pitch > 255) { + pitch = 255; + } + } + + // kill old sound + StopSound(origin); + + // try to find a channel + cnum = getChannel(origin, sfx); + + if (cnum < 0) { + return; + } + + // + // This is supposed to handle the loading/caching. + // For some odd reason, the caching is done nearly + // each time the sound is needed? + // + // get lumpnum if necessary + if (sfx.lumpnum < 0) // Now, it crosses into specific territory. + { + sfx.lumpnum = ISND.GetSfxLumpNum(sfx); + } + + /* #ifndef SNDSRV // cache data if necessary if (!sfx->data) @@ -322,54 +303,51 @@ else if (pitch>255) } #endif */ - - // increase the usefulness - if (sfx.usefulness++ < 0) - sfx.usefulness = 1; - - // Assigns the handle to one of the channels in the - // mix/output buffer. This is when things actually - // become hard (pun intended). - // TODO: which channel? How do we know how the actual hardware - // ones map with the "soft" ones? - // Essentially we're begging to get an actual channel. - - channels[cnum].handle = ISND.StartSound(sfx_id, - /*sfx->data,*/ - volume, - sep, - pitch, - priority); - - if (D) System.err.printf("Handle %d for channel %d for sound %s vol %d sep %d\n",channels[cnum].handle, - cnum,sfx.name,volume,sep); - } - - - public void - StartSound - ( ISoundOrigin origin, - sfxenum_t sfx_id ){ - // MAES: necessary sanity check at this point. - if (sfx_id!=null && sfx_id.ordinal()>0) - StartSound(origin,sfx_id.ordinal()); - } - - public void - StartSound - ( ISoundOrigin origin, - int sfx_id ) - { - /* #ifdef SAWDEBUG + // increase the usefulness + if (sfx.usefulness++ < 0) { + sfx.usefulness = 1; + } + + // Assigns the handle to one of the channels in the + // mix/output buffer. This is when things actually + // become hard (pun intended). + // TODO: which channel? How do we know how the actual hardware + // ones map with the "soft" ones? + // Essentially we're begging to get an actual channel. + channels[cnum].handle = ISND.StartSound(sfx_id, + /*sfx->data,*/ + volume, + sep, + pitch, + priority); + + if (D) { + LOGGER.log(Level.FINE, String.format("Handle %d for channel %d for sound %s vol %d sep %d\n", channels[cnum].handle, + cnum, sfx.name, volume, sep)); + } + } + + public void + StartSound(ISoundOrigin origin, + sfxenum_t sfx_id) { + // MAES: necessary sanity check at this point. + if (sfx_id != null && sfx_id.ordinal() > 0) { + StartSound(origin, sfx_id.ordinal()); + } + } + + public void + StartSound(ISoundOrigin origin, + int sfx_id) { + /* #ifdef SAWDEBUG // if (sfx_id == sfx_sawful) // sfx_id = sfx_itemup; #endif */ - StartSoundAtVolume(origin, sfx_id, snd_SfxVolume); - + StartSoundAtVolume(origin, sfx_id, snd_SfxVolume); - // UNUSED. We had problems, had we not? - /* #ifdef SAWDEBUG + // UNUSED. We had problems, had we not? + /* #ifdef SAWDEBUG { int i; int n; @@ -423,61 +401,53 @@ else if (pitch>255) } } #endif*/ - - } - - // This one is public. - public void StopSound(ISoundOrigin origin) - { - - int cnum; - - for (cnum=0 ; cnum snd_SfxVolume) - { - vps.volume = snd_SfxVolume; - } - } - - // check non-local sounds for distance clipping - // or modify their params - if (c.origin!=null && (listener != c.origin)) - { - audible = AdjustSoundParams(listener, - c.origin, - vps); - - if (!audible) - { - StopChannel(cnum); - } - else - ISND.UpdateSoundParams(c.handle, vps.volume, vps.sep, vps.pitch); - } - } - else - { - // if channel is allocated but sound has stopped, - // free it - StopChannel(cnum); - } - } - } - // kill music if it is a single-play && finished - // if ( mus_playing - // && !I_QrySongPlaying(mus_playing->handle) - // && !mus_paused ) - // S_StopMusic(); - } - - public void SetMusicVolume(int volume) - { - if (volume < 0 || volume > 127) - { - DS.doomSystem.Error("Attempt to set music volume at %d", - volume); - } - - IMUS.SetMusicVolume(volume); - snd_MusicVolume = volume; - } - - public void SetSfxVolume(int volume) - { - - if (volume < 0 || volume > 127) - DS.doomSystem.Error("Attempt to set sfx volume at %d", volume); - - snd_SfxVolume = volume; - - } - - // - // Starts some music with the music id found in sounds.h. - // - public void StartMusic(int m_id) - { - ChangeMusic(m_id, false); - } - - // - // Starts some music with the music id found in sounds.h. - // - public void StartMusic(musicenum_t m_id) - { - ChangeMusic(m_id.ordinal(), false); - } - - public void ChangeMusic(musicenum_t musicnum, - boolean looping ) - { - ChangeMusic(musicnum.ordinal(), false); - } - - - public void - ChangeMusic - ( int musicnum, - boolean looping ) - { - musicinfo_t music = null; - String namebuf; - - if ( (musicnum <= musicenum_t.mus_None.ordinal()) - || (musicnum >= musicenum_t.NUMMUSIC.ordinal()) ) - { - - DS.doomSystem.Error("Bad music number %d", musicnum); - } - else - music = sounds.S_music[musicnum]; - - if (mus_playing == music) - return; - - // shutdown old music - StopMusic(); - - // get lumpnum if neccessary - if (music.lumpnum==0) - { - namebuf=String.format("d_%s", music.name); - music.lumpnum = DS.wadLoader.GetNumForName(namebuf); - } - - // load & register it - music.data = DS.wadLoader.CacheLumpNumAsRawBytes(music.lumpnum, Defines.PU_MUSIC); - music.handle = IMUS.RegisterSong(music.data); - - // play it - IMUS.PlaySong(music.handle, looping); - SetMusicVolume(this.snd_MusicVolume); - - mus_playing = music; - } - - public void StopMusic() - { - if (mus_playing!=null) - { - if (mus_paused) - IMUS.ResumeSong(mus_playing.handle); - - IMUS.StopSong(mus_playing.handle); - IMUS.UnRegisterSong(mus_playing.handle); - //Z_ChangeTag(mus_playing->data, PU_CACHE); - - mus_playing.data = null; - mus_playing = null; - } - } - - - /** This is S_StopChannel. There's another StopChannel - * with a similar contract in ISound. Don't confuse the two. - * - * - * - * @param cnum - */ - - protected void StopChannel(int cnum) - { - - int i; - channel_t c = channels[cnum]; - - // Is it playing? - if (c.sfxinfo!=null) - { - // stop the sound playing - if (ISND.SoundIsPlaying(c.handle)) - { - /*#ifdef SAWDEBUG + for (cnum = 0; cnum < numChannels; cnum++) { + c = channels[cnum]; + sfx = c.sfxinfo; + + //System.out.printf("Updating channel %d %s\n",cnum,c); + if (c.sfxinfo != null) { + if (ISND.SoundIsPlaying(c.handle)) { + // initialize parameters + vps.volume = snd_SfxVolume; + vps.pitch = NORM_PITCH; + vps.sep = NORM_SEP; + + sfx = c.sfxinfo; + + if (sfx.link != null) { + vps.pitch = sfx.pitch; + vps.volume += sfx.volume; + if (vps.volume < 1) { + StopChannel(cnum); + continue; + } else if (vps.volume > snd_SfxVolume) { + vps.volume = snd_SfxVolume; + } + } + + // check non-local sounds for distance clipping + // or modify their params + if (c.origin != null && (listener != c.origin)) { + audible = AdjustSoundParams(listener, + c.origin, + vps); + + if (!audible) { + StopChannel(cnum); + } else { + ISND.UpdateSoundParams(c.handle, vps.volume, vps.sep, vps.pitch); + } + } + } else { + // if channel is allocated but sound has stopped, + // free it + StopChannel(cnum); + } + } + } + // kill music if it is a single-play && finished + // if ( mus_playing + // && !I_QrySongPlaying(mus_playing->handle) + // && !mus_paused ) + // S_StopMusic(); + } + + public void SetMusicVolume(int volume) { + if (volume < 0 || volume > 127) { + DS.doomSystem.Error("Attempt to set music volume at %d", + volume); + } + + IMUS.SetMusicVolume(volume); + snd_MusicVolume = volume; + } + + public void SetSfxVolume(int volume) { + + if (volume < 0 || volume > 127) { + DS.doomSystem.Error("Attempt to set sfx volume at %d", volume); + } + + snd_SfxVolume = volume; + + } + + // + // Starts some music with the music id found in sounds.h. + // + public void StartMusic(int m_id) { + ChangeMusic(m_id, false); + } + + // + // Starts some music with the music id found in sounds.h. + // + public void StartMusic(musicenum_t m_id) { + ChangeMusic(m_id.ordinal(), false); + } + + public void ChangeMusic(musicenum_t musicnum, + boolean looping) { + ChangeMusic(musicnum.ordinal(), false); + } + + public void + ChangeMusic(int musicnum, + boolean looping) { + musicinfo_t music = null; + String namebuf; + + if ((musicnum <= musicenum_t.mus_None.ordinal()) + || (musicnum >= musicenum_t.NUMMUSIC.ordinal())) { + + DS.doomSystem.Error("Bad music number %d", musicnum); + } else { + music = sounds.S_music[musicnum]; + } + + if (mus_playing == music) { + return; + } + + // shutdown old music + StopMusic(); + + // get lumpnum if neccessary + if (music.lumpnum == 0) { + namebuf = String.format("d_%s", music.name); + music.lumpnum = DS.wadLoader.GetNumForName(namebuf); + } + + // load & register it + music.data = DS.wadLoader.CacheLumpNumAsRawBytes(music.lumpnum, Defines.PU_MUSIC); + music.handle = IMUS.RegisterSong(music.data); + + // play it + IMUS.PlaySong(music.handle, looping); + SetMusicVolume(this.snd_MusicVolume); + + mus_playing = music; + } + + public void StopMusic() { + if (mus_playing != null) { + if (mus_paused) { + IMUS.ResumeSong(mus_playing.handle); + } + + IMUS.StopSong(mus_playing.handle); + IMUS.UnRegisterSong(mus_playing.handle); + //Z_ChangeTag(mus_playing->data, PU_CACHE); + + mus_playing.data = null; + mus_playing = null; + } + } + + /** This is S_StopChannel. There's another StopChannel + * with a similar contract in ISound. Don't confuse the two. + * + * + * + * @param cnum + */ + protected void StopChannel(int cnum) { + + int i; + channel_t c = channels[cnum]; + + // Is it playing? + if (c.sfxinfo != null) { + // stop the sound playing + if (ISND.SoundIsPlaying(c.handle)) { + /*#ifdef SAWDEBUG if (c.sfxinfo == &S_sfx[sfx_sawful]) fprintf(stderr, "stopped\n"); #endif*/ - ISND.StopSound(c.handle); - } - - // check to see - // if other channels are playing the sound - for (i=0 ; i>1); - - if (DS.gamemap != 8 - && approx_dist > S_CLIPPING_DIST) - { - return false; - } - - // angle of source to listener - angle = rr.RendererState.PointToAngle(listener.x, - listener.y, - source.getX(), - source.getY()); - - if (angle > listener.angle) - angle = angle - listener.angle; - else - angle = angle + (0xffffffffL - listener.angle&BITS32); - - angle&=BITS32; - angle >>= ANGLETOFINESHIFT; - - // stereo separation - vps.sep = 128 - (FixedMul(S_STEREO_SWING,finesine[(int) angle])>>FRACBITS); - - // volume calculation - if (approx_dist < S_CLOSE_DIST) - { - vps.volume = snd_SfxVolume; - } - else if (DS.gamemap == 8) - { - if (approx_dist > S_CLIPPING_DIST) - approx_dist = S_CLIPPING_DIST; - - vps.volume = 15+ ((snd_SfxVolume-15) - *((S_CLIPPING_DIST - approx_dist)>>FRACBITS)) - / S_ATTENUATOR; - } - else - { - // distance effect - vps.volume = (snd_SfxVolume - * ((S_CLIPPING_DIST - approx_dist)>>FRACBITS)) - / S_ATTENUATOR; - // Let's do some maths here: S_CLIPPING_DIST-approx_dist - // can be at most 0x04100000. shifting left means 0x0410, - // or 1040 in decimal. - // The unmultiplied max volume is 15, attenuator is 1040. - // So snd_SfxVolume should be 0-127. - - } - - // MAES: pitch calculation for doppler effects. Nothing to write - // home about. - - /* + ISND.StopSound(c.handle); + } + + // check to see + // if other channels are playing the sound + for (i = 0; i < numChannels; i++) { + if (cnum != i + && c.sfxinfo == channels[i].sfxinfo) { + break; + } + } + + // degrade usefulness of sound data + c.sfxinfo.usefulness--; + + c.sfxinfo = null; + } + } + + // + // Changes volume, stereo-separation, and pitch variables + // from the norm of a sound effect to be played. + // If the sound is not audible, returns a 0. + // Otherwise, modifies parameters and returns 1. + // + protected boolean + AdjustSoundParams(mobj_t listener, + ISoundOrigin source, + vps_t vps) { + int approx_dist; + int adx; + int ady; + long angle; + + // calculate the distance to sound origin + // and clip it if necessary + adx = Math.abs(listener.x - source.getX()); + ady = Math.abs(listener.y - source.getY()); + + // From _GG1_ p.428. Appox. eucledian distance fast. + approx_dist = adx + ady - ((adx < ady ? adx : ady) >> 1); + + if (DS.gamemap != 8 + && approx_dist > S_CLIPPING_DIST) { + return false; + } + + // angle of source to listener + angle = rr.RendererState.PointToAngle(listener.x, + listener.y, + source.getX(), + source.getY()); + + if (angle > listener.angle) { + angle = angle - listener.angle; + } else { + angle = angle + (0xffffffffL - listener.angle & BITS32); + } + + angle &= BITS32; + angle >>= ANGLETOFINESHIFT; + + // stereo separation + vps.sep = 128 - (FixedMul(S_STEREO_SWING, finesine[(int) angle]) >> FRACBITS); + + // volume calculation + if (approx_dist < S_CLOSE_DIST) { + vps.volume = snd_SfxVolume; + } else if (DS.gamemap == 8) { + if (approx_dist > S_CLIPPING_DIST) { + approx_dist = S_CLIPPING_DIST; + } + + vps.volume = 15 + ((snd_SfxVolume - 15) + * ((S_CLIPPING_DIST - approx_dist) >> FRACBITS)) + / S_ATTENUATOR; + } else { + // distance effect + vps.volume = (snd_SfxVolume + * ((S_CLIPPING_DIST - approx_dist) >> FRACBITS)) + / S_ATTENUATOR; + // Let's do some maths here: S_CLIPPING_DIST-approx_dist + // can be at most 0x04100000. shifting left means 0x0410, + // or 1040 in decimal. + // The unmultiplied max volume is 15, attenuator is 1040. + // So snd_SfxVolume should be 0-127. + + } + + // MAES: pitch calculation for doppler effects. Nothing to write + // home about. + /* // calculate the relative speed between source and sound origin. // and clip it if necessary @@ -819,83 +753,72 @@ else if (DS.gamemap == 8) if (vps.pitch<0) vps.pitch=0; if (vps.pitch>255) vps.pitch=255; - */ - - return (vps.volume > 0); - } - - - - - // - // S_getChannel : - // If none available, return -1. Otherwise channel #. - // - protected int getChannel( ISoundOrigin origin,sfxinfo_t sfxinfo ) - { - // channel number to use - int cnum; - - channel_t c; - - // Find an open channel - // If it's null, OK, use that. - // If it's an origin-specific sound and has the same origin, override. - for (cnum=0 ; cnum= sfxinfo.priority) break; - - if (cnum == numChannels) - { - // FUCK! No lower priority. Sorry, Charlie. - return -1; - } - else - { - // Otherwise, kick out lower priority. - StopChannel(cnum); - } - } - - c = channels[cnum]; - - // channel is decided to be cnum. - c.sfxinfo = sfxinfo; - c.origin = origin; - - return cnum; - } - - /** Nice one. A sound should have a maximum duration in tics, - * and we can give it a handle proportional to the future tics - * it should play until. Ofc, this means the minimum timeframe - * for cutting a sound off is just 1 tic. - * - * @param handle - * @return - */ - - /* + */ + return (vps.volume > 0); + } + + // + // S_getChannel : + // If none available, return -1. Otherwise channel #. + // + protected int getChannel(ISoundOrigin origin, sfxinfo_t sfxinfo) { + // channel number to use + int cnum; + + channel_t c; + + // Find an open channel + // If it's null, OK, use that. + // If it's an origin-specific sound and has the same origin, override. + for (cnum = 0; cnum < numChannels; cnum++) { + if (channels[cnum].sfxinfo == null) { + break; + } else if (origin != null && channels[cnum].origin == origin) { + StopChannel(cnum); + break; + } + } + + // None available + if (cnum == numChannels) { + // Look for lower priority + for (cnum = 0; cnum < numChannels; cnum++) { + if (channels[cnum].sfxinfo.priority >= sfxinfo.priority) { + break; + } + } + + if (cnum == numChannels) { + // FUCK! No lower priority. Sorry, Charlie. + return -1; + } else { + // Otherwise, kick out lower priority. + StopChannel(cnum); + } + } + + c = channels[cnum]; + + // channel is decided to be cnum. + c.sfxinfo = sfxinfo; + c.origin = origin; + + return cnum; + } + + /** Nice one. A sound should have a maximum duration in tics, + * and we can give it a handle proportional to the future tics + * it should play until. Ofc, this means the minimum timeframe + * for cutting a sound off is just 1 tic. + * + * @param handle + * @return + */ + + /* public boolean SoundIsPlaying(int handle) { // Ouch. return (DS.gametic < handle); } */ - - - } diff --git a/src/s/AbstractSoundDriver.java b/src/s/AbstractSoundDriver.java index dcd0a8c3..5937f9bf 100644 --- a/src/s/AbstractSoundDriver.java +++ b/src/s/AbstractSoundDriver.java @@ -4,6 +4,9 @@ import data.sounds; import static data.sounds.S_sfx; import doom.DoomMain; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; /** * Functionality and fields that are common among the various "sound drivers" @@ -11,12 +14,13 @@ * * @author Maes */ - public abstract class AbstractSoundDriver implements ISoundDriver { + private static final Logger LOGGER = Loggers.getLogger(AbstractSoundDriver.class.getName()); + protected final static boolean D = false; // debug - - protected final DoomMain DM; + + protected final DoomMain DM; /** * The global mixing buffer. Basically, samples from all active internal @@ -27,9 +31,8 @@ public abstract class AbstractSoundDriver implements ISoundDriver { * Not all i * */ - protected byte[] mixbuffer;// = new byte[MIXBUFFERSIZE]; - + protected final int numChannels; /** The actual lengths of all sound effects. */ @@ -39,7 +42,6 @@ public abstract class AbstractSoundDriver implements ISoundDriver { * The sound in channel handles, determined on registration, might be used * to unregister/stop/modify, currently unused. */ - protected final int[] channelhandles; /** @@ -66,8 +68,7 @@ public abstract class AbstractSoundDriver implements ISoundDriver { // protected final static DataLine.Info info = new DataLine.Info(Clip.class, // format); - - public AbstractSoundDriver(DoomMain DM, int numChannels) { + public AbstractSoundDriver(DoomMain DM, int numChannels) { this.DM = DM; this.numChannels = numChannels; channelids = new int[numChannels]; @@ -79,11 +80,12 @@ public AbstractSoundDriver(DoomMain DM, int numChannels) { * Generates volume lookup tables which also turn the unsigned samples into * signed samples. */ - protected final void generateVolumeLUT() { - for (int i = 0; i < 128; i++) - for (int j = 0; j < 256; j++) + for (int i = 0; i < 128; i++) { + for (int j = 0; j < 256; j++) { vol_lookup[i][j] = (i * (j - 128) * 256) / 127; + } + } } /** @@ -95,11 +97,10 @@ protected final void generateVolumeLUT() { * @param steptablemid * @return */ - protected void generateStepTable(int steptablemid) { for (int i = -128; i < 128; i++) { - steptable[steptablemid + i] = - (int) (Math.pow(2.0, (i / 64.0)) * 65536.0); + steptable[steptablemid + i] + = (int) (Math.pow(2.0, (i / 64.0)) * 65536.0); //System.out.printf("Pitch %d %d %f\n",i,steptable[steptablemid + i],FixedFloat.toFloat(steptable[steptablemid + i])); } } @@ -112,7 +113,6 @@ protected void generateStepTable(int steptablemid) { * @param index * @return */ - protected byte[] getsfx(String sfxname, int[] len, int index) { byte[] sfx; byte[] paddedsfx; @@ -136,30 +136,30 @@ protected byte[] getsfx(String sfxname, int[] len, int index) { // I do not do runtime patches to that // variable. Instead, we will use a // default sound for replacement. - if (DM.wadLoader.CheckNumForName(name) == -1) + if (DM.wadLoader.CheckNumForName(name) == -1) { sfxlump = DM.wadLoader.GetNumForName("dspistol"); - else + } else { sfxlump = DM.wadLoader.GetNumForName(name); + } + + DMXSound dmx = DM.wadLoader.CacheLumpNum(sfxlump, 0, DMXSound.class); - DMXSound dmx= DM.wadLoader.CacheLumpNum(sfxlump, 0, DMXSound.class); - // KRUDE - if (dmx.speed==SAMPLERATE/2){ + if (dmx.speed == SAMPLERATE / 2) { // Plain linear interpolation. - dmx.data=DSP.crudeResample(dmx.data,2); + dmx.data = DSP.crudeResample(dmx.data, 2); //DSP.filter(dmx.data,SAMPLERATE, SAMPLERATE/4); - dmx.datasize=dmx.data.length; - + dmx.datasize = dmx.data.length; + } - + sfx = dmx.data; // MAES: A-ha! So that's how they do it. // SOund effects are padded to the highest multiple integer of // the mixing buffer's size (with silence) - - paddedsize = - ((dmx.datasize + (SAMPLECOUNT - 1)) / SAMPLECOUNT) * SAMPLECOUNT; + paddedsize + = ((dmx.datasize + (SAMPLECOUNT - 1)) / SAMPLECOUNT) * SAMPLECOUNT; // Allocate from zone memory. paddedsfx = new byte[paddedsize]; @@ -169,13 +169,17 @@ protected byte[] getsfx(String sfxname, int[] len, int index) { System.arraycopy(sfx, 0, paddedsfx, 0, dmx.datasize); // Pad with silence (unsigned) - for (i = dmx.datasize; i < paddedsize; i++) + for (i = dmx.datasize; i < paddedsize; i++) { paddedsfx[i] = (byte) 127; + } // Remove the cached lump. DM.wadLoader.UnlockLumpNum(sfxlump); - if (D) System.out.printf("SFX %d name %s size %d speed %d padded to %d\n", index, S_sfx[index].name, dmx.datasize,dmx.speed,paddedsize); + if (D) { + LOGGER.log(Level.FINE, + String.format("SFX %d name %s size %d speed %d padded to %d", index, S_sfx[index].name, dmx.datasize, dmx.speed, paddedsize)); + } // Preserve padded length. len[index] = paddedsize; @@ -215,10 +219,11 @@ protected final byte[] getsfx16(String sfxname, int[] len, int index) { // I do not do runtime patches to that // variable. Instead, we will use a // default sound for replacement. - if (DM.wadLoader.CheckNumForName(name) == -1) + if (DM.wadLoader.CheckNumForName(name) == -1) { sfxlump = DM.wadLoader.GetNumForName("dspistol"); - else + } else { sfxlump = DM.wadLoader.GetNumForName(name); + } size = DM.wadLoader.LumpLength(sfxlump); @@ -226,7 +231,6 @@ protected final byte[] getsfx16(String sfxname, int[] len, int index) { // Size blown up to accommodate two channels and 16 bits. // Sampling rate stays the same. - paddedsize = (size - 8) * 2 * 2; // Allocate from zone memory. paddedsfx = new byte[paddedsize]; @@ -234,7 +238,6 @@ protected final byte[] getsfx16(String sfxname, int[] len, int index) { // Skip first 8 bytes (header), blow up the data // to stereo, BIG ENDIAN, SIGNED, 16 bit. Don't expect any fancy DSP // here! - int sample = 0; for (i = 8; i < size; i++) { // final short sam=(short) vol_lookup[127][0xFF&sfx[i]]; @@ -265,17 +268,15 @@ protected final byte[] getsfx16(String sfxname, int[] len, int index) { * (e.g. classic mixer uses it, but AudioLine-based implementations are not * guaranteed. */ - @Override public int StartSound(int id, int vol, int sep, int pitch, int priority) { - if (id < 1 || id > S_sfx.length - 1) + if (id < 1 || id > S_sfx.length - 1) { return BUSY_HANDLE; - + } // Find a free channel and get a timestamp/handle for the new sound. - int handle = this.addsfx(id, vol, steptable[pitch], sep); - return handle; + return this.addsfx(id, vol, steptable[pitch], sep); } /** @@ -289,7 +290,6 @@ public int StartSound(int id, int vol, int sep, int pitch, int priority) { * @param seperation * @return */ - protected abstract int addsfx(int sfxid, int volume, int step, int seperation); @@ -302,14 +302,15 @@ protected abstract int addsfx(int sfxid, int volume, int step, public final int GetSfxLumpNum(sfxinfo_t sfx) { String namebuf; namebuf = String.format("ds%s", sfx.name).toUpperCase(); - if (namebuf.equals("DSNONE")) + if (namebuf.equals("DSNONE")) { return -1; + } int lump; try { lump = DM.wadLoader.GetNumForName(namebuf); } catch (Exception e) { - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "GetSfxLumpNum failure", e); return -1; } @@ -321,34 +322,32 @@ public final int GetSfxLumpNum(sfxinfo_t sfx) { * * @return */ - protected final void initMixBuffer() { + protected final void initMixBuffer() { for (int i = 0; i < MIXBUFFERSIZE; i += 4) { - mixbuffer[i] = - (byte) (((int) (0x7FFF * Math.sin(1.5 * Math.PI * (double) i - / MIXBUFFERSIZE)) & 0xff00) >>> 8); - mixbuffer[i + 1] = - (byte) ((int) (0x7FFF * Math.sin(1.5 * Math.PI * (double) i - / MIXBUFFERSIZE)) & 0xff); - mixbuffer[i + 2] = - (byte) (((int) (0x7FFF * Math.sin(1.5 * Math.PI * (double) i - / MIXBUFFERSIZE)) & 0xff00) >>> 8); - mixbuffer[i + 3] = - (byte) ((int) (0x7FFF * Math.sin(1.5 * Math.PI * (double) i - / MIXBUFFERSIZE)) & 0xff); + mixbuffer[i] + = (byte) (((int) (0x7FFF * Math.sin(1.5 * Math.PI * (double) i + / MIXBUFFERSIZE)) & 0xff00) >>> 8); + mixbuffer[i + 1] + = (byte) ((int) (0x7FFF * Math.sin(1.5 * Math.PI * (double) i + / MIXBUFFERSIZE)) & 0xff); + mixbuffer[i + 2] + = (byte) (((int) (0x7FFF * Math.sin(1.5 * Math.PI * (double) i + / MIXBUFFERSIZE)) & 0xff00) >>> 8); + mixbuffer[i + 3] + = (byte) ((int) (0x7FFF * Math.sin(1.5 * Math.PI * (double) i + / MIXBUFFERSIZE)) & 0xff); } } - + /** * Loads samples in 8-bit format, forcibly converts them to the common sampling rate. * Used by. */ - protected final void initSound8() { int i; // Initialize external data (all sounds) at start, keep static. - for (i = 1; i < NUMSFX; i++) { // Alias? Example is the chaingun sound linked to pistol. if (sounds.S_sfx[i].link == null) { @@ -368,12 +367,10 @@ protected final void initSound8() { * Only used by the Clip and David "drivers". * */ - protected final void initSound16() { int i; // Initialize external data (all sounds) at start, keep static. - for (i = 1; i < NUMSFX; i++) { // Alias? Example is the chaingun sound linked to pistol. if (sounds.S_sfx[i].link == null) { diff --git a/src/s/AudioChunk.java b/src/s/AudioChunk.java index dcf0e421..bccbfcd6 100644 --- a/src/s/AudioChunk.java +++ b/src/s/AudioChunk.java @@ -1,21 +1,21 @@ package s; -public class AudioChunk{ +public class AudioChunk { + public AudioChunk() { - buffer=new byte[s.ISoundDriver.MIXBUFFERSIZE]; - setStuff(0,0); - this.free=true; + buffer = new byte[s.ISoundDriver.MIXBUFFERSIZE]; + setStuff(0, 0); + this.free = true; } - - public void setStuff(int chunk, int time){ + + public void setStuff(int chunk, int time) { this.chunk = chunk; this.time = time; } - + public int chunk; public int time; public byte[] buffer; public boolean free; - -} \ No newline at end of file +} diff --git a/src/s/ClassicDoomSoundDriver.java b/src/s/ClassicDoomSoundDriver.java index 92a52932..a2518bef 100644 --- a/src/s/ClassicDoomSoundDriver.java +++ b/src/s/ClassicDoomSoundDriver.java @@ -6,10 +6,13 @@ import java.util.HashMap; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Semaphore; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.SourceDataLine; +import mochadoom.Loggers; import pooling.AudioChunkPool; /** @@ -26,9 +29,9 @@ * * @author Maes */ +public class ClassicDoomSoundDriver extends AbstractSoundDriver { -public class ClassicDoomSoundDriver extends AbstractSoundDriver - { + private static final Logger LOGGER = Loggers.getLogger(ClassicDoomSoundDriver.class.getName()); protected final Semaphore produce; @@ -38,15 +41,14 @@ public class ClassicDoomSoundDriver extends AbstractSoundDriver // protected FileOutputStream fos; // protected DataOutputStream dao; - // The one and only line protected SourceDataLine line = null; - protected HashMap cachedSounds = - new HashMap(); + protected HashMap cachedSounds + = new HashMap<>(); - public ClassicDoomSoundDriver(DoomMain DM, int numChannels) { - super(DM,numChannels); + public ClassicDoomSoundDriver(DoomMain DM, int numChannels) { + super(DM, numChannels); channelleftvol_lookup = new int[numChannels][]; channelrightvol_lookup = new int[numChannels][]; channelstep = new int[numChannels]; @@ -57,7 +59,7 @@ public ClassicDoomSoundDriver(DoomMain DM, int numChannels) { produce = new Semaphore(1); consume = new Semaphore(1); produce.drainPermits(); - mixbuffer= new byte[MIXBUFFERSIZE]; + mixbuffer = new byte[MIXBUFFERSIZE]; } /** The channel step amount... */ @@ -99,7 +101,6 @@ public ClassicDoomSoundDriver(DoomMain DM, int numChannels) { * hardware channels (left and right, that is). This function currently * supports only 16bit. */ - public void UpdateSound() { mixed = false; @@ -112,7 +113,6 @@ public void UpdateSound() { // Pointers in global mixbuffer, left, right, end. // Maes: those were explicitly signed short pointers... - int leftout; int rightout; int leftend; @@ -136,15 +136,15 @@ public void UpdateSound() { leftend = SAMPLECOUNT * step; for (chan = 0; chan < numChannels; chan++) { - if (channels[chan] != null) - // SOME mixing has taken place. + if (channels[chan] != null) // SOME mixing has taken place. + { mixed = true; + } } // Mix sounds into the mixing buffer. // Loop over step*SAMPLECOUNT, // that is SAMPLECOUNT values for two channels. - while (leftout < leftend) { // Reset left/right value. dl = 0; @@ -153,7 +153,6 @@ public void UpdateSound() { // Love thy L2 chache - made this a loop. // Now more channels could be set at compile time // as well. Thus loop those channels. - for (chan = 0; chan < numChannels; chan++) { // if (D) System.err.printf("Checking channel %d\n",chan); @@ -164,15 +163,14 @@ public void UpdateSound() { // Get the raw data from the channel. // Maes: this is supposed to be an 8-bit unsigned value. - sample = 0x00FF & channels[chan][channel_pointer]; - + sample = 0x00FF & channels[chan][channel_pointer]; + // Add left and right part for this channel (sound) // to the current data. Adjust volume accordingly. // Q: could this be optimized by converting samples to 16-bit // at load time, while also allowing for stereo samples? // A: Only for the stereo part. You would still look a lookup // for the CURRENT volume level. - dl += channelleftvol_lookup[chan][sample]; dr += channelrightvol_lookup[chan][sample]; @@ -192,19 +190,18 @@ public void UpdateSound() { // Check whether we are done. Also to avoid overflows. if (channel_pointer >= channelsend[chan]) { // Reset pointer for a channel. - if (D) - System.err - .printf( - "Channel %d handle %d pointer %d thus done, stopping\n", - chan, this.channelhandles[chan], - channel_pointer); + if (D) { + LOGGER.log(Level.INFO, String.format( + "Channel %d handle %d pointer %d thus done, stopping", + chan, this.channelhandles[chan], + channel_pointer)); + } channels[chan] = null; channel_pointer = 0; } // Write pointer back, so we know where a certain channel // is the next time UpdateSounds is called. - p_channels[chan] = channel_pointer; } @@ -213,28 +210,28 @@ public void UpdateSound() { // MAES: at this point, the actual values for a single sample // (YIKES!) are in d1 and d2. We must use the leftout/rightout // pointers to write them back into the mixbuffer. - // Clamp to range. Left hardware channel. // Remnant of 8-bit mixing code? That must have raped ears // and made them bleed. // if (dl > 127) *leftout = 127; // else if (dl < -128) *leftout = -128; // else *leftout = dl; - - if (dl > 0x7fff) + if (dl > 0x7fff) { dl = 0x7fff; - else if (dl < -0x8000) + } else if (dl < -0x8000) { dl = -0x8000; + } // Write left channel mixbuffer[leftout] = (byte) ((dl & 0xFF00) >>> 8); mixbuffer[leftout + 1] = (byte) (dl & 0x00FF); // Same for right hardware channel. - if (dr > 0x7fff) + if (dr > 0x7fff) { dr = 0x7fff; - else if (dr < -0x8000) + } else if (dr < -0x8000) { dr = -0x8000; + } // Write right channel. mixbuffer[rightout] = (byte) ((dr & 0xFF00) >>> 8); @@ -252,7 +249,6 @@ else if (dr < -0x8000) // Q: what's the purpose of channelremainder etc? // A: pitch variations were done with fractional pointers 16.16 // style. - } /** @@ -260,7 +256,6 @@ else if (dr < -0x8000) * the old DPMS based DOS version, this were simply dummies in the Linux * version. See soundserver initdata(). */ - @Override public void SetChannels(int numChannels) { // Init internal lookups (raw data, mixing buffer, channels). @@ -273,12 +268,12 @@ public void SetChannels(int numChannels) { for (int i = 0; i < this.numChannels; i++) { channels[i] = null; } - + generateStepTable(steptablemid); generateVolumeLUT(); } - + protected MixServer SOUNDSRV; protected Thread SOUNDTHREAD; @@ -287,7 +282,7 @@ public void SetChannels(int numChannels) { public boolean InitSound() { // Secure and configure sound device first. - System.out.println("I_InitSound: "); + LOGGER.log(Level.INFO, "I_InitSound"); // We only need a single data line. // PCM, signed, 16-bit, stereo, 22025 KHz, 2048 bytes per "frame", @@ -298,20 +293,19 @@ public boolean InitSound() { if (AudioSystem.isLineSupported(info)) try { - line = (SourceDataLine) AudioSystem.getSourceDataLine(format); - line.open(format,AUDIOLINE_BUFFER); - } catch (Exception e) { - e.printStackTrace(); - System.err.print("Could not play signed 16 data\n"); - return false; - } + line = (SourceDataLine) AudioSystem.getSourceDataLine(format); + line.open(format, AUDIOLINE_BUFFER); + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "Could not play signed 16 data", e); + return false; + } if (line != null) { - System.err.print(" configured audio device\n"); + LOGGER.log(Level.INFO, "configured audio device"); line.start(); } else { - System.err.print(" could not configure audio device\n"); - return false; + LOGGER.log(Level.SEVERE, "could not configure audio device"); + return false; } // This was here only for debugging purposes @@ -320,28 +314,26 @@ public boolean InitSound() { * DataOutputStream(fos); } catch (FileNotFoundException e) { * Auto-generated catch block e.printStackTrace(); } */ - SOUNDSRV = new MixServer(line); SOUNDTHREAD = new Thread(SOUNDSRV); SOUNDTHREAD.start(); // Initialize external data (all sounds) at start, keep static. - System.err.print("I_InitSound: "); + LOGGER.log(Level.INFO, "I_InitSound"); super.initSound8(); - System.err.print(" pre-cached all sound data\n"); + LOGGER.log(Level.INFO, "pre-cached all sound data"); // Now initialize mixbuffer with zero. initMixBuffer(); // Finished initialization. - System.err.print("I_InitSound: sound module ready\n"); + LOGGER.log(Level.INFO, "I_InitSound: sound module ready"); return true; } - @Override protected int addsfx(int sfxid, int volume, int step, int seperation) { int i; @@ -354,8 +346,8 @@ protected int addsfx(int sfxid, int volume, int step, int seperation) { int rightvol; int leftvol; - int broken=-1; - + int broken = -1; + // Chainsaw troubles. // Play these sound effects only one at a time. if ((sfxid >= sfxenum_t.sfx_sawup.ordinal() @@ -368,37 +360,38 @@ protected int addsfx(int sfxid, int volume, int step, int seperation) { if ((channels[i] != null) && (channelids[i] == sfxid)) { // Reset. this.p_channels[i] = 0; - this.channels[i]=null; + this.channels[i] = null; // We are sure that iff, // there will only be one. - broken=i; + broken = i; break; } } } // Loop all channels to find oldest SFX. - if (broken>=0) { - i=broken; - oldestnum=broken; - } - else - for (i = 0; (i < numChannels) && (channels[i] != null); i++) { - if (channelstart[i] < oldest) { - oldestnum = i; + if (broken >= 0) { + i = broken; + oldestnum = broken; + } else { + for (i = 0; (i < numChannels) && (channels[i] != null); i++) { + if (channelstart[i] < oldest) { + oldestnum = i; + } } } oldest = channelstart[oldestnum]; - + // Tales from the cryptic. // If we found a channel, fine. // If not, we simply overwrite the first one, 0. // Probably only happens at startup. - if (i == numChannels) + if (i == numChannels) { slot = oldestnum; - else + } else { slot = i; + } // Okay, in the less recent channel, // we will handle the new SFX. @@ -413,7 +406,9 @@ protected int addsfx(int sfxid, int volume, int step, int seperation) { // Reset current handle number, limited to 0..100. if (handlenums == 0) // was !handlenums, so it's actually 1...100? + { handlenums = 100; + } // Assign current handle number. // Preserved so sounds could be stopped (unused). @@ -443,11 +438,18 @@ protected int addsfx(int sfxid, int volume, int step, int seperation) { // Sanity check, clamp volume. // Maes: better to clamp than to crash, no? - - if (rightvol < 0) rightvol=0; - if (rightvol >127) rightvol=127; - if (leftvol < 0) leftvol=0; - if (leftvol >127) leftvol=127; + if (rightvol < 0) { + rightvol = 0; + } + if (rightvol > 127) { + rightvol = 127; + } + if (leftvol < 0) { + leftvol = 0; + } + if (leftvol > 127) { + leftvol = 127; + } // Get the proper lookup table piece // for this volume level??? @@ -458,10 +460,14 @@ protected int addsfx(int sfxid, int volume, int step, int seperation) { // e.g. for avoiding duplicates of chainsaw. channelids[slot] = sfxid; - if (D) System.err.println(channelStatus()); - if (D) System.err.printf( - "Playing sfxid %d handle %d length %d vol %d on channel %d\n", - sfxid, rc, S_sfx[sfxid].data.length, volume, slot); + if (D) { + LOGGER.log(Level.FINE, String.valueOf(channelStatus())); + } + if (D) { + LOGGER.log(Level.FINE, String.format( + "Playing sfxid %d handle %d length %d vol %d on channel %d", + sfxid, rc, S_sfx[sfxid].data.length, volume, slot)); + } // You tell me. return rc; @@ -482,11 +488,11 @@ public void ShutdownSound() { } // System.err.printf("%d channels died off\n",i); - UpdateSound(); SubmitSound(); - if (i == numChannels) + if (i == numChannels) { done = true; + } } this.line.drain(); @@ -496,7 +502,7 @@ public void ShutdownSound() { try { SOUNDTHREAD.join(); } catch (InterruptedException e) { - // Well, I don't care. + // Well, I don't care. } line.close(); @@ -513,8 +519,8 @@ public MixServer(SourceDataLine line) { private SourceDataLine auline; - private ArrayBlockingQueue audiochunks = - new ArrayBlockingQueue(BUFFER_CHUNKS * 2); + private ArrayBlockingQueue audiochunks + = new ArrayBlockingQueue<>(BUFFER_CHUNKS * 2); public void addChunk(AudioChunk chunk) { audiochunks.offer(chunk); @@ -527,28 +533,24 @@ public void run() { while (!terminate) { // while (timing[mixstate]<=mytime){ - // Try acquiring a produce permit before going on. - try { // System.err.println("Waiting for a permit..."); produce.acquire(); // System.err.println("Got a permit"); } catch (InterruptedException e) { // Well, ouch. - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "MixServer run failure", e); } int chunks = 0; // System.err.printf("Audio queue has %d chunks\n",audiochunks.size()); - // Play back only at most a given number of chunks once you reach // this spot - - int atMost=Math.min(ISoundDriver.BUFFER_CHUNKS,audiochunks.size()); - - while (atMost-->0){ + int atMost = Math.min(ISoundDriver.BUFFER_CHUNKS, audiochunks.size()); + + while (atMost-- > 0) { AudioChunk chunk = null; try { @@ -566,7 +568,6 @@ public void run() { // Signal that we consumed a whole buffer and we are ready for // another one. - consume.release(); } } @@ -589,8 +590,9 @@ public boolean SoundIsPlaying(int handle) { protected int getChannelFromHandle(int handle) { // Which channel has it? for (int i = 0; i < numChannels; i++) { - if (channelhandles[i] == handle) + if (channelhandles[i] == handle) { return i; + } } return BUSY_HANDLE; @@ -613,13 +615,12 @@ public void SubmitSound() { // It's possible for us to stay silent and give the audio // queue a chance to get drained. if (mixed) { - silence=0; + silence = 0; AudioChunk gunk = audiochunkpool.checkOut(); // Ha ha you're ass is mine! gunk.free = false; // System.err.printf("Submitted sound chunk %d to buffer %d \n",chunk,mixstate); - // Copy the currently mixed chunk into its position inside the // master buffer. System.arraycopy(mixbuffer, 0, gunk.buffer, 0, MIXBUFFERSIZE); @@ -627,28 +628,28 @@ public void SubmitSound() { this.SOUNDSRV.addChunk(gunk); // System.err.println(chunk++); - chunk++; // System.err.println(chunk); - if (consume.tryAcquire()) + if (consume.tryAcquire()) { produce.release(); + } } else { silence++; // MAES: attempt to fix lingering noise error - if (silence >ISoundDriver.BUFFER_CHUNKS*5){ + if (silence > ISoundDriver.BUFFER_CHUNKS * 5) { line.flush(); - silence=0; - } + silence = 0; + } // System.err.println("SILENT_CHUNK"); // this.SOUNDSRV.addChunk(SILENT_CHUNK); } // line.write(mixbuffer, 0, mixbuffer.length); } - - private int silence=0; + + private int silence = 0; @Override public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { @@ -662,12 +663,13 @@ public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { int rightvol = vol - ((vol * sep * sep) >> 16); // Sanity check, clamp volume. - - if (rightvol < 0 || rightvol > 127) + if (rightvol < 0 || rightvol > 127) { DM.doomSystem.Error("rightvol out of bounds"); + } - if (leftvol < 0 || leftvol > 127) + if (leftvol < 0 || leftvol > 127) { DM.doomSystem.Error("leftvol out of bounds"); + } // Get the proper lookup table piece // for this volume level??? @@ -685,10 +687,11 @@ public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { public String channelStatus() { sb.setLength(0); for (int i = 0; i < numChannels; i++) { - if (channels[i] != null) + if (channels[i] != null) { sb.append(i); - else + } else { sb.append('-'); + } } return sb.toString(); diff --git a/src/s/ClipSFXModule.java b/src/s/ClipSFXModule.java index 6117cbc4..e800e93e 100644 --- a/src/s/ClipSFXModule.java +++ b/src/s/ClipSFXModule.java @@ -5,12 +5,15 @@ import doom.DoomMain; import java.util.Collection; import java.util.HashMap; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; import javax.sound.sampled.FloatControl; import javax.sound.sampled.FloatControl.Type; import javax.sound.sampled.LineUnavailableException; +import mochadoom.Loggers; /** Experimental Clip based driver. It does work, but it has no * tangible advantages over the Audioline or Classic one. If the @@ -31,444 +34,426 @@ * @author Velktron * */ +public class ClipSFXModule extends AbstractSoundDriver { + + private static final Logger LOGGER = Loggers.getLogger(ClipSFXModule.class.getName()); + + HashMap cachedSounds = new HashMap<>(); + + // Either it's null (no clip is playing) or non-null (some clip is playing). + Clip[] channels; + + public final float[] linear2db; + + public ClipSFXModule(DoomMain DM, int numChannels) { + super(DM, numChannels); + linear2db = computeLinear2DB(); + } -public class ClipSFXModule extends AbstractSoundDriver{ - - HashMap cachedSounds = new HashMap(); - - - // Either it's null (no clip is playing) or non-null (some clip is playing). - Clip[] channels; - - - public final float[] linear2db; - - public ClipSFXModule(DoomMain DM, int numChannels) { - super(DM,numChannels); - linear2db=computeLinear2DB(); - } - private float[] computeLinear2DB() { - - // Maximum volume is 0 db, minimum is ... -96 db. - // We rig this so that half-scale actually gives quarter power, - // and so is -6 dB. - float[] tmp=new float[VOLUME_STEPS]; - - for (int i=0;i> 8)); + paddedsfx[sample++] = (byte) (0xFF & sam); + paddedsfx[sample++] = (byte) (0xFF & (sam >> 8)); + paddedsfx[sample++] = (byte) (0xFF & sam); + } + + // Remove the cached lump. + DM.wadLoader.UnlockLumpNum(sfxlump); + + // Return allocated padded data. + // So the first 8 bytes are useless? + return paddedsfx; + } + + @Override + public void UpdateSound() { + // We do nothing here, since the mixing is delegated to the OS + // Just hope that it's more efficient that our own... + + } + + @Override + public void SubmitSound() { + // Dummy. Nothing actual to do here. + + } + + @Override + public void ShutdownSound() { + // Wait till all pending sounds are finished. + boolean done = false; + int i; + + // FIXME (below). + //fprintf( stderr, "I_ShutdownSound: NOT finishing pending sounds\n"); + //fflush( stderr ); + while (!done) { + for (i = 0; i < numChannels && ((channels[i] == null) || (!channels[i].isActive())); i++); + // FIXME. No proper channel output. + if (i == numChannels) { + done = true; + } + } + + for (i = 0; i < numChannels; i++) { + if (channels[i] != null) { + channels[i].close(); + } + } + + // Free up resources taken up by cached clips. + Collection clips = this.cachedSounds.values(); + for (Clip c : clips) { + c.close(); + } + // Done. + + } + + @Override + public void SetChannels(int numChannels) { + channels = new Clip[numChannels]; + } + + private final void getClipForChannel(int c, int sfxid) { + + // Try to see if we already have such a clip. + Clip clip = this.cachedSounds.get(sfxid); + + boolean exists = false; + + // Does it exist? + if (clip != null) { + + // Well, it does, but we are not done yet. + exists = true; + // Is it NOT playing already? + if (!clip.isActive()) { + // Assign it to the channel. + channels[c] = clip; + return; + } + } + + // Sorry, Charlie. Gotta make a new one. + DataLine.Info info = new DataLine.Info(Clip.class, DoomSound.DEFAULT_SAMPLES_FORMAT); + + try { + clip = (Clip) AudioSystem.getLine(info); + } catch (LineUnavailableException e) { + LOGGER.log(Level.SEVERE, "Line unavailable", e); + } + try { + clip.open(DoomSound.DEFAULT_SAMPLES_FORMAT, S_sfx[sfxid].data, 0, S_sfx[sfxid].data.length); + } catch (LineUnavailableException e) { + LOGGER.log(Level.SEVERE, "Line unavailable", e); + } + + if (!exists) { + this.cachedSounds.put(sfxid, clip); + } + + channels[c] = clip; + + // Control[] cs=clip.getControls(); + // + // for (Control cc:cs){ + // System.out.println("Control "+cc.getType().toString()); + // } + } + + // + // This function adds a sound to the + // list of currently active sounds, + // which is maintained as a given number + // (eight, usually) of internal channels. + // Returns a handle. + // + protected short handlenums = 0; + + protected int addsfx(int sfxid, int volume, int pitch, int seperation) { + int i; + int rc = -1; + + int oldest = DM.gametic; + int oldestnum = 0; + int slot; + + // Chainsaw troubles. + // Play these sound effects only one at a time. + if (sfxid == sfxenum_t.sfx_sawup.ordinal() + || sfxid == sfxenum_t.sfx_sawidl.ordinal() + || sfxid == sfxenum_t.sfx_sawful.ordinal() + || sfxid == sfxenum_t.sfx_sawhit.ordinal() + || sfxid == sfxenum_t.sfx_stnmov.ordinal() + || sfxid == sfxenum_t.sfx_pistol.ordinal()) { + // Loop all channels, check. + for (i = 0; i < numChannels; i++) { + // Active, and using the same SFX? + if (channels[i] != null && channels[i].isRunning() + && channelids[i] == sfxid) { + // Reset. + channels[i].stop(); + // We are sure that iff, + // there will only be one. + break; + } + } + } + + // Loop all channels to find oldest SFX. + for (i = 0; (i < numChannels) && (channels[i] != null); i++) { + if (channelstart[i] < oldest) { + oldestnum = i; + oldest = channelstart[i]; + } + } + + // Tales from the cryptic. + // If we found a channel, fine. + // If not, we simply overwrite the first one, 0. + // Probably only happens at startup. + if (i == numChannels) { + slot = oldestnum; + } else { + slot = i; + } + + // Okay, in the less recent channel, + // we will handle the new SFX. + // We need to decide whether we can reuse an existing clip + // or create a new one. In any case, when this method return + // we should have a valid clip assigned to channel "slot". + getClipForChannel(slot, sfxid); + + // Reset current handle number, limited to 0..100. + if (handlenums == 0) // was !handlenums, so it's actually 1...100? + { + handlenums = MAXHANDLES; + } + + // Assign current handle number. + // Preserved so sounds could be stopped (unused). + channelhandles[slot] = rc = handlenums--; + + // Should be gametic, I presume. + channelstart[slot] = DM.gametic; + + // Get the proper lookup table piece + // for this volume level??? + //channelleftvol_lookup[slot] = vol_lookup[leftvol]; + //channelrightvol_lookup[slot] = vol_lookup[rightvol]; + // Preserve sound SFX id, + // e.g. for avoiding duplicates of chainsaw. + channelids[slot] = sfxid; + + setVolume(slot, volume); + setPanning(slot, seperation); + //channels[slot].addSound(sound, handlenums); + //channels[slot].setPitch(pitch); + + if (D) { + LOGGER.log(Level.FINE, channelStatus()); + } + if (D) { + LOGGER.log(Level.FINE, String.format("Playing %d vol %d on channel %d\n", rc, volume, slot)); + } + // Well...play it. -/** Modified getsfx. The individual length of each sfx is not of interest. - * However, they must be transformed into 16-bit, signed, stereo samples - * beforehand, before being "fed" to the audio clips. - * - * @param sfxname - * @param index - * @return - */ - protected byte[] getsfx(String sfxname,int index) { - byte[] sfx; - byte[] paddedsfx; - int i; - int size; - int paddedsize; - String name; - int sfxlump; - - // Get the sound data from the WAD, allocate lump - // in zone memory. - name = String.format("ds%s", sfxname).toUpperCase(); - - // Now, there is a severe problem with the - // sound handling, in it is not (yet/anymore) - // gamemode aware. That means, sounds from - // DOOM II will be requested even with DOOM - // shareware. - // The sound list is wired into sounds.c, - // which sets the external variable. - // I do not do runtime patches to that - // variable. Instead, we will use a - // default sound for replacement. - if (DM.wadLoader.CheckNumForName(name) == -1) - sfxlump = DM.wadLoader.GetNumForName("dspistol"); - else - sfxlump = DM.wadLoader.GetNumForName(name); - - size = DM.wadLoader.LumpLength(sfxlump); - - sfx = DM.wadLoader.CacheLumpNumAsRawBytes(sfxlump, 0); - - // Size blown up to accommodate two channels and 16 bits. - // Sampling rate stays the same. - - paddedsize = (size-8)*2*2; - // Allocate from zone memory. - paddedsfx = new byte[paddedsize]; - - // Skip first 8 bytes (header), blow up the data - // to stereo, BIG ENDIAN, SIGNED, 16 bit. Don't expect any fancy DSP here! - - int sample=0; - for (i = 8; i < size; i++){ - // final short sam=(short) vol_lookup[127][0xFF&sfx[i]]; - final short sam=(short) ((0xFF&sfx[i]-128)<<8); - paddedsfx[sample++] = (byte) (0xFF&(sam>>8)); - paddedsfx[sample++]=(byte) (0xFF&sam); - paddedsfx[sample++]=(byte) (0xFF&(sam>>8)); - paddedsfx[sample++]=(byte) (0xFF&sam); - } - - // Remove the cached lump. - DM.wadLoader.UnlockLumpNum(sfxlump); - - // Return allocated padded data. - // So the first 8 bytes are useless? - return paddedsfx; - } - - @Override - public void UpdateSound() { - // We do nothing here, since the mixing is delegated to the OS - // Just hope that it's more efficient that our own... - - } - - @Override - public void SubmitSound() { - // Dummy. Nothing actual to do here. - - } - - @Override - public void ShutdownSound() { - // Wait till all pending sounds are finished. - boolean done = false; - int i; - - - // FIXME (below). - //fprintf( stderr, "I_ShutdownSound: NOT finishing pending sounds\n"); - //fflush( stderr ); - - while ( !done) - { - for( i=0 ; i clips=this.cachedSounds.values(); - for (Clip c:clips){ - c.close(); - } - - // Done. - return; - - } - - @Override - public void SetChannels(int numChannels) { - channels= new Clip[numChannels]; - } - - private final void getClipForChannel(int c, int sfxid){ - - // Try to see if we already have such a clip. - Clip clip=this.cachedSounds.get(sfxid); - - boolean exists=false; - - // Does it exist? - if (clip!=null){ - - // Well, it does, but we are not done yet. - exists=true; - // Is it NOT playing already? - if (!clip.isActive()){ - // Assign it to the channel. - channels[c]=clip; - return; - } - } - - // Sorry, Charlie. Gotta make a new one. - DataLine.Info info = new DataLine.Info(Clip.class, DoomSound.DEFAULT_SAMPLES_FORMAT); - - try { - clip = (Clip) AudioSystem.getLine(info); - } catch (LineUnavailableException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - try { - clip.open( DoomSound.DEFAULT_SAMPLES_FORMAT, S_sfx[sfxid].data, 0, S_sfx[sfxid].data.length); - } catch (LineUnavailableException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - if (!exists) - this.cachedSounds.put(sfxid,clip); - - channels[c]=clip; - - - // Control[] cs=clip.getControls(); - // - // for (Control cc:cs){ - // System.out.println("Control "+cc.getType().toString()); - // } - } - - // - // This function adds a sound to the - // list of currently active sounds, - // which is maintained as a given number - // (eight, usually) of internal channels. - // Returns a handle. - // - protected short handlenums = 0; - - protected int addsfx ( int sfxid,int volume,int pitch,int seperation) - { - int i; - int rc = -1; - - int oldest = DM.gametic; - int oldestnum = 0; - int slot; - - // Chainsaw troubles. - // Play these sound effects only one at a time. - if ( sfxid == sfxenum_t.sfx_sawup.ordinal() - || sfxid == sfxenum_t.sfx_sawidl.ordinal() - || sfxid == sfxenum_t.sfx_sawful.ordinal() - || sfxid == sfxenum_t.sfx_sawhit.ordinal() - || sfxid == sfxenum_t.sfx_stnmov.ordinal() - || sfxid == sfxenum_t.sfx_pistol.ordinal() ) - { - // Loop all channels, check. - for (i=0 ; i=0) { - channels[hnd].stop(); - channels[hnd]=null; - } - } - - @Override - public boolean SoundIsPlaying(int handle) { - - return getChannelFromHandle(handle)!=BUSY_HANDLE; - } - - - @Override - public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { - - // This should be called on sounds that are ALREADY playing. We really need - // to retrieve channels from their handles. - - //System.err.printf("Updating sound with handle %d vol %d sep %d pitch %d\n",handle,vol,sep,pitch); - - int i=getChannelFromHandle(handle); - // None has it? - if (i!=BUSY_HANDLE){ - //System.err.printf("Updating sound with handle %d in channel %d\n",handle,i); - setVolume(i,vol); - setPanning(i,sep); - //channels[i].setPanning(sep); - } - - } - - - /** Internal use. - * - * @param handle - * @return the channel that has the handle, or -2 if none has it. - */ - private int getChannelFromHandle(int handle){ - // Which channel has it? - for (int i=0;i= 0) { + channels[hnd].stop(); + channels[hnd] = null; + } + } + + @Override + public boolean SoundIsPlaying(int handle) { + return getChannelFromHandle(handle) != BUSY_HANDLE; + } + + @Override + public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { + + // This should be called on sounds that are ALREADY playing. We really need + // to retrieve channels from their handles. + //System.err.printf("Updating sound with handle %d vol %d sep %d pitch %d\n",handle,vol,sep,pitch); + int i = getChannelFromHandle(handle); + // None has it? + if (i != BUSY_HANDLE) { + //System.err.printf("Updating sound with handle %d in channel %d\n",handle,i); + setVolume(i, vol); + setPanning(i, sep); + //channels[i].setPanning(sep); + } + + } + + /** Internal use. + * + * @param handle + * @return the channel that has the handle, or -2 if none has it. + */ + private int getChannelFromHandle(int handle) { + // Which channel has it? + for (int i = 0; i < numChannels; i++) { + if (channelhandles[i] == handle) { + return i; + } + } + + return BUSY_HANDLE; + } + + StringBuilder sb = new StringBuilder(); + + public String channelStatus() { + sb.setLength(0); + for (int i = 0; i < numChannels; i++) { + if (channels[i] != null && channels[i].isActive()) { + sb.append(i); + } else { + sb.append('-'); + } + } + + return sb.toString(); + + } + +} diff --git a/src/s/DMXSound.java b/src/s/DMXSound.java index cba19fbb..8e48af04 100644 --- a/src/s/DMXSound.java +++ b/src/s/DMXSound.java @@ -4,35 +4,33 @@ import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; - import w.CacheableDoomObject; /** An object representation of Doom's sound format */ +public class DMXSound implements CacheableDoomObject { -public class DMXSound implements CacheableDoomObject{ - - /** ushort, all Doom samples are "type 3". No idea how */ + /** ushort, all Doom samples are "type 3". No idea how */ public int type; /** ushort, speed in Hz. */ - public int speed; + public int speed; /** uint */ public int datasize; public byte[] data; - + @Override public void unpack(ByteBuffer buf) throws IOException { - buf.order(ByteOrder.LITTLE_ENDIAN); - type=buf.getChar(); - speed=buf.getChar(); - try { - datasize = buf.getInt(); - } catch (BufferUnderflowException e) { - datasize = buf.capacity() - buf.position(); - } - data=new byte[Math.min(buf.remaining(),datasize)]; - buf.get(data); + buf.order(ByteOrder.LITTLE_ENDIAN); + type = buf.getChar(); + speed = buf.getChar(); + try { + datasize = buf.getInt(); + } catch (BufferUnderflowException e) { + datasize = buf.capacity() - buf.position(); + } + data = new byte[Math.min(buf.remaining(), datasize)]; + buf.get(data); } } diff --git a/src/s/DSP.java b/src/s/DSP.java index 81eb176d..e28a10d2 100644 --- a/src/s/DSP.java +++ b/src/s/DSP.java @@ -20,7 +20,6 @@ public class DSP { * = width of windowed Sinc used as the low pass filter rem resamp() * returns a filtered new sample point */ - public float resamp(float x, float[] indat, int alim, float fmax, float fsr, int wnwdth) { int i, j; @@ -31,13 +30,14 @@ public float resamp(float x, float[] indat, int alim, float fmax, for (i = -wnwdth / 2; i < wnwdth / 2; i++) { // For 1 window width j = (int) (x + i); // Calc input sample index // calculate von Hann Window. Scale and calculate Sinc - r_w = - (float) (0.5 - 0.5 * Math.cos(2 * Math.PI - * (0.5 + (j - x) / wnwdth))); + r_w + = (float) (0.5 - 0.5 * Math.cos(2 * Math.PI + * (0.5 + (j - x) / wnwdth))); r_a = (float) (2 * Math.PI * (j - x) * fmax / fsr); r_snc = 1; - if (Math.abs(r_a) > 0) + if (Math.abs(r_a) > 0) { r_snc = (int) (Math.sin(r_a) / r_a); + } if ((j >= 0) && (j < alim)) { r_y = (int) (r_y + r_g * r_w * r_snc * indat[j]); } @@ -53,7 +53,6 @@ public float resamp(float x, float[] indat, int alim, float fmax, * student. (consider this code Open Source under a BSD style license) IMHO. * YMMV. http://www.nicholson.com/rhn/dsp.html */ - /** * R. Nicholson's QDDS FIR filter generator cookbook recipe QDDS = Quick, * Dirty, Dumb and Short version 0.6b - 2006-Dec-14, 2007-Sep-30 No @@ -80,7 +79,6 @@ public float resamp(float x, float[] indat, int alim, float fmax, * a lowpass filter * @return array of FIR taps */ - public static double[] wsfiltgen(int nt, double fc, double fsr, double bw, double g) { double[] fir = new double[nt];// // fir(0) = 0 @@ -92,133 +90,131 @@ public static double[] wsfiltgen(int nt, double fc, double fsr, double bw, doubl for (int i = 1; i < nt; i++) { a = (i - nt / 2) * 2.0 * Math.PI * bw / fsr; // scale Sinc width ys = 1; - if (Math.abs(a) > 0) + if (Math.abs(a) > 0) { ys = Math.sin(a) / a; // calculate Sinc function + } yg = g * (4.0 * bw / fsr); // correct window gain yw = 0.54 - 0.46 * Math.cos(i * 2.0 * Math.PI / nt); // Hamming - // window + // window yf = Math.cos((i - nt / 2) * 2.0 * Math.PI * fc / fsr); // spectral - // shift to - // fc + // shift to + // fc fir[i] = yf * yw * yg * ys; // rem assign fir coeff. } return fir; } - - public static void main(String[] argv){ - double[] fir=wsfiltgen(128,11025/2.0,22050,22050*3.0/4,0.5); - System.out.println(fir); - + + public static void main(String[] argv) { + double[] fir = wsfiltgen(128, 11025 / 2.0, 22050, 22050 * 3.0 / 4, 0.5); + //System.out.println(fir); + } - - public static byte[] crudeResample(byte[] input,int factor){ - - if (input==null || input.length<1) return null; - - final int LEN=input.length; - - byte[] res=new byte[LEN*factor]; - int k=0; - float start,end; - - res[0]=input[0]; - - for (int i=0;i cachedSounds = new ArrayList<>(); + + public final float[] linear2db; + + private SoundWorker[] channels; + private Thread[] soundThread; + + public DavidSFXModule(DoomMain DM, int numChannels) { + super(DM, numChannels); + linear2db = computeLinear2DB(); + + } -public class DavidSFXModule extends AbstractSoundDriver{ - - ArrayList cachedSounds=new ArrayList(); - - public final float[] linear2db; - - private SoundWorker[] channels; - private Thread[] soundThread; - - public DavidSFXModule(DoomMain DM,int numChannels) { - super(DM,numChannels); - linear2db=computeLinear2DB(); - - } - private float[] computeLinear2DB() { - - // Maximum volume is 0 db, minimum is ... -96 db. - // We rig this so that half-scale actually gives quarter power, - // and so is -6 dB. - float[] tmp=new float[VOLUME_STEPS]; - - for (int i=0;i> 16); ///(256*256); - seperation = seperation - 257; - rightvol = - volume - ((volume*seperation*seperation) >> 16); - - - // Sanity check, clamp volume. - - if (rightvol < 0 || rightvol > 127) - DM.doomSystem.Error("rightvol out of bounds"); - - if (leftvol < 0 || leftvol > 127) - DM.doomSystem.Error("leftvol out of bounds"); - - // Preserve sound SFX id, - // e.g. for avoiding duplicates of chainsaw. - channelids[slot] = sfxid; - - channels[slot].setVolume(volume); - channels[slot].setPanning(seperation+256); - channels[slot].addSound(cachedSounds.get(sfxid).data, handlenums); - channels[slot].setPitch(pitch); - - if (D) System.err.println(channelStatus()); - if (D) System.err.printf("Playing %d vol %d on channel %d\n",rc,volume,slot); - // You tell me. - return rc; - } - - @Override - public void StopSound(int handle) { - // Which channel has it? - int hnd=getChannelFromHandle(handle); - if (hnd>=0) - channels[hnd].stopSound(); - } + // or reuse an existing one if it exists. + createDataLineForChannel(slot, sfxid); + + // Reset current handle number, limited to 0..100. + if (handlenums == 0) // was !handlenums, so it's actually 1...100? + { + handlenums = MAXHANDLES; + } + + // Assign current handle number. + // Preserved so sounds could be stopped (unused). + channelhandles[slot] = rc = handlenums--; + channelstart[slot] = DM.gametic; + + // Separation, that is, orientation/stereo. + // range is: 1 - 256 + seperation += 1; + + // Per left/right channel. + // x^2 seperation, + // adjust volume properly. + leftvol + = volume - ((volume * seperation * seperation) >> 16); ///(256*256); + seperation = seperation - 257; + rightvol + = volume - ((volume * seperation * seperation) >> 16); + + // Sanity check, clamp volume. + if (rightvol < 0 || rightvol > 127) { + DM.doomSystem.Error("rightvol out of bounds"); + } + + if (leftvol < 0 || leftvol > 127) { + DM.doomSystem.Error("leftvol out of bounds"); + } + + // Preserve sound SFX id, + // e.g. for avoiding duplicates of chainsaw. + channelids[slot] = sfxid; + + channels[slot].setVolume(volume); + channels[slot].setPanning(seperation + 256); + channels[slot].addSound(cachedSounds.get(sfxid).data, handlenums); + channels[slot].setPitch(pitch); + + if (D) { + LOGGER.log(Level.FINE, channelStatus()); + } + if (D) { + LOGGER.log(Level.FINE, String.format("Playing %d vol %d on channel %d", rc, volume, slot)); + } + // You tell me. + return rc; + } + + @Override + public void StopSound(int handle) { + // Which channel has it? + int hnd = getChannelFromHandle(handle); + if (hnd >= 0) { + channels[hnd].stopSound(); + } + } + + @Override + public boolean SoundIsPlaying(int handle) { + + return getChannelFromHandle(handle) != BUSY_HANDLE; + } + + @Override + public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { + + // This should be called on sounds that are ALREADY playing. We really need + // to retrieve channels from their handles. + //System.err.printf("Updating sound with handle %d vol %d sep %d pitch %d\n",handle,vol,sep,pitch); + int i = getChannelFromHandle(handle); + // None has it? + if (i != BUSY_HANDLE) { + //System.err.printf("Updating sound with handle %d in channel %d\n",handle,i); + channels[i].setVolume(vol); + channels[i].setPitch(pitch); + channels[i].setPanning(sep); + } + + } + + /** Internal use. + * + * @param handle + * @return the channel that has the handle, or -2 if none has it. + */ + private int getChannelFromHandle(int handle) { + // Which channel has it? + for (int i = 0; i < numChannels; i++) { + if (channelhandles[i] == handle) { + return i; + } + } + + return BUSY_HANDLE; + } + + /** A Thread for playing digital sound effects. + * + * Obviously you need as many as channels? + * + * In order not to end up in a hell of effects, + * certain types of sounds must be limited to 1 per object. + * + */ + private class SoundWorker implements Runnable { + + public Semaphore wait; // Holds the worker still until there's a new sound + FloatControl vc; // linear volume control + FloatControl bc; // balance/panning control + FloatControl pc; // pitch control + byte[] currentSoundSync; + byte[] currentSound; + + public SoundWorker(int id) { + this.id = id; + this.handle = IDLE_HANDLE; + wait = new Semaphore(1); + } + + int id; + /** Used to find out whether the same object is continuously making + * sounds. E.g. the player, ceilings etc. In that case, they must be + * interrupted. + */ + int handle; + public boolean terminate; + SourceDataLine auline; + + /** This is how you tell the thread to play a sound, + * I suppose. */ + public void addSound(byte[] ds, int handle) { + + if (D) { + LOGGER.log(Level.INFO, String.format("Added handle %d to channel %d", handle, id)); + } + this.handle = handle; + this.currentSound = ds; + this.auline.stop(); + this.auline.start(); + this.wait.release(); + + } + + /** Accepts volume in "Doom" format (0-127). + * + * @param volume + */ + public void setVolume(int volume) { + if (vc != null) { + if (vc.getType() == FloatControl.Type.MASTER_GAIN) { + float vol = linear2db[volume]; + vc.setValue(vol); + } else if (vc.getType() == FloatControl.Type.VOLUME) { + float vol = vc.getMinimum() + (vc.getMaximum() - vc.getMinimum()) * (float) volume / 127f; + vc.setValue(vol); + } + } + } + + public void setPanning(int sep) { + // Q: how does Doom's sep map to stereo panning? + // A: Apparently it's 0-255 L-R. + if (bc != null) { + float pan = bc.getMinimum() + (bc.getMaximum() - bc.getMinimum()) * (float) (sep) / ISoundDriver.PANNING_STEPS; + //System.err.printf("Panning %d %f %f %f\n",sep,bc.getMinimum(),bc.getMaximum(),pan); + bc.setValue(pan); + } + } + + /** Expects a steptable value between 16K and 256K, with + * 64K being the middle. + * + * @param pitch + */ + public void setPitch(int pitch) { + if (pc != null) { + float pan = (float) (pc.getValue() * ((float) pitch / 65536.0)); + pc.setValue(pan); + } + } + + public void run() { + LOGGER.log(Level.INFO, String.format("Sound thread %d started", id)); + while (!terminate) { + currentSoundSync = currentSound; + if (currentSoundSync != null) { + + try { + auline.write(currentSoundSync, 0, currentSoundSync.length); + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "SoundWorker run failure", e); + return; + } finally { + // The previous steps are actually VERY fast. + // However this one waits until the data has been + // consumed, Interruptions/signals won't reach here, + // so it's pointless trying to interrupt the actual filling. + //long a=System.nanoTime(); + auline.drain(); + //long b=System.nanoTime(); + //System.out.printf("Channel %d completed in %f.\n",id,(float)(b-a)/1000000000f); + } + // Report that this channel is free. + currentSound = null; + // Remove its handle. + + //System.out.printf("Channel %d with handle %d done. Marking as free\n",id,handle); + if (handle > 0) { + channelhandles[this.id] = IDLE_HANDLE; + } + this.handle = IDLE_HANDLE; + } + + // If we don't sleep at least a bit here, busy waiting becomes + // way too taxing. Waiting on a semaphore (triggered by adding a new sound) + // seems like a better method. + try { + wait.acquire(); + } catch (InterruptedException e) { + } + } + } + + public void stopSound() { + auline.stop(); + auline.flush(); + //System.out.printf("Channel %d with handle %d interrupted. Marking as free\n",id,handle); + channelhandles[this.id] = IDLE_HANDLE; + this.handle = IDLE_HANDLE; + currentSound = null; + auline.start(); + } + + public boolean isPlaying() { + //System.out.printf("Channel %d with handle %d queried\n",id,handle); + return (this.handle != IDLE_HANDLE || this.currentSound != null); + } + + } + + StringBuilder sb = new StringBuilder(); + + public String channelStatus() { + sb.setLength(0); + for (int i = 0; i < numChannels; i++) { + if (channels[i].isPlaying()) { + sb.append(i); + } else { + sb.append('-'); + } + } + + return sb.toString(); + + } - @Override - public boolean SoundIsPlaying(int handle) { - - return getChannelFromHandle(handle)!=BUSY_HANDLE; - } - - - @Override - public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { - - // This should be called on sounds that are ALREADY playing. We really need - // to retrieve channels from their handles. - - //System.err.printf("Updating sound with handle %d vol %d sep %d pitch %d\n",handle,vol,sep,pitch); - - int i=getChannelFromHandle(handle); - // None has it? - if (i!=BUSY_HANDLE){ - //System.err.printf("Updating sound with handle %d in channel %d\n",handle,i); - channels[i].setVolume(vol); - channels[i].setPitch(pitch); - channels[i].setPanning(sep); - } - - } - - /** Internal use. - * - * @param handle - * @return the channel that has the handle, or -2 if none has it. - */ - private int getChannelFromHandle(int handle){ - // Which channel has it? - for (int i=0;i0) - channelhandles[this.id]=IDLE_HANDLE; - this.handle=IDLE_HANDLE; - } - - // If we don't sleep at least a bit here, busy waiting becomes - // way too taxing. Waiting on a semaphore (triggered by adding a new sound) - // seems like a better method. - - try { - wait.acquire(); - } catch (InterruptedException e) { - } - } - } - - public void stopSound() { - auline.stop(); - auline.flush(); - //System.out.printf("Channel %d with handle %d interrupted. Marking as free\n",id,handle); - channelhandles[this.id]=IDLE_HANDLE; - this.handle=IDLE_HANDLE; - currentSound = null; - auline.start(); - } - - public boolean isPlaying() { - //System.out.printf("Channel %d with handle %d queried\n",id,handle); - return (this.handle!=IDLE_HANDLE||this.currentSound!=null); - } - - } - - StringBuilder sb=new StringBuilder(); - - public String channelStatus(){ - sb.setLength(0); - for (int i=0;i= 0 ? signed : 256 + signed); - unsigned = (256 + signed) % 256; - return unsigned; - } - - public static int fread(byte[] bytes, int size, int count, InputStream file) throws IOException { - int retour = 0; - do { - if (file.read(bytes, retour*size, size) < size) - return retour; - retour++; - } - while (--count > 0); - return retour; - } - - public static int freadint(InputStream file) throws IOException { - /*byte[] bytes = new byte[2]; + + private static final Logger LOGGER = Loggers.getLogger(DoomIO.class.getName()); + + InputStream is; + OutputStream os; + + public DoomIO(InputStream is, OutputStream os) { + this.is = is; + this.os = os; + } + + public static int toUnsigned(byte signed) { + int unsigned = (signed & 0xff); + unsigned = (signed >= 0 ? signed : 256 + signed); + unsigned = (256 + signed) % 256; + return unsigned; + } + + public static int fread(byte[] bytes, int size, int count, InputStream file) throws IOException { + int retour = 0; + do { + if (file.read(bytes, retour * size, size) < size) { + return retour; + } + retour++; + } while (--count > 0); + return retour; + } + + public static int freadint(InputStream file) throws IOException { + /*byte[] bytes = new byte[2]; if (fread(bytes, 2, 1, file) < 1) return -1; int retour = toUnsigned(bytes[1])*256 + toUnsigned(bytes[0]); return retour;*/ - return freadint(file, 2); - } + return freadint(file, 2); + } - public static int freadint(InputStream file, int nbBytes) throws IOException { - byte[] bytes = new byte[nbBytes]; - if (fread(bytes, nbBytes, 1, file) < 1) - return -1; - long retour = 0; - for (int i = 0; i < nbBytes; i++) { - retour += toUnsigned(bytes[i])*(long)Math.pow(256, i); - } - //toUnsigned(bytes[1])*256 + toUnsigned(bytes[0]); - - if (retour > (long)Math.pow(256, nbBytes)/2) - retour -= (long)Math.pow(256, nbBytes); - - return (int)retour; - } - - public static int fwrite2(byte[] ptr, int offset, int size, Object file) throws IOException - { - fwrite(ptr, offset, size, 1, file); - return 0; - } - - public static int fwrite2(byte[] ptr, int size, Object file) throws IOException - { - return fwrite2(ptr, 0, size, file); - } - - public static int fwrite2(byte[] ptr, Object file) throws IOException - { - return fwrite2(ptr, 0, ptr.length, file); - } - - public static void fwrite(String bytes, int size, int count, Object file) throws IOException { - fwrite(toByteArray(bytes), size, count, file); - } - - public static void fwrite(byte[] bytes, int size, int count, Object file) throws IOException { - fwrite(bytes, 0, size, count, file); - } - - public static void fwrite(byte[] bytes, int offset, int size, int count, Object file) throws IOException { - if (file instanceof OutputStream) { - /*byte[] b = bytes; + public static int freadint(InputStream file, int nbBytes) throws IOException { + byte[] bytes = new byte[nbBytes]; + if (fread(bytes, nbBytes, 1, file) < 1) { + return -1; + } + long retour = 0; + for (int i = 0; i < nbBytes; i++) { + retour += toUnsigned(bytes[i]) * (long) Math.pow(256, i); + } + //toUnsigned(bytes[1])*256 + toUnsigned(bytes[0]); + + if (retour > (long) Math.pow(256, nbBytes) / 2) { + retour -= (long) Math.pow(256, nbBytes); + } + + return (int) retour; + } + + public static int fwrite2(byte[] ptr, int offset, int size, Object file) throws IOException { + fwrite(ptr, offset, size, 1, file); + return 0; + } + + public static int fwrite2(byte[] ptr, int size, Object file) throws IOException { + return fwrite2(ptr, 0, size, file); + } + + public static int fwrite2(byte[] ptr, Object file) throws IOException { + return fwrite2(ptr, 0, ptr.length, file); + } + + public static void fwrite(String bytes, int size, int count, Object file) throws IOException { + fwrite(toByteArray(bytes), size, count, file); + } + + public static void fwrite(byte[] bytes, int size, int count, Object file) throws IOException { + fwrite(bytes, 0, size, count, file); + } + + public static void fwrite(byte[] bytes, int offset, int size, int count, Object file) throws IOException { + if (file instanceof OutputStream) { + /*byte[] b = bytes; if (bytes.length < size) { b = new byte[size]; copyBytes(from, to, offset) }*/ - - ((OutputStream)file).write(bytes, offset, Math.min(bytes.length, size)); - for (int i = bytes.length; i < size; i++) - ((OutputStream)file).write((byte)0); // padding effect if size is bigger than byte array - } - if (file instanceof Writer) { - char[] ch = new char[bytes.length]; - for (int i = 0; i < bytes.length; i++) { - ch[i] = (char)toUnsigned(bytes[i]); - } - - ((Writer)file).write(ch, offset, size); - } - } - - public static byte[] toByteArray(String str) { - byte[] retour = new byte[str.length()]; - for (int i = 0; i < str.length(); i++) { - retour[i] = (byte)(str.charAt(i) & 0xFF); - } - return retour; - } - - public static byte[] toByteArray(int str) { - return toByteArray(str, 2); - } - - public static enum Endian { BIG, LITTLE } - public static Endian writeEndian = Endian.LITTLE; - - static int byteIdx(int i, int nbBytes) { - return (writeEndian == Endian.BIG ? i : nbBytes-1-i); - } - - public static void copyBytes(byte[] from, byte[] to, int offset) { - for (byte b: from) { - to[offset++] = b; - } - } - - public static byte[] toByteArray(Long str, int nbBytes) { - return toByteArray(str.intValue(), nbBytes); - } - - public static byte[] toByteArray(Short str, int nbBytes) { - return toByteArray(str.intValue(), nbBytes); - } - - public static byte[] toByteArray(int[] str, int nbBytes) { - byte[] bytes = new byte[str.length*nbBytes]; - for (int i = 0; i < str.length; i++) { - copyBytes(toByteArray(str[i], nbBytes), bytes, i*nbBytes); - } - return bytes; - } - /* + ((OutputStream) file).write(bytes, offset, Math.min(bytes.length, size)); + for (int i = bytes.length; i < size; i++) { + ((OutputStream) file).write((byte) 0); // padding effect if size is bigger than byte array + } + } + if (file instanceof Writer) { + char[] ch = new char[bytes.length]; + for (int i = 0; i < bytes.length; i++) { + ch[i] = (char) toUnsigned(bytes[i]); + } + + ((Writer) file).write(ch, offset, size); + } + } + + public static byte[] toByteArray(String str) { + byte[] retour = new byte[str.length()]; + for (int i = 0; i < str.length(); i++) { + retour[i] = (byte) (str.charAt(i) & 0xFF); + } + return retour; + } + + public static byte[] toByteArray(int str) { + return toByteArray(str, 2); + } + + public static enum Endian { + BIG, LITTLE + } + public static Endian writeEndian = Endian.LITTLE; + + static int byteIdx(int i, int nbBytes) { + return (writeEndian == Endian.BIG ? i : nbBytes - 1 - i); + } + + public static void copyBytes(byte[] from, byte[] to, int offset) { + for (byte b : from) { + to[offset++] = b; + } + } + + public static byte[] toByteArray(Long str, int nbBytes) { + return toByteArray(str.intValue(), nbBytes); + } + + public static byte[] toByteArray(Short str, int nbBytes) { + return toByteArray(str.intValue(), nbBytes); + } + + public static byte[] toByteArray(int[] str, int nbBytes) { + byte[] bytes = new byte[str.length * nbBytes]; + for (int i = 0; i < str.length; i++) { + copyBytes(toByteArray(str[i], nbBytes), bytes, i * nbBytes); + } + return bytes; + } + + /* public static byte[] toByteArray(boolean[] bools, int nbBytes) { byte[] bytes = new byte[bools.length*nbBytes]; for (int i = 0; i < bools.length; i++) { @@ -156,104 +164,101 @@ public static byte[] toByteArray(boolean[] bools, int nbBytes) { return bytes; } */ - /* + /* public static byte[] toByteArray(Boolean bool, int nbBytes) { int val = (bool?1:0); return toByteArray(val, nbBytes); }*/ + public static byte[] toByteArray(Integer str, int nbBytes) { + Long val = str.longValue(); + if (val < 0) { + val = (long) Math.pow(256, nbBytes) + val; + } + + byte[] bytes = new byte[nbBytes]; + long tmp = val; + for (int i = 0; i < nbBytes - 1; i++) { + bytes[byteIdx(i, nbBytes)] = (byte) (tmp % 256); + tmp = tmp / 256; + } + + bytes[byteIdx(nbBytes - 1, nbBytes)] = (byte) (tmp); + return bytes; + } + + private static Field getField(Class clazz, String fieldName) throws NoSuchFieldException { + try { + return clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + Class superClass = clazz.getSuperclass(); + if (superClass == null) { + throw e; + } else { + return getField(superClass, fieldName); + } + } + } + + public static void linkBA(Object obj, Object fieldName, Object stream, int size) { + if (stream instanceof OutputStream) { + try { + Object val = null; + if (fieldName instanceof String) { + val = getField(obj.getClass(), (String) fieldName).get(obj); + if (val instanceof Enum) { + val = ((Enum) val).ordinal(); + } + } + if (fieldName instanceof Integer) { + val = fieldName; + } + + Method method = DoomIO.class.getMethod("toByteArray", val.getClass(), int.class); + byte[] bytes = (byte[]) method.invoke(null, val, size); + ((OutputStream) stream).write(bytes); + + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "linkBA output failure", e); + } + } + + if (stream instanceof InputStream) { + try { + if (fieldName instanceof String) { + Field field = obj.getClass().getField((String) fieldName); + assigner(obj, field, (InputStream) stream, size); + } + if (fieldName instanceof Integer) { + ((InputStream) stream).read(new byte[size]); + } + + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "linkBA input failure", e); + } + } - public static byte[] toByteArray(Integer str, int nbBytes) { - Long val = str.longValue(); - if (val < 0) - val = (long)Math.pow(256, nbBytes) + val; - - byte[] bytes = new byte[nbBytes]; - long tmp = val; - for (int i = 0; i clazz, String fieldName) throws NoSuchFieldException { - try { - return clazz.getDeclaredField(fieldName); - } catch (NoSuchFieldException e) { - Class superClass = clazz.getSuperclass(); - if (superClass == null) { - throw e; - } else { - return getField(superClass, fieldName); - } - } - } - - public static void linkBA(Object obj, Object fieldName, Object stream, int size) { - if (stream instanceof OutputStream) { - try { - Object val = null; - if (fieldName instanceof String) { - val = getField(obj.getClass(), (String)fieldName).get(obj); - if (val instanceof Enum) { - val = ((Enum)val).ordinal(); - } - } - if (fieldName instanceof Integer) { - val = fieldName; - } - - Method method = DoomIO.class.getMethod("toByteArray", val.getClass(), int.class); - byte[] bytes = (byte[])method.invoke(null, val, size); - ((OutputStream)stream).write(bytes); - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - if (stream instanceof InputStream) { - try { - if (fieldName instanceof String) { - Field field = obj.getClass().getField((String)fieldName); - assigner(obj, field, (InputStream)stream, size); - } - if (fieldName instanceof Integer) { - ((InputStream)stream).read(new byte[size]); - } - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - // public static int freadint(InputStream file, int nbBytes) throws IOException { + } - } - public static void assigner(Object obj, Field field, InputStream is, int size) throws IOException, IllegalArgumentException, IllegalAccessException { - - Class c = field.getType(); - if (c.isArray()) { - Object a = field.get(obj); - int len = Array.getLength(a); - for (int i = 0; i < len; i++) { - int val = DoomIO.freadint((InputStream)is, size); - Object o = Array.get(a, i); - Array.set(a, i, assignValue(val, o, o.getClass())); - } - return; - } - - int val = DoomIO.freadint((InputStream)is, size); - Object v = assignValue(val, field.get(obj), field.getType()); - field.set(obj, v); + public static void assigner(Object obj, Field field, InputStream is, int size) throws IOException, IllegalArgumentException, IllegalAccessException { - /*Object[] enums = c.getEnumConstants(); + Class c = field.getType(); + if (c.isArray()) { + Object a = field.get(obj); + int len = Array.getLength(a); + for (int i = 0; i < len; i++) { + int val = DoomIO.freadint((InputStream) is, size); + Object o = Array.get(a, i); + Array.set(a, i, assignValue(val, o, o.getClass())); + } + return; + } + + int val = DoomIO.freadint((InputStream) is, size); + Object v = assignValue(val, field.get(obj), field.getType()); + field.set(obj, v); + + /*Object[] enums = c.getEnumConstants(); if (enums != null) { int val = DoomIO.freadint((InputStream)is, size); field.set(obj, enums[val]); @@ -262,40 +267,41 @@ public static void assigner(Object obj, Field field, InputStream is, int size) t int val = DoomIO.freadint((InputStream)is, size); field.set(obj, val); }*/ - } - - public static Object assignValue(int val, Object objToReplace, Class classe) { - if (classe.isAssignableFrom(Boolean.class) || classe.isAssignableFrom(boolean.class)) { - return (val == 0 ? false : true); - } - - Object[] enums = classe.getEnumConstants(); - if (enums != null) { - //int val = DoomIO.freadint((InputStream)is, size); - return enums[val]; - //field.set(obj, enums[val]); - } - else { - //int val = DoomIO.freadint((InputStream)is, size); - //field.set(obj, val); - } - - return val; - } - - public static String baToString(byte[] bytes) { - String str = ""; - for (int i = 0; i < bytes.length && bytes[i] != 0; i++) - str += (char)bytes[i]; - return str; - } - - public static int indexOfArray(Object[] a, Object o) { - for (int i = 0; i < a.length/* Array.getLength(a)*/; i++) { - if (/*Array.get(a, i)*/a[i] == o) - return i; - } - return -1; - } + } + + public static Object assignValue(int val, Object objToReplace, Class classe) { + if (classe.isAssignableFrom(Boolean.class) || classe.isAssignableFrom(boolean.class)) { + return (val != 0); + } + + Object[] enums = classe.getEnumConstants(); + if (enums != null) { + //int val = DoomIO.freadint((InputStream)is, size); + return enums[val]; + //field.set(obj, enums[val]); + } else { + //int val = DoomIO.freadint((InputStream)is, size); + //field.set(obj, val); + } + + return val; + } + + public static String baToString(byte[] bytes) { + String str = ""; + for (int i = 0; i < bytes.length && bytes[i] != 0; i++) { + str += (char) bytes[i]; + } + return str; + } + + public static int indexOfArray(Object[] a, Object o) { + for (int i = 0; i < a.length/* Array.getLength(a)*/; i++) { + if (/*Array.get(a, i)*/a[i] == o) { + return i; + } + } + return -1; + } } diff --git a/src/s/DoomSound.java b/src/s/DoomSound.java index 1c9c7fd8..4ad63f6f 100644 --- a/src/s/DoomSound.java +++ b/src/s/DoomSound.java @@ -1,44 +1,42 @@ package s; +import data.sfxinfo_t; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioFormat.Encoding; -import data.sfxinfo_t; - /** A class representing a sample in memory * Convenient for wrapping/mirroring it regardless of what it represents. * */ class DoomSound extends sfxinfo_t { - /** This audio format is the one used by internal samples (16 bit, 11KHz, Stereo) + /** This audio format is the one used by internal samples (16 bit, 11KHz, Stereo) * for Clips and AudioLines. Sure, it's not general enough... who cares though? */ - public final static AudioFormat DEFAULT_SAMPLES_FORMAT=new AudioFormat(Encoding.PCM_SIGNED, ISoundDriver.SAMPLERATE, 16, 2, 4, ISoundDriver.SAMPLERATE, true); - - public final static AudioFormat DEFAULT_DOOM_FORMAT=new AudioFormat(Encoding.PCM_UNSIGNED, ISoundDriver.SAMPLERATE, 8, 1, 1, ISoundDriver.SAMPLERATE, true); - - - public AudioFormat format; - - public DoomSound(AudioFormat format) { - this.format=format; - } - - public DoomSound(){ - this.format=DEFAULT_DOOM_FORMAT; - } - - public DoomSound(sfxinfo_t sfx,AudioFormat format){ - this(format); - this.data=sfx.data; - this.pitch=sfx.pitch; - this.link=sfx.link; - this.lumpnum=sfx.lumpnum; - this.name=sfx.name; - this.priority=sfx.priority; - this.singularity=sfx.singularity; - this.usefulness=sfx.usefulness; - this.volume=sfx.volume; - } - + public final static AudioFormat DEFAULT_SAMPLES_FORMAT = new AudioFormat(Encoding.PCM_SIGNED, ISoundDriver.SAMPLERATE, 16, 2, 4, ISoundDriver.SAMPLERATE, true); + + public final static AudioFormat DEFAULT_DOOM_FORMAT = new AudioFormat(Encoding.PCM_UNSIGNED, ISoundDriver.SAMPLERATE, 8, 1, 1, ISoundDriver.SAMPLERATE, true); + + public AudioFormat format; + + public DoomSound(AudioFormat format) { + this.format = format; + } + + public DoomSound() { + this.format = DEFAULT_DOOM_FORMAT; + } + + public DoomSound(sfxinfo_t sfx, AudioFormat format) { + this(format); + this.data = sfx.data; + this.pitch = sfx.pitch; + this.link = sfx.link; + this.lumpnum = sfx.lumpnum; + this.name = sfx.name; + this.priority = sfx.priority; + this.singularity = sfx.singularity; + this.usefulness = sfx.usefulness; + this.volume = sfx.volume; + } + } diff --git a/src/s/DoomToWave.java b/src/s/DoomToWave.java index fe4f5d85..d639644f 100644 --- a/src/s/DoomToWave.java +++ b/src/s/DoomToWave.java @@ -6,262 +6,260 @@ import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; - +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import utils.C2JUtils; public class DoomToWave { - static int MEMORYCACHE = 0x8000; - static class RIFFHEAD { - byte[] riff = new byte[4]; - int length; - byte[] wave = new byte[4]; - - public void pack(ByteBuffer b){ - b.put(riff); - b.putInt(length); - b.put(wave); - } - - public int size(){ - return 12; - } - - } - - RIFFHEAD headr = new RIFFHEAD(); - - static class CHUNK - { byte[] name = new byte[4]; - int size; - - public void pack(ByteBuffer b){ - b.put(name); - b.putInt(size); - } - - public int size(){ - return 8; - } - } - - CHUNK headc = new CHUNK(); - - static class WAVEFMT - { byte[] fmt = new byte[4]; /* "fmt " */ - int fmtsize; /*0x10*/ - int tag; /*format tag. 1=PCM*/ - int channel; /*1*/ - int smplrate; - int bytescnd; /*average bytes per second*/ - int align; /*block alignment, in bytes*/ - int nbits; /*specific to PCM format*/ - - public void pack(ByteBuffer b){ - b.put(fmt); - b.putInt(fmtsize); - b.putChar((char) tag); - b.putChar((char) channel); - b.putInt(smplrate); - b.putInt(bytescnd); - b.putChar((char) align); - b.putChar((char) nbits); - } - - public int size(){ - return 24; - } - } - - WAVEFMT headf = new WAVEFMT(); - int SIZEOF_WAVEFMT = 24; - - static class WAVEDATA /*data*/ - { byte[] data = new byte[4]; /* "data" */ - int datasize; - - public void pack(ByteBuffer b){ - b.put(data); - b.putInt(datasize); - } - } - WAVEDATA headw = new WAVEDATA(); - int SIZEOF_WAVEDATA = 8; - - public void SNDsaveSound(InputStream is, OutputStream os) throws IOException { - int type = DoomIO.freadint(is, 2);// peek_i16_le (buffer); - int speed = DoomIO.freadint(is, 2);//peek_u16_le (buffer + 2); - int datasize = DoomIO.freadint(is, 4);//peek_i32_le (buffer + 4); - if (type!=3) - System.out.println("Sound: weird type "+type+". Extracting anyway."); - - int headsize = 2 + 2 + 4; - int size = is.available(); - - int phys_size = size /*- headsize*/; - if (datasize > phys_size) - { - System.out.println("Sound %s: declared sample size %lu greater than lump size %lu ;"/*, + private static final Logger LOGGER = Loggers.getLogger(DoomToWave.class.getName()); + + static int MEMORYCACHE = 0x8000; + + static class RIFFHEAD { + + byte[] riff = new byte[4]; + int length; + byte[] wave = new byte[4]; + + public void pack(ByteBuffer b) { + b.put(riff); + b.putInt(length); + b.put(wave); + } + + public int size() { + return 12; + } + + } + + RIFFHEAD headr = new RIFFHEAD(); + + static class CHUNK { + + byte[] name = new byte[4]; + int size; + + public void pack(ByteBuffer b) { + b.put(name); + b.putInt(size); + } + + public int size() { + return 8; + } + } + + CHUNK headc = new CHUNK(); + + static class WAVEFMT { + + byte[] fmt = new byte[4]; + /* "fmt " */ + int fmtsize; + /*0x10*/ + int tag; + /*format tag. 1=PCM*/ + int channel; + /*1*/ + int smplrate; + int bytescnd; + /*average bytes per second*/ + int align; + /*block alignment, in bytes*/ + int nbits; + + /*specific to PCM format*/ + public void pack(ByteBuffer b) { + b.put(fmt); + b.putInt(fmtsize); + b.putChar((char) tag); + b.putChar((char) channel); + b.putInt(smplrate); + b.putInt(bytescnd); + b.putChar((char) align); + b.putChar((char) nbits); + } + + public int size() { + return 24; + } + } + + WAVEFMT headf = new WAVEFMT(); + int SIZEOF_WAVEFMT = 24; + + static class WAVEDATA /*data*/ { + + byte[] data = new byte[4]; + /* "data" */ + int datasize; + + public void pack(ByteBuffer b) { + b.put(data); + b.putInt(datasize); + } + } + WAVEDATA headw = new WAVEDATA(); + int SIZEOF_WAVEDATA = 8; + + public void SNDsaveSound(InputStream is, OutputStream os) throws IOException { + int type = DoomIO.freadint(is, 2);// peek_i16_le (buffer); + int speed = DoomIO.freadint(is, 2);//peek_u16_le (buffer + 2); + int datasize = DoomIO.freadint(is, 4);//peek_i32_le (buffer + 4); + if (type != 3) { + LOGGER.log(Level.FINE, String.format("Sound: weird type %d. Extracting anyway.", type)); + } + + int headsize = 2 + 2 + 4; + /*- headsize*/ int phys_size = is.available(); + if (datasize > phys_size) { + LOGGER.log(Level.INFO, "Sound: declared sample size greater than lump size"/*, lump_name (name), (unsigned long) datasize, (unsigned long) phys_size*/); - System.out.println("Sound %s: truncating to lump size."/*, lump_name (name)*/); - datasize = phys_size; - } - /* Sometimes the size of sound lump is greater - than the declared sound size. */ - - else if (datasize < phys_size) - { - if (/*fullSND == TRUE*/true) /* Save entire lump */ - datasize = phys_size; - else - { - /*Warning ( + LOGGER.log(Level.INFO, "Sound: truncating to lump size."/*, lump_name (name)*/); + datasize = phys_size; + } /* Sometimes the size of sound lump is greater + than the declared sound size. */ else if (datasize < phys_size) { + if (/*fullSND == TRUE*/true) /* Save entire lump */ { + datasize = phys_size; + } else { + /*Warning ( "Sound %s: lump size %lu greater than declared sample size %lu ;", lump_name (name), (unsigned long) datasize, (unsigned long) phys_size); Warning ("Sound %s: truncating to declared sample size.", lump_name (name));*/ - } - } - - DoomIO.writeEndian = DoomIO.Endian.BIG; - - SNDsaveWave(is, os, speed, datasize); - } - - public byte[] DMX2Wave(byte[] DMXSound) throws IOException { - ByteBuffer is=ByteBuffer.wrap(DMXSound); - is.order(ByteOrder.LITTLE_ENDIAN); - int type = 0x0000FFFF&is.getShort();// peek_i16_le (buffer); - int speed = 0x0000FFFF&is.getShort();//peek_u16_le (buffer + 2); - int datasize = is.getInt();//peek_i32_le (buffer + 4); - if (type!=3) - System.out.println("Sound: weird type "+type+". Extracting anyway."); - - int headsize = 2 + 2 + 4; - int size = is.remaining(); - - int phys_size = size /*- headsize*/; - if (datasize > phys_size) - { - System.out.println("Sound %s: declared sample size %lu greater than lump size %lu ;"/*, + } + } + + DoomIO.writeEndian = DoomIO.Endian.BIG; + + SNDsaveWave(is, os, speed, datasize); + } + + public byte[] DMX2Wave(byte[] DMXSound) throws IOException { + ByteBuffer is = ByteBuffer.wrap(DMXSound); + is.order(ByteOrder.LITTLE_ENDIAN); + int type = 0x0000FFFF & is.getShort();// peek_i16_le (buffer); + int speed = 0x0000FFFF & is.getShort();//peek_u16_le (buffer + 2); + int datasize = is.getInt();//peek_i32_le (buffer + 4); + if (type != 3) { + LOGGER.log(Level.INFO, String.format("Sound: weird type %d. Extracting anyway.", type)); + } + + int headsize = 2 + 2 + 4; + /*- headsize*/ int phys_size = is.remaining(); + if (datasize > phys_size) { + LOGGER.log(Level.INFO, "Sound: declared sample size greater than lump size"/*, lump_name (name), (unsigned long) datasize, (unsigned long) phys_size*/); - System.out.println("Sound %s: truncating to lump size."/*, lump_name (name)*/); - datasize = phys_size; - } - /* Sometimes the size of sound lump is greater - than the declared sound size. */ - - else if (datasize < phys_size) - { - if (/*fullSND == TRUE*/true) /* Save entire lump */ - datasize = phys_size; - else - { - /*Warning ( + LOGGER.log(Level.INFO, "Sound: truncating to lump size."/*, lump_name (name)*/); + datasize = phys_size; + } /* Sometimes the size of sound lump is greater + than the declared sound size. */ else if (datasize < phys_size) { + if (/*fullSND == TRUE*/true) /* Save entire lump */ { + datasize = phys_size; + } else { + /*Warning ( "Sound %s: lump size %lu greater than declared sample size %lu ;", lump_name (name), (unsigned long) datasize, (unsigned long) phys_size); Warning ("Sound %s: truncating to declared sample size.", lump_name (name));*/ - } - } - - return SNDsaveWave(is, speed, datasize); - } - - protected byte[] SNDsaveWave(ByteBuffer is, int speed, int size) throws IOException - { - - // Size with header and data etc. - byte[] output=new byte[headr.size()+headf.size() + SIZEOF_WAVEDATA+2*size]; - ByteBuffer os=ByteBuffer.wrap(output); - os.order(ByteOrder.LITTLE_ENDIAN); - os.position(0); - headr.riff = ("RIFF").getBytes(); - int siz = 4 + SIZEOF_WAVEFMT + SIZEOF_WAVEDATA+2*size; - headr.length = siz; - headr.wave = C2JUtils.toByteArray("WAVE"); - - headr.pack(os); - - headf.fmt = C2JUtils.toByteArray("fmt "); - headf.fmtsize = SIZEOF_WAVEFMT - 8; - headf.tag = 1; - headf.channel = 2; // Maes: HACK to force stereo lines. - headf.smplrate = speed; - headf.bytescnd = 2*speed; // Ditto. - headf.align = 1; - headf.nbits = 8; - - headf.pack(os); - - headw.data = C2JUtils.toByteArray("data"); - headw.datasize = 2*size; - //byte[] wtf=DoomIO.toByteArray(headw.datasize, 4); - - - headw.pack(os); - - byte tmp; - - for (int i=0;iMEMORYCACHE)? MEMORYCACHE:(size-wsize); - is.read(bytes, 0, sz); - os.write(bytes, 0, sz); - //if(fwrite((buffer+(wsize)),(size_t)sz,1,fp)!=1) - // ProgError("%s: write error (%s)", fname (file), strerror (errno)); - } - } + } + } + + return SNDsaveWave(is, speed, datasize); + } + + protected byte[] SNDsaveWave(ByteBuffer is, int speed, int size) throws IOException { + + // Size with header and data etc. + byte[] output = new byte[headr.size() + headf.size() + SIZEOF_WAVEDATA + 2 * size]; + ByteBuffer os = ByteBuffer.wrap(output); + os.order(ByteOrder.LITTLE_ENDIAN); + os.position(0); + headr.riff = ("RIFF").getBytes(); + int siz = 4 + SIZEOF_WAVEFMT + SIZEOF_WAVEDATA + 2 * size; + headr.length = siz; + headr.wave = C2JUtils.toByteArray("WAVE"); + + headr.pack(os); + + headf.fmt = C2JUtils.toByteArray("fmt "); + headf.fmtsize = SIZEOF_WAVEFMT - 8; + headf.tag = 1; + headf.channel = 2; // Maes: HACK to force stereo lines. + headf.smplrate = speed; + headf.bytescnd = 2 * speed; // Ditto. + headf.align = 1; + headf.nbits = 8; + + headf.pack(os); + + headw.data = C2JUtils.toByteArray("data"); + headw.datasize = 2 * size; + //byte[] wtf=DoomIO.toByteArray(headw.datasize, 4); + + headw.pack(os); + + byte tmp; + + for (int i = 0; i < size; i++) { + tmp = is.get(); + os.put(tmp); + os.put(tmp); + } + + return os.array(); + } + + void SNDsaveWave(InputStream is, OutputStream os, int speed, int size) throws IOException { + int wsize, sz = 0; + headr.riff = DoomIO.toByteArray("RIFF"); + int siz = 4 + SIZEOF_WAVEFMT + SIZEOF_WAVEDATA + size; + headr.length = siz; + headr.wave = DoomIO.toByteArray("WAVE"); + + DoomIO.fwrite2(headr.riff, os); + DoomIO.fwrite2(DoomIO.toByteArray(headr.length, 4), os); + DoomIO.fwrite2(headr.wave, os); + + headf.fmt = DoomIO.toByteArray("fmt "); + headf.fmtsize = SIZEOF_WAVEFMT - 8; + headf.tag = 1; + headf.channel = 1; // Maes: HACK to force stereo lines. + headf.smplrate = speed; + headf.bytescnd = speed; + headf.align = 1; + headf.nbits = 8; + + DoomIO.fwrite2(headf.fmt, os); + DoomIO.fwrite2(DoomIO.toByteArray(headf.fmtsize, 4), os); + DoomIO.fwrite2(DoomIO.toByteArray(headf.tag, 2), os); + DoomIO.fwrite2(DoomIO.toByteArray(headf.channel, 2), os); + DoomIO.fwrite2(DoomIO.toByteArray(headf.smplrate, 4), os); + DoomIO.fwrite2(DoomIO.toByteArray(headf.bytescnd, 4), os); + DoomIO.fwrite2(DoomIO.toByteArray(headf.align, 2), os); + DoomIO.fwrite2(DoomIO.toByteArray(headf.nbits, 2), os); + + headw.data = DoomIO.toByteArray("data"); + headw.datasize = size; + + DoomIO.fwrite2(headw.data, os); + DoomIO.fwrite2(DoomIO.toByteArray(headw.datasize, 4), os); + + ByteArrayOutputStream shit = (ByteArrayOutputStream) os; + + byte[] crap = shit.toByteArray(); + + byte[] bytes = new byte[MEMORYCACHE]; + for (wsize = 0; wsize < size; wsize += sz) { + sz = (size - wsize > MEMORYCACHE) ? MEMORYCACHE : (size - wsize); + is.read(bytes, 0, sz); + os.write(bytes, 0, sz); + //if(fwrite((buffer+(wsize)),(size_t)sz,1,fp)!=1) + // ProgError("%s: write error (%s)", fname (file), strerror (errno)); + } + } } diff --git a/src/s/DummyMusic.java b/src/s/DummyMusic.java index 9cdc22ac..e904c47f 100644 --- a/src/s/DummyMusic.java +++ b/src/s/DummyMusic.java @@ -2,58 +2,58 @@ public class DummyMusic implements IMusic { - @Override - public void InitMusic() { - // TODO Auto-generated method stub + @Override + public void InitMusic() { + // TODO Auto-generated method stub - } + } - @Override - public void ShutdownMusic() { - // TODO Auto-generated method stub + @Override + public void ShutdownMusic() { + // TODO Auto-generated method stub - } + } - @Override - public void SetMusicVolume(int volume) { - // TODO Auto-generated method stub + @Override + public void SetMusicVolume(int volume) { + // TODO Auto-generated method stub - } + } - @Override - public void PauseSong(int handle) { - // TODO Auto-generated method stub + @Override + public void PauseSong(int handle) { + // TODO Auto-generated method stub - } + } - @Override - public void ResumeSong(int handle) { - // TODO Auto-generated method stub + @Override + public void ResumeSong(int handle) { + // TODO Auto-generated method stub - } + } - @Override - public int RegisterSong(byte[] data) { - // TODO Auto-generated method stub - return 0; - } + @Override + public int RegisterSong(byte[] data) { + // TODO Auto-generated method stub + return 0; + } - @Override - public void PlaySong(int handle, boolean looping) { - // TODO Auto-generated method stub + @Override + public void PlaySong(int handle, boolean looping) { + // TODO Auto-generated method stub - } + } - @Override - public void StopSong(int handle) { - // TODO Auto-generated method stub + @Override + public void StopSong(int handle) { + // TODO Auto-generated method stub - } + } - @Override - public void UnRegisterSong(int handle) { - // TODO Auto-generated method stub + @Override + public void UnRegisterSong(int handle) { + // TODO Auto-generated method stub - } + } } diff --git a/src/s/DummySFX.java b/src/s/DummySFX.java index 6bb5e574..1ef16cde 100644 --- a/src/s/DummySFX.java +++ b/src/s/DummySFX.java @@ -4,64 +4,64 @@ public class DummySFX implements ISoundDriver { - @Override - public boolean InitSound() { - // Dummy is super-reliable ;-) - return true; - } + @Override + public boolean InitSound() { + // Dummy is super-reliable ;-) + return true; + } - @Override - public void UpdateSound() { - // TODO Auto-generated method stub + @Override + public void UpdateSound() { + // TODO Auto-generated method stub - } + } - @Override - public void SubmitSound() { - // TODO Auto-generated method stub + @Override + public void SubmitSound() { + // TODO Auto-generated method stub - } + } - @Override - public void ShutdownSound() { - // TODO Auto-generated method stub + @Override + public void ShutdownSound() { + // TODO Auto-generated method stub - } + } - @Override - public int GetSfxLumpNum(sfxinfo_t sfxinfo) { - // TODO Auto-generated method stub - return 0; - } + @Override + public int GetSfxLumpNum(sfxinfo_t sfxinfo) { + // TODO Auto-generated method stub + return 0; + } - @Override - public int StartSound(int id, int vol, int sep, int pitch, int priority) { - // TODO Auto-generated method stub - return 0; - } + @Override + public int StartSound(int id, int vol, int sep, int pitch, int priority) { + // TODO Auto-generated method stub + return 0; + } - @Override - public void StopSound(int handle) { - // TODO Auto-generated method stub + @Override + public void StopSound(int handle) { + // TODO Auto-generated method stub - } + } - @Override - public boolean SoundIsPlaying(int handle) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean SoundIsPlaying(int handle) { + // TODO Auto-generated method stub + return false; + } - @Override - public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { - // TODO Auto-generated method stub + @Override + public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { + // TODO Auto-generated method stub - } + } - @Override - public void SetChannels(int numChannels) { - // TODO Auto-generated method stub - - } + @Override + public void SetChannels(int numChannels) { + // TODO Auto-generated method stub + + } } diff --git a/src/s/DummySoundDriver.java b/src/s/DummySoundDriver.java index ac0d5eba..25b31bda 100644 --- a/src/s/DummySoundDriver.java +++ b/src/s/DummySoundDriver.java @@ -1,8 +1,8 @@ package s; -import p.mobj_t; import data.sounds.musicenum_t; import data.sounds.sfxenum_t; +import p.mobj_t; /** Does nothing. Just allows me to code without * commenting out ALL sound-related code. Hopefully @@ -11,103 +11,102 @@ * @author Velktron * */ +public class DummySoundDriver implements IDoomSound { + + @Override + public void Init(int sfxVolume, int musicVolume) { + // TODO Auto-generated method stub + + } + + @Override + public void Start() { + // TODO Auto-generated method stub + + } + + @Override + public void StartSound(ISoundOrigin origin, int sound_id) { + // TODO Auto-generated method stub + + } + + @Override + public void StartSound(ISoundOrigin origin, sfxenum_t sound_id) { + // TODO Auto-generated method stub + + } + + @Override + public void StartSoundAtVolume(ISoundOrigin origin, int sound_id, int volume) { + // TODO Auto-generated method stub + + } + + @Override + public void StopSound(ISoundOrigin origin) { + // TODO Auto-generated method stub + + } + + @Override + public void ChangeMusic(int musicnum, boolean looping) { + // TODO Auto-generated method stub + + } + + @Override + public void StopMusic() { + // TODO Auto-generated method stub + + } + + @Override + public void PauseSound() { + // TODO Auto-generated method stub + + } + + @Override + public void ResumeSound() { + // TODO Auto-generated method stub + + } + + @Override + public void UpdateSounds(mobj_t listener) { + // TODO Auto-generated method stub + + } + + @Override + public void SetMusicVolume(int volume) { + // TODO Auto-generated method stub + + } + + @Override + public void SetSfxVolume(int volume) { + // TODO Auto-generated method stub + + } + + @Override + public void StartMusic(int music_id) { + // TODO Auto-generated method stub + + } + + @Override + public void StartMusic(musicenum_t music_id) { + // TODO Auto-generated method stub + + } + + @Override + public void ChangeMusic(musicenum_t musicnum, boolean looping) { + // TODO Auto-generated method stub -public class DummySoundDriver implements IDoomSound{ - - @Override - public void Init(int sfxVolume, int musicVolume) { - // TODO Auto-generated method stub - - } - - @Override - public void Start() { - // TODO Auto-generated method stub - - } - - @Override - public void StartSound(ISoundOrigin origin, int sound_id) { - // TODO Auto-generated method stub - - } - - @Override - public void StartSound(ISoundOrigin origin, sfxenum_t sound_id) { - // TODO Auto-generated method stub - - } - - @Override - public void StartSoundAtVolume(ISoundOrigin origin, int sound_id, int volume) { - // TODO Auto-generated method stub - - } - - @Override - public void StopSound(ISoundOrigin origin) { - // TODO Auto-generated method stub - - } - - @Override - public void ChangeMusic(int musicnum, boolean looping) { - // TODO Auto-generated method stub - - } - - @Override - public void StopMusic() { - // TODO Auto-generated method stub - - } - - @Override - public void PauseSound() { - // TODO Auto-generated method stub - - } - - @Override - public void ResumeSound() { - // TODO Auto-generated method stub - - } - - @Override - public void UpdateSounds(mobj_t listener) { - // TODO Auto-generated method stub - - } - - @Override - public void SetMusicVolume(int volume) { - // TODO Auto-generated method stub - - } - - @Override - public void SetSfxVolume(int volume) { - // TODO Auto-generated method stub - - } - - @Override - public void StartMusic(int music_id) { - // TODO Auto-generated method stub - - } - - @Override - public void StartMusic(musicenum_t music_id) { - // TODO Auto-generated method stub - - } - - @Override - public void ChangeMusic(musicenum_t musicnum, boolean looping) { - // TODO Auto-generated method stub - - } + } } diff --git a/src/s/FinnwMusicModule.java b/src/s/FinnwMusicModule.java index 46f78adb..c2cc75c4 100644 --- a/src/s/FinnwMusicModule.java +++ b/src/s/FinnwMusicModule.java @@ -20,7 +20,8 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; - +import java.util.logging.Level; +import java.util.logging.Logger; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiDevice; import javax.sound.midi.MidiEvent; @@ -33,6 +34,7 @@ import javax.sound.midi.SysexMessage; import javax.sound.midi.Track; import javax.sound.midi.Transmitter; +import mochadoom.Loggers; /** A music driver that bypasses Sequences and sends events from a MUS lump * directly to a MIDI device. @@ -53,11 +55,13 @@ */ public class FinnwMusicModule implements IMusic { + private static final Logger LOGGER = Loggers.getLogger(FinnwMusicModule.class.getName()); + public FinnwMusicModule() { this.lock = new ReentrantLock(); - this.channels = new ArrayList(15); - this.songs = new ArrayList(1); - for (int midiChan = 0; midiChan < 16; ++ midiChan) { + this.channels = new ArrayList<>(15); + this.songs = new ArrayList<>(1); + for (int midiChan = 0; midiChan < 16; ++midiChan) { if (midiChan != 9) { channels.add(new Channel(midiChan)); } @@ -74,7 +78,7 @@ public void InitMusic() { genMidiEG.sendTo(receiver); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } catch (MidiUnavailableException ex) { - System.err.println(ex); + LOGGER.log(Level.WARNING, "InitMusic: midi unavailable", ex); receiver = null; } exec = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl()); @@ -96,8 +100,8 @@ public void PlaySong(int handle, boolean looping) { if (0 <= handle && handle < songs.size()) { prepare(receiver); Song song = songs.get(handle); - currentTransmitter = - new ScheduledTransmitter(song.getScoreBuffer(), looping); + currentTransmitter + = new ScheduledTransmitter(song.getScoreBuffer(), looping); currentTransmitter.setReceiver(receiver); } } finally { @@ -133,7 +137,7 @@ public void ResumeSong(int handle) { @Override public void SetMusicVolume(int volume) { - float fVol = volume * (1/127f); + float fVol = volume * (1 / 127f); fVol = Math.max(0f, Math.min(fVol, 1f)); lock.lock(); try { @@ -177,17 +181,17 @@ public void UnRegisterSong(int handle) { } static boolean hasMusMagic(ByteBuffer magicBuf) { - return magicBuf.get(0) == 'M' && - magicBuf.get(1) == 'U' && - magicBuf.get(2) == 'S' && - magicBuf.get(3) == 0x1a; + return magicBuf.get(0) == 'M' + && magicBuf.get(1) == 'U' + && magicBuf.get(2) == 'S' + && magicBuf.get(3) == 0x1a; } - EventGroup nextEventGroup(ByteBuffer scoreBuffer, boolean looping) { + EventGroup nextEventGroup(ByteBuffer scoreBuffer, boolean looping) { EventGroup result = new EventGroup(volume); boolean last; do { - if (! scoreBuffer.hasRemaining()) { + if (!scoreBuffer.hasRemaining()) { if (looping) { scoreBuffer.flip(); } else { @@ -200,8 +204,7 @@ EventGroup nextEventGroup(ByteBuffer scoreBuffer, boolean looping) { int chanIndex = descriptor & 15; Channel channel = channels.get(chanIndex); switch (eventType) { - case 0: - { + case 0: { int note = scoreBuffer.get() & 0xff; if ((note & 0x80) != 0) { throw new IllegalArgumentException("Invalid note byte"); @@ -209,8 +212,7 @@ EventGroup nextEventGroup(ByteBuffer scoreBuffer, boolean looping) { checkChannelExists("note off", channel).noteOff(note, result); } break; - case 1: - { + case 1: { int note = scoreBuffer.get() & 0xff; boolean hasVelocity = (note & 0x80) != 0; if (hasVelocity) { @@ -224,98 +226,98 @@ EventGroup nextEventGroup(ByteBuffer scoreBuffer, boolean looping) { } } break; - case 2: - { + case 2: { int wheelVal = scoreBuffer.get() & 0xff; checkChannelExists("pitch bend", channel).pitchBend(wheelVal, result); } break; - case 3: - { + case 3: { int sysEvt = scoreBuffer.get() & 0xff; switch (sysEvt) { - case 10: - checkChannelExists("all sounds off", channel).allSoundsOff(result); - break; - case 11: - checkChannelExists("all notes off", channel).allNotesOff(result); - break; - case 14: - checkChannelExists("reset all controllers", channel).resetAll(result); - break; - default: - String msg = String.format("Invalid system event (%d)", sysEvt); - throw new IllegalArgumentException(msg); + case 10: + checkChannelExists("all sounds off", channel).allSoundsOff(result); + break; + case 11: + checkChannelExists("all notes off", channel).allNotesOff(result); + break; + case 14: + checkChannelExists("reset all controllers", channel).resetAll(result); + break; + default: + String msg = String.format("Invalid system event (%d)", sysEvt); + throw new IllegalArgumentException(msg); } } break; - case 4: - int cNum = scoreBuffer.get() & 0xff; - if ((cNum & 0x80) != 0) { - throw new IllegalArgumentException("Invalid controller number "); - } - int cVal = scoreBuffer.get() & 0xff; - if (cNum == 3 && 133 <= cVal && cVal <= 135) { - // workaround for some TNT.WAD tracks - cVal = 127; - } - if ((cVal & 0x80) != 0) { - String msg = String.format("Invalid controller value (%d; cNum=%d)", cVal, cNum); - throw new IllegalArgumentException(msg); - } - switch (cNum) { - case 0: - checkChannelExists("patch change", channel).patchChange(cVal, result); - break; - case 1: - // Don't forward this to the MIDI device. Some devices - // react badly to banks that are undefined in GM Level 1 - checkChannelExists("bank switch", channel); - break; - case 2: - checkChannelExists("vibrato change", channel).vibratoChange(cVal, result); - break; - case 3: - checkChannelExists("volume", channel).volume(cVal, result); - break; case 4: - checkChannelExists("pan", channel).pan(cVal, result); - break; - case 5: - checkChannelExists("expression", channel).expression(cVal, result); + int cNum = scoreBuffer.get() & 0xff; + if ((cNum & 0x80) != 0) { + throw new IllegalArgumentException("Invalid controller number "); + } + int cVal = scoreBuffer.get() & 0xff; + if (cNum == 3 && 133 <= cVal && cVal <= 135) { + // workaround for some TNT.WAD tracks + cVal = 127; + } + if ((cVal & 0x80) != 0) { + String msg = String.format("Invalid controller value (%d; cNum=%d)", cVal, cNum); + throw new IllegalArgumentException(msg); + } + switch (cNum) { + case 0: + checkChannelExists("patch change", channel).patchChange(cVal, result); + break; + case 1: + // Don't forward this to the MIDI device. Some devices + // react badly to banks that are undefined in GM Level 1 + checkChannelExists("bank switch", channel); + break; + case 2: + checkChannelExists("vibrato change", channel).vibratoChange(cVal, result); + break; + case 3: + checkChannelExists("volume", channel).volume(cVal, result); + break; + case 4: + checkChannelExists("pan", channel).pan(cVal, result); + break; + case 5: + checkChannelExists("expression", channel).expression(cVal, result); + break; + case 6: + checkChannelExists("reverb depth", channel).reverbDepth(cVal, result); + break; + case 7: + checkChannelExists("chorus depth", channel).chorusDepth(cVal, result); + break; + default: + throw new AssertionError("Controller number " + cNum + ": not yet implemented"); + } break; case 6: - checkChannelExists("reverb depth", channel).reverbDepth(cVal, result); - break; - case 7: - checkChannelExists("chorus depth", channel).chorusDepth(cVal, result); + if (looping) { + scoreBuffer.flip(); + } else { + return result.emptyToNull(); + } break; default: - throw new AssertionError("Controller number " + cNum + ": not yet implemented"); - } - break; - case 6: - if (looping) { - scoreBuffer.flip(); - } else { - return result.emptyToNull(); - } - break; - default: - String msg = String.format("Unknown event type: last=%5s eventType=%d chanIndex=%d%n", last, eventType, chanIndex); - throw new IllegalArgumentException(msg); + String msg = String.format("Unknown event type: last=%5s eventType=%d chanIndex=%d%n", last, eventType, chanIndex); + throw new IllegalArgumentException(msg); } - } while (! last); + } while (!last); int qTics = readTime(scoreBuffer); result.addDelay(qTics); return result; } static class EventGroup { + EventGroup(float volScale) { - this.messages = new ArrayList(); + this.messages = new ArrayList<>(); this.volScale = volScale; } + void addDelay(int tics) { delay += tics; } @@ -330,31 +332,38 @@ void addDelay(int tics) { private static final int CTRL_REVERB_DEPTH = 91; private static final int CTRL_MODULATION_POT = 1; private static final int CTRL_VOLUME = 7; + void allNotesOff(int midiChan) { addControlChange(midiChan, CHM_ALL_NOTES_OFF, 0); } + void allSoundsOff(int midiChan) { addControlChange(midiChan, CHM_ALL_SOUND_OFF, 0); } + long appendTo(Sequence sequence, int trackNum, long pos) { Track track = sequence.getTracks()[trackNum]; - for (MidiMessage msg: messages) { + for (MidiMessage msg : messages) { track.add(new MidiEvent(msg, pos)); } return pos + delay * 3; } + long appendTo(Track track, long pos, int scale) { - for (MidiMessage msg: messages) { + for (MidiMessage msg : messages) { track.add(new MidiEvent(msg, pos)); } return pos + delay * scale; } + void chorusDepth(int midiChan, int depth) { addControlChange(midiChan, CTRL_CHORUS_DEPTH, depth); } + void generalMidi(int mode) { - addSysExMessage(0xf0, (byte)0x7e, (byte)0x7f, (byte)9, (byte)mode, (byte)0xf7); + addSysExMessage(0xf0, (byte) 0x7e, (byte) 0x7f, (byte) 9, (byte) mode, (byte) 0xf7); } + EventGroup emptyToNull() { if (messages.isEmpty()) { return null; @@ -362,57 +371,73 @@ EventGroup emptyToNull() { return this; } } + void expression(int midiChan, int expr) { addControlChange(midiChan, CTRL_EXPRESSION_POT, expr); } + int getDelay() { return delay; } + void noteOn(int midiChan, int note, int velocity) { addShortMessage(midiChan, ShortMessage.NOTE_ON, note, velocity); } + void noteOff(int midiChan, int note) { addShortMessage(midiChan, ShortMessage.NOTE_OFF, note, 0); } + void pan(int midiChan, int pan) { addControlChange(midiChan, CTRL_PAN, pan); } + void patchChange(int midiChan, int patchId) { addShortMessage(midiChan, ShortMessage.PROGRAM_CHANGE, patchId, 0); } + void pitchBend(int midiChan, int wheelVal) { int pb14 = wheelVal * 64; addShortMessage(midiChan, ShortMessage.PITCH_BEND, pb14 % 128, pb14 / 128); } + void pitchBendSensitivity(int midiChan, int semitones) { addRegParamChange(midiChan, RPM_PITCH_BEND_SENSITIVITY, RPL_PITCH_BEND_SENSITIVITY, semitones); } + void resetAllControllern(int midiChan) { addControlChange(midiChan, CHM_RESET_ALL, 0); } + void reverbDepth(int midiChan, int depth) { addControlChange(midiChan, CTRL_REVERB_DEPTH, depth); } + void sendTo(Receiver receiver) { - for (MidiMessage msg: messages) { + for (MidiMessage msg : messages) { receiver.send(msg, -1); } } + void vibratoChange(int midiChan, int depth) { addControlChange(midiChan, CTRL_MODULATION_POT, depth); } + void volume(int midiChan, int vol) { vol = (int) Math.round(vol * volScale); addControlChange(midiChan, CTRL_VOLUME, vol); } + private void addControlChange(int midiChan, int ctrlId, int ctrlVal) { addShortMessage(midiChan, ShortMessage.CONTROL_CHANGE, ctrlId, ctrlVal); } + private void addRegParamChange(int midiChan, int paramMsb, int paramLsb, int valMsb) { addControlChange(midiChan, 101, paramMsb); addControlChange(midiChan, 100, paramLsb); addControlChange(midiChan, 6, valMsb); } + private void addShortMessage(int midiChan, int cmd, int data1, int data2) { try { ShortMessage msg = new ShortMessage(); @@ -422,6 +447,7 @@ private void addShortMessage(int midiChan, int cmd, int data1, int data2) { throw new RuntimeException(ex); } } + private void addSysExMessage(int status, byte... data) { try { SysexMessage msg = new SysexMessage(); @@ -438,6 +464,7 @@ private void addSysExMessage(int status, byte... data) { /** A collection of kludges to pick a MIDI output device until cvars are implemented */ static class MidiDeviceComparator implements Comparator { + @Override public int compare(MidiDevice.Info o1, MidiDevice.Info o2) { float score1 = score(o1), score2 = score(o2); @@ -449,6 +476,7 @@ public int compare(MidiDevice.Info o1, MidiDevice.Info o2) { return 0; } } + private float score(MidiDevice.Info info) { String lcName = info.getName().toLowerCase(Locale.ENGLISH); float result = 0f; @@ -475,15 +503,16 @@ private float score(MidiDevice.Info info) { } static class ThreadFactoryImpl implements ThreadFactory { + @Override public Thread newThread(final Runnable r) { - Thread thread = - new Thread(r, String.format("FinnwMusicModule-%d", NEXT_ID.getAndIncrement())); + Thread thread + = new Thread(r, String.format("FinnwMusicModule-%d", NEXT_ID.getAndIncrement())); thread.setPriority(Thread.MAX_PRIORITY - 1); return thread; } - private static final AtomicInteger NEXT_ID = - new AtomicInteger(1); + private static final AtomicInteger NEXT_ID + = new AtomicInteger(1); } final Lock lock; @@ -498,11 +527,10 @@ public Thread newThread(final Runnable r) { float volume; private static Receiver getReceiver() throws MidiUnavailableException { - List dInfos = - new ArrayList(Arrays.asList(MidiSystem.getMidiDeviceInfo())); + List dInfos + = new ArrayList<>(Arrays.asList(MidiSystem.getMidiDeviceInfo())); for (Iterator it = dInfos.iterator(); - it.hasNext(); - ) { + it.hasNext();) { MidiDevice.Info dInfo = it.next(); MidiDevice dev = MidiSystem.getMidiDevice(dInfo); if (dev.getMaxReceivers() == 0) { @@ -510,7 +538,9 @@ private static Receiver getReceiver() throws MidiUnavailableException { it.remove(); } } - if (dInfos.isEmpty()) return null; + if (dInfos.isEmpty()) { + return null; + } Collections.sort(dInfos, new MidiDeviceComparator()); MidiDevice.Info dInfo = dInfos.get(0); MidiDevice dev = MidiSystem.getMidiDevice((MidiDevice.Info) dInfo); @@ -520,7 +550,7 @@ private static Receiver getReceiver() throws MidiUnavailableException { private void prepare(Receiver receiver) { EventGroup setupEG = new EventGroup(volume); - for (Channel chan: channels) { + for (Channel chan : channels) { chan.allSoundsOff(setupEG); chan.resetAll(setupEG); chan.pitchBendSensitivity(2, setupEG); @@ -547,6 +577,7 @@ private static void sleepUninterruptibly(int timeout, TimeUnit timeUnit) { Thread.currentThread().interrupt(); } } + private static Channel checkChannelExists(String type, Channel channel) throws IllegalArgumentException { if (channel == null) { @@ -565,61 +596,78 @@ private int readTime(ByteBuffer scoreBuffer) { last = (digit & 0x80) == 0; result <<= 7; result |= digit & 127; - } while (! last); + } while (!last); return result; } private static class Channel { + Channel(int midiChan) { this.midiChan = midiChan; } + void allNotesOff(EventGroup eventGroup) { eventGroup.allNotesOff(midiChan); } + void allSoundsOff(EventGroup eventGroup) { eventGroup.allSoundsOff(midiChan); } + void chorusDepth(int depth, EventGroup eventGroup) { eventGroup.chorusDepth(midiChan, depth); } + void expression(int expr, EventGroup eventGroup) { eventGroup.expression(midiChan, expr); } + void noteOff(int note, EventGroup eventGroup) { eventGroup.noteOff(midiChan, note); } + void noteOn(int note, EventGroup eventGroup) { eventGroup.noteOn(midiChan, note, lastVelocity); } + void noteOn(int note, int velocity, EventGroup eventGroup) { lastVelocity = velocity; noteOn(note, eventGroup); } + void pan(int pan, EventGroup eventGroup) { eventGroup.pan(midiChan, pan); } + void patchChange(int patchId, EventGroup eventGroup) { eventGroup.patchChange(midiChan, patchId); } + void pitchBend(int wheelVal, EventGroup eventGroup) { eventGroup.pitchBend(midiChan, wheelVal); } + void pitchBendSensitivity(int semitones, EventGroup eventGroup) { eventGroup.pitchBendSensitivity(midiChan, semitones); } + void resetAll(EventGroup eventGroup) { eventGroup.resetAllControllern(midiChan); } + void reverbDepth(int depth, EventGroup eventGroup) { eventGroup.reverbDepth(midiChan, depth); } + void vibratoChange(int depth, EventGroup eventGroup) { eventGroup.vibratoChange(midiChan, depth); } + void volume(int vol, EventGroup eventGroup) { eventGroup.volume(midiChan, vol); lastVolume = vol; } + void volumeChanged(EventGroup eventGroup) { eventGroup.volume(midiChan, lastVolume); } @@ -675,7 +723,7 @@ public void setReceiver(Receiver receiver) { } void scheduleIfRequired(Receiver receiver, - EventGroup currentGroup) { + EventGroup currentGroup) { assert (((ReentrantLock) lock).isHeldByCurrentThread()); if (currentGroup == null) { try { @@ -683,8 +731,8 @@ void scheduleIfRequired(Receiver receiver, if (currentGroup != null) { triggerTask = new TriggerTask(currentGroup, receiver); long delay = Math.max(0, nextGroupTime - System.nanoTime()); - future = - exec.schedule(triggerTask, delay, TimeUnit.NANOSECONDS); + future + = exec.schedule(triggerTask, delay, TimeUnit.NANOSECONDS); nextGroupTime += currentGroup.getDelay() * nanosPerTick; } else { triggerTask = null; @@ -693,7 +741,7 @@ void scheduleIfRequired(Receiver receiver, } catch (RejectedExecutionException ex) { // This is normal when shutting down } catch (Exception ex) { - System.err.println(ex); + LOGGER.log(Level.WARNING, "schedule failure", ex); } } } @@ -704,14 +752,12 @@ void stop() { future.cancel(false); try { future.get(); - } catch (InterruptedException ex) { - } catch (ExecutionException ex) { - } catch (CancellationException ex) { + } catch (InterruptedException | ExecutionException | CancellationException ex) { } future = null; } EventGroup cleanup = new EventGroup(0f); - for (Channel chan: channels) { + for (Channel chan : channels) { chan.allNotesOff(cleanup); } cleanup.sendTo(receiver); @@ -720,7 +766,7 @@ void stop() { void volumeChanged() { assert (((ReentrantLock) lock).isHeldByCurrentThread()); EventGroup adjust = new EventGroup(volume); - for (Channel chan: channels) { + for (Channel chan : channels) { chan.volumeChanged(adjust); } adjust.sendTo(receiver); @@ -728,6 +774,7 @@ void volumeChanged() { TriggerTask triggerTask; private class TriggerTask implements Runnable { + @Override public void run() { boolean shouldSend = false; @@ -744,6 +791,7 @@ public void run() { eventGroup.sendTo(receiver); } } + TriggerTask(EventGroup eventGroup, Receiver receiver) { this.eventGroup = eventGroup; this.receiver = receiver; @@ -770,13 +818,14 @@ public void run() { /** Contains unfiltered MUS data */ private class Song { + Song(ByteBuffer data) { this.data = data.asReadOnlyBuffer(); this.data.order(ByteOrder.LITTLE_ENDIAN); byte[] magic = new byte[4]; this.data.get(magic); ByteBuffer magicBuf = ByteBuffer.wrap(magic); - if (! hasMusMagic(magicBuf)) { + if (!hasMusMagic(magicBuf)) { throw new IllegalArgumentException("Expected magic string \"MUS\\x1a\" but found " + Arrays.toString(magic)); } this.scoreLen = this.data.getShort() & 0xffff; @@ -788,8 +837,7 @@ ByteBuffer getScoreBuffer() { ByteBuffer scoreBuffer = this.data.duplicate(); scoreBuffer.position(scoreStart); scoreBuffer.limit(scoreStart + scoreLen); - ByteBuffer slice = scoreBuffer.slice(); - return slice; + return scoreBuffer.slice(); } private final ByteBuffer data; private final int scoreLen; diff --git a/src/s/IDoomSound.java b/src/s/IDoomSound.java index dcf68a70..69669464 100644 --- a/src/s/IDoomSound.java +++ b/src/s/IDoomSound.java @@ -34,7 +34,6 @@ // with separate concerns for SFX and MUSIC. // //----------------------------------------------------------------------------- - public interface IDoomSound { static IDoomSound chooseSoundIsPresent(DoomMain DM, CVarManager CVM, ISoundDriver ISND) { @@ -50,133 +49,129 @@ static IDoomSound chooseSoundIsPresent(DoomMain DM, CVarManager CVM, ISoun } } - class channel_t{ - - // sound information (if null, channel avail.) - sfxinfo_t sfxinfo; - - // origin of sound - ISoundOrigin origin; - - // handle of the sound being played - int handle; - } - - /** Convenience hack */ - public static final int NUMSFX=sfxenum_t.NUMSFX.ordinal(); - - // Purpose? - public static final char snd_prefixen[] - = { 'P', 'P', 'A', 'S', 'S', 'S', 'M', 'M', 'M', 'S', 'S', 'S' }; - - public static final int S_MAX_VOLUME=127; - - // when to clip out sounds - // Does not fit the large outdoor areas. - public static final int S_CLIPPING_DIST = (1200*0x10000); - - // Distance tp origin when sounds should be maxed out. - // This should relate to movement clipping resolution - // (see BLOCKMAP handling). - // Originally: (200*0x10000). - public static final int S_CLOSE_DIST =(160*0x10000); - - public static final int S_ATTENUATOR =((S_CLIPPING_DIST-S_CLOSE_DIST)>>m.fixed_t.FRACBITS); - - // Adjustable by menu. - //protected final int NORM_VOLUME snd_MaxVolume - - public static final int NORM_PITCH = 128; - public final static int NORM_PRIORITY = 64; - public final static int NORM_SEP =128; - - public final static int S_PITCH_PERTURB = 1; - public final static int S_STEREO_SWING = (96*0x10000); - - // percent attenuation from front to back - public final static int S_IFRACVOL = 30; - - public final static int NA = 0; - public final static int S_NUMCHANNELS= 2; - - /** - * Initializes sound stuff, including volume Sets channels, SFX and music - * volume, allocates channel buffer, sets S_sfx lookup. - */ - - void Init(int sfxVolume, int musicVolume); - - /** - * Per level startup code. Kills playing sounds at start of level, - * determines music if any, changes music. - */ - public void Start(); - - /** - * Start sound for thing at using from sounds.h - */ - public void StartSound(ISoundOrigin origin, int sound_id); - - /** - * Start sound for thing at using from sounds.h - * Convenience method using sfxenum_t instead. Delegated to int version. - * - */ - public void StartSound(ISoundOrigin origin, sfxenum_t sound_id); - - /** Will start a sound at a given volume. */ - public void StartSoundAtVolume(ISoundOrigin origin, int sound_id, int volume); - - /** Stop sound for thing at */ - public void StopSound(ISoundOrigin origin); - - /** - * Start music using from sounds.h, and set whether looping - * - * @param musicnum - * @param looping - */ - public void ChangeMusic(int musicnum, boolean looping); - - public void ChangeMusic(musicenum_t musicnum, boolean looping); - - /** Stops the music fer sure. */ - public void StopMusic(); - - /** Stop and resume music, during game PAUSE. */ - public void PauseSound(); - - public void ResumeSound(); - - /** - * Updates music & sounds - * - * @param listener - */ - public void UpdateSounds(mobj_t listener); - - public void SetMusicVolume(int volume); - - public void SetSfxVolume(int volume); - - - /** Start music using from sounds.h */ - public void StartMusic(int music_id); - - /** Start music using from sounds.h - * Convenience method using musicenum_t. - */ - public void StartMusic(musicenum_t music_id); - - // - // Internals. - // - // MAES: these appear to be only of value for internal implementation, - // and are never called externally. Thus, they might as well - // not be part of the interface, even though it's convenient to reuse them. - // - - /* + class channel_t { + + // sound information (if null, channel avail.) + sfxinfo_t sfxinfo; + + // origin of sound + ISoundOrigin origin; + + // handle of the sound being played + int handle; + } + + /** Convenience hack */ + public static final int NUMSFX = sfxenum_t.NUMSFX.ordinal(); + + // Purpose? + public static final char snd_prefixen[] + = {'P', 'P', 'A', 'S', 'S', 'S', 'M', 'M', 'M', 'S', 'S', 'S'}; + + public static final int S_MAX_VOLUME = 127; + + // when to clip out sounds + // Does not fit the large outdoor areas. + public static final int S_CLIPPING_DIST = (1200 * 0x10000); + + // Distance tp origin when sounds should be maxed out. + // This should relate to movement clipping resolution + // (see BLOCKMAP handling). + // Originally: (200*0x10000). + public static final int S_CLOSE_DIST = (160 * 0x10000); + + public static final int S_ATTENUATOR = ((S_CLIPPING_DIST - S_CLOSE_DIST) >> m.fixed_t.FRACBITS); + + // Adjustable by menu. + //protected final int NORM_VOLUME snd_MaxVolume + public static final int NORM_PITCH = 128; + public final static int NORM_PRIORITY = 64; + public final static int NORM_SEP = 128; + + public final static int S_PITCH_PERTURB = 1; + public final static int S_STEREO_SWING = (96 * 0x10000); + + // percent attenuation from front to back + public final static int S_IFRACVOL = 30; + + public final static int NA = 0; + public final static int S_NUMCHANNELS = 2; + + /** + * Initializes sound stuff, including volume Sets channels, SFX and music + * volume, allocates channel buffer, sets S_sfx lookup. + */ + void Init(int sfxVolume, int musicVolume); + + /** + * Per level startup code. Kills playing sounds at start of level, + * determines music if any, changes music. + */ + public void Start(); + + /** + * Start sound for thing at using from sounds.h + */ + public void StartSound(ISoundOrigin origin, int sound_id); + + /** + * Start sound for thing at using from sounds.h + * Convenience method using sfxenum_t instead. Delegated to int version. + * + */ + public void StartSound(ISoundOrigin origin, sfxenum_t sound_id); + + /** Will start a sound at a given volume. */ + public void StartSoundAtVolume(ISoundOrigin origin, int sound_id, int volume); + + /** Stop sound for thing at */ + public void StopSound(ISoundOrigin origin); + + /** + * Start music using from sounds.h, and set whether looping + * + * @param musicnum + * @param looping + */ + public void ChangeMusic(int musicnum, boolean looping); + + public void ChangeMusic(musicenum_t musicnum, boolean looping); + + /** Stops the music fer sure. */ + public void StopMusic(); + + /** Stop and resume music, during game PAUSE. */ + public void PauseSound(); + + public void ResumeSound(); + + /** + * Updates music & sounds + * + * @param listener + */ + public void UpdateSounds(mobj_t listener); + + public void SetMusicVolume(int volume); + + public void SetSfxVolume(int volume); + + /** Start music using from sounds.h */ + public void StartMusic(int music_id); + + /** Start music using from sounds.h + * Convenience method using musicenum_t. + */ + public void StartMusic(musicenum_t music_id); + + // + // Internals. + // + // MAES: these appear to be only of value for internal implementation, + // and are never called externally. Thus, they might as well + // not be part of the interface, even though it's convenient to reuse them. + // + /* int S_getChannel ( mobj_t origin, @@ -192,6 +187,5 @@ class channel_t{ int pitch ); void S_StopChannel(int cnum); - */ - + */ } diff --git a/src/s/IMusic.java b/src/s/IMusic.java index c0c1396e..416a802f 100644 --- a/src/s/IMusic.java +++ b/src/s/IMusic.java @@ -1,45 +1,44 @@ package s; // - import doom.CVarManager; import doom.CommandVariable; // MUSIC I/O // - public interface IMusic { - void InitMusic(); - void ShutdownMusic(); - // Volume. - void SetMusicVolume(int volume); - /** PAUSE game handling. */ - void PauseSong(int handle); - void ResumeSong(int handle); - - /** Registers a song handle to song data. - * This should handle any conversions from MUS/MIDI/OPL/etc. - * - * */ - int RegisterSong(byte[] data); - - - /** Called by anything that wishes to start music. + void InitMusic(); + + void ShutdownMusic(); + // Volume. + + void SetMusicVolume(int volume); + + /** PAUSE game handling. */ + void PauseSong(int handle); + + void ResumeSong(int handle); + + /** Registers a song handle to song data. + * This should handle any conversions from MUS/MIDI/OPL/etc. + * + * */ + int RegisterSong(byte[] data); + + /** Called by anything that wishes to start music. plays a song, and when the song is done, starts playing it again in an endless loop. Horrible thing to do, considering. */ - - void - PlaySong - ( int handle, - boolean looping ); - - /** Stops a song over 3 seconds. */ - void StopSong(int handle); - - /** See above (register), then think backwards */ - void UnRegisterSong(int handle); + void + PlaySong(int handle, + boolean looping); + + /** Stops a song over 3 seconds. */ + void StopSong(int handle); + + /** See above (register), then think backwards */ + void UnRegisterSong(int handle); public static IMusic chooseModule(CVarManager CVM) { if (CVM.bool(CommandVariable.NOMUSIC) || CVM.bool(CommandVariable.NOSOUND)) { diff --git a/src/s/ISoundDriver.java b/src/s/ISoundDriver.java index c6c00dcd..2409c49a 100644 --- a/src/s/ISoundDriver.java +++ b/src/s/ISoundDriver.java @@ -5,6 +5,9 @@ import doom.CVarManager; import doom.CommandVariable; import doom.DoomMain; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; //Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- @@ -29,52 +32,51 @@ // implement this. // //----------------------------------------------------------------------------- - public interface ISoundDriver { - - public static final int VOLUME_STEPS = 128; - public static final int PANNING_STEPS = 256; - public static final int IDLE_HANDLE = -1; - public static final int BUSY_HANDLE = -2; - // Needed for calling the actual sound output - // We mix 1024 samples each time, but we only call UpdateSound() - // 1 time out of three. - - public static final int NUM_CHANNELS = 8; - // It is 2 for 16bit, and 2 for two channels. - public static final int BUFMUL = 4; - - public static final int SAMPLERATE = 22050; // Hz - - // Update all 30 millisecs, approx. 30fps synchronized. - // Linux resolution is allegedly 10 millisecs, - // scale is microseconds. - public static final int SOUND_INTERVAL = 500; - - /** Yes, it's possible to select a different sound frame rate */ - - public static final int SND_FRAME_RATE =21; - // Was 512, but if you mix that many samples per tic you will - // eventually outrun the buffer :-/ I fail to see the mathematical - // justification behind this, unless they simply wanted the buffer to - // be a nice round number in size. - public static final int SAMPLECOUNT =SAMPLERATE/SND_FRAME_RATE; - public static final int MIXBUFFERSIZE =(SAMPLECOUNT*BUFMUL); - public static final int SAMPLESIZE = 16 ; // 16bit - public static final int NUMSFX = sfxenum_t.NUMSFX.ordinal() ; - public static final int MAXHANDLES = 100; - /** How many audio chunks/frames to mix before submitting them to - * the output. - */ - public static final int BUFFER_CHUNKS=5; - - /** Ths audio buffer size of the audioline itself. - * Increasing this is the only effective way to combat output stuttering on - * slower machines. - */ - public static final int AUDIOLINE_BUFFER=2*BUFFER_CHUNKS*MIXBUFFERSIZE; - public static final int SOUND_PERIOD = 1000/SND_FRAME_RATE; // in ms + static final Logger LOGGER = Loggers.getLogger(ISoundDriver.class.getName()); + + public static final int VOLUME_STEPS = 128; + public static final int PANNING_STEPS = 256; + public static final int IDLE_HANDLE = -1; + public static final int BUSY_HANDLE = -2; + // Needed for calling the actual sound output + // We mix 1024 samples each time, but we only call UpdateSound() + // 1 time out of three. + + public static final int NUM_CHANNELS = 8; + // It is 2 for 16bit, and 2 for two channels. + public static final int BUFMUL = 4; + + public static final int SAMPLERATE = 22050; // Hz + + // Update all 30 millisecs, approx. 30fps synchronized. + // Linux resolution is allegedly 10 millisecs, + // scale is microseconds. + public static final int SOUND_INTERVAL = 500; + + /** Yes, it's possible to select a different sound frame rate */ + public static final int SND_FRAME_RATE = 21; + // Was 512, but if you mix that many samples per tic you will + // eventually outrun the buffer :-/ I fail to see the mathematical + // justification behind this, unless they simply wanted the buffer to + // be a nice round number in size. + public static final int SAMPLECOUNT = SAMPLERATE / SND_FRAME_RATE; + public static final int MIXBUFFERSIZE = (SAMPLECOUNT * BUFMUL); + public static final int SAMPLESIZE = 16; // 16bit + public static final int NUMSFX = sfxenum_t.NUMSFX.ordinal(); + public static final int MAXHANDLES = 100; + /** How many audio chunks/frames to mix before submitting them to + * the output. + */ + public static final int BUFFER_CHUNKS = 5; + + /** Ths audio buffer size of the audioline itself. + * Increasing this is the only effective way to combat output stuttering on + * slower machines. + */ + public static final int AUDIOLINE_BUFFER = 2 * BUFFER_CHUNKS * MIXBUFFERSIZE; + public static final int SOUND_PERIOD = 1000 / SND_FRAME_RATE; // in ms public static ISoundDriver chooseModule(DoomMain DM, CVarManager CVM) { final ISoundDriver driver; @@ -84,7 +86,7 @@ public static ISoundDriver chooseModule(DoomMain DM, CVarManager CVM) { // Switch between possible sound drivers. if (CVM.bool(CommandVariable.AUDIOLINES)) { // Crudish. driver = new DavidSFXModule(DM, DM.numChannels); - } else if (CVM.bool(CommandVariable.SPEAKERSOUND)) { // PC Speaker emulation + } else if (CVM.bool(CommandVariable.SPEAKERSOUND)) { // PC Speaker emulation driver = new SpeakerDoomSoundDriver(DM, DM.numChannels); } else if (CVM.bool(CommandVariable.CLIPSOUND)) { driver = new ClipSFXModule(DM, DM.numChannels); @@ -96,63 +98,58 @@ public static ISoundDriver chooseModule(DoomMain DM, CVarManager CVM) { } // Check for sound init failure and revert to dummy if (!driver.InitSound()) { - System.err.println("S_InitSound: failed. Reverting to dummy...\n"); + LOGGER.log(Level.WARNING, "S_InitSound: failed. Reverting to dummy..."); return new DummySFX(); } return driver; } - - /** Init at program start. Return false if device invalid, - * so that caller can decide best course of action. - * The suggested one is to swap the sound "driver" for a dummy. - * - * @return - */ - boolean InitSound(); - - // ... update sound buffer and audio device at runtime... - void UpdateSound(); - void SubmitSound(); - // ... shut down and relase at program termination. - void ShutdownSound(); + /** Init at program start. Return false if device invalid, + * so that caller can decide best course of action. + * The suggested one is to swap the sound "driver" for a dummy. + * + * @return + */ + boolean InitSound(); + // ... update sound buffer and audio device at runtime... + void UpdateSound(); - // - // SFX I/O - // + void SubmitSound(); - // Initialize channels? - void SetChannels(int numChannels); + // ... shut down and relase at program termination. + void ShutdownSound(); - // Get raw data lump index for sound descriptor. - int GetSfxLumpNum (sfxinfo_t sfxinfo ); + // + // SFX I/O + // + // Initialize channels? + void SetChannels(int numChannels); + // Get raw data lump index for sound descriptor. + int GetSfxLumpNum(sfxinfo_t sfxinfo); - // Starts a sound in a particular sound channel. - int StartSound - ( int id, - int vol, - int sep, - int pitch, - int priority ); + // Starts a sound in a particular sound channel. + int StartSound(int id, + int vol, + int sep, + int pitch, + int priority); + // Stops a sound channel. + void StopSound(int handle); - // Stops a sound channel. - void StopSound(int handle); - - /** Called by S_*() functions to see if a channel is still playing. + /** Called by S_*() functions to see if a channel is still playing. Returns false if no longer playing, true if playing. This is a relatively "high level" function, so its accuracy relies on what the "system specific" sound code reports back */ - boolean SoundIsPlaying(int handle); + boolean SoundIsPlaying(int handle); - /* Updates the volume, separation, + /* Updates the volume, separation, and pitch of a sound channel. */ - void UpdateSoundParams - ( int handle, - int vol, - int sep, - int pitch ); - + void UpdateSoundParams(int handle, + int vol, + int sep, + int pitch); + } diff --git a/src/s/ISoundOrigin.java b/src/s/ISoundOrigin.java index f7da368f..3e390c64 100644 --- a/src/s/ISoundOrigin.java +++ b/src/s/ISoundOrigin.java @@ -1,9 +1,11 @@ package s; /** Use this instead of that degemobj_t crud */ - public interface ISoundOrigin { - public int getX(); - public int getY(); - public int getZ(); - } + + public int getX(); + + public int getY(); + + public int getZ(); +} diff --git a/src/s/MusReader.java b/src/s/MusReader.java index 1e7ead2a..dd33dc0f 100644 --- a/src/s/MusReader.java +++ b/src/s/MusReader.java @@ -6,7 +6,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MetaMessage; import javax.sound.midi.MidiEvent; @@ -15,7 +14,6 @@ import javax.sound.midi.Sequence; import javax.sound.midi.ShortMessage; import javax.sound.midi.Track; - import m.Swap; /** @@ -35,7 +33,7 @@ public class MusReader { * @param is MUS data (this method does not try to auto-detect the format.) */ public static Sequence getSequence(InputStream is) - throws IOException, InvalidMidiDataException { + throws IOException, InvalidMidiDataException { DataInputStream dis = new DataInputStream(is); dis.skip(6); int rus = dis.readUnsignedShort(); @@ -51,13 +49,13 @@ public static Sequence getSequence(InputStream is) tick = eg.appendTo(track, tick); } MetaMessage endOfSequence = new MetaMessage(); - endOfSequence.setMessage(47, new byte[] {0}, 1); + endOfSequence.setMessage(47, new byte[]{0}, 1); track.add(new MidiEvent(endOfSequence, tick)); return sequence; } private static EventGroup - nextEventGroup(InputStream is, int[] channelVelocity) throws IOException { + nextEventGroup(InputStream is, int[] channelVelocity) throws IOException { EventGroup result = new EventGroup(); boolean last; do { @@ -78,8 +76,7 @@ public static Sequence getSequence(InputStream is) midiChan = 9; } switch (eventType) { - case 0: - { + case 0: { int note = is.read() & 0xff; if ((note & 0x80) != 0) { throw new IllegalArgumentException("Invalid note byte"); @@ -87,8 +84,7 @@ public static Sequence getSequence(InputStream is) result.noteOff(midiChan, note); } break; - case 1: - { + case 1: { int note = is.read() & 0xff; boolean hasVelocity = (note & 0x80) != 0; final int velocity; @@ -104,86 +100,84 @@ public static Sequence getSequence(InputStream is) result.noteOn(midiChan, note & 0x7f, velocity); } break; - case 2: - { + case 2: { int wheelVal = is.read() & 0xff; result.pitchBend(midiChan, wheelVal); } break; - case 3: - { + case 3: { int sysEvt = is.read() & 0xff; switch (sysEvt) { - case 10: - result.allSoundsOff(midiChan); - break; - case 11: - result.allNotesOff(midiChan); - break; - case 14: - result.resetAllControllers(midiChan); - break; - default: - String msg = String.format("Invalid system event (%d)", sysEvt); - throw new IllegalArgumentException(msg); + case 10: + result.allSoundsOff(midiChan); + break; + case 11: + result.allNotesOff(midiChan); + break; + case 14: + result.resetAllControllers(midiChan); + break; + default: + String msg = String.format("Invalid system event (%d)", sysEvt); + throw new IllegalArgumentException(msg); } } break; - case 4: - int cNum = is.read() & 0xff; - if ((cNum & 0x80) != 0) { - throw new IllegalArgumentException("Invalid controller number "); - } - int cVal = is.read() & 0xff; - if (cNum == 3 && 133 <= cVal && cVal <= 135) { - // workaround for some TNT.WAD tracks - cVal = 127; - } - if ((cVal & 0x80) != 0) { - String msg = String.format("Invalid controller value (%d; cNum=%d)", cVal, cNum); - throw new IllegalArgumentException(msg); - } - switch (cNum) { - case 0: - result.patchChange(midiChan, cVal); - break; - case 1: - // Don't forward this to the MIDI device. Some synths if - // in GM level 1 mode will react badly to banks that are - // undefined in GM Level 1 - break; - case 2: - result.vibratoChange(midiChan, cVal); - break; - case 3: - result.volume(midiChan, cVal); - break; case 4: - result.pan(midiChan, cVal); - break; - case 5: - result.expression(midiChan, cVal); + int cNum = is.read() & 0xff; + if ((cNum & 0x80) != 0) { + throw new IllegalArgumentException("Invalid controller number "); + } + int cVal = is.read() & 0xff; + if (cNum == 3 && 133 <= cVal && cVal <= 135) { + // workaround for some TNT.WAD tracks + cVal = 127; + } + if ((cVal & 0x80) != 0) { + String msg = String.format("Invalid controller value (%d; cNum=%d)", cVal, cNum); + throw new IllegalArgumentException(msg); + } + switch (cNum) { + case 0: + result.patchChange(midiChan, cVal); + break; + case 1: + // Don't forward this to the MIDI device. Some synths if + // in GM level 1 mode will react badly to banks that are + // undefined in GM Level 1 + break; + case 2: + result.vibratoChange(midiChan, cVal); + break; + case 3: + result.volume(midiChan, cVal); + break; + case 4: + result.pan(midiChan, cVal); + break; + case 5: + result.expression(midiChan, cVal); + break; + case 6: + result.reverbDepth(midiChan, cVal); + break; + case 7: + result.chorusDepth(midiChan, cVal); + break; + case 8: + result.sustain(midiChan, cVal); + break; + default: + throw new AssertionError("Unknown controller number: " + cNum + "(value: " + cVal + ")"); + } break; case 6: - result.reverbDepth(midiChan, cVal); - break; - case 7: - result.chorusDepth(midiChan, cVal); - break; - case 8: - result.sustain(midiChan, cVal); - break; + return result.emptyToNull(); default: - throw new AssertionError("Unknown controller number: " + cNum + "(value: " + cVal + ")"); - } - break; - case 6: - return result.emptyToNull(); - default: - String msg = String.format("Unknown event type: %d", eventType); - throw new IllegalArgumentException(msg); + String msg = String.format("Unknown event type: %d", eventType); + throw new IllegalArgumentException(msg); } - } while (! last); + } while (!last); int qTics = readVLV(is); result.addDelay(qTics); return result; @@ -197,32 +191,39 @@ private static int readVLV(InputStream is) throws IOException { last = (digit & 0x80) == 0; result <<= 7; result |= digit & 127; - } while (! last); + } while (!last); return result; } private static class EventGroup { + EventGroup() { - this.messages = new ArrayList(); + this.messages = new ArrayList<>(); } + void addDelay(long ticks) { delay += ticks; } + void allNotesOff(int midiChan) { addControlChange(midiChan, CHM_ALL_NOTES_OFF, 0); } + void allSoundsOff(int midiChan) { addControlChange(midiChan, CHM_ALL_SOUND_OFF, 0); } + long appendTo(Track track, long tick) { - for (MidiMessage msg: messages) { + for (MidiMessage msg : messages) { track.add(new MidiEvent(msg, tick)); } return tick + delay * 3; } + void chorusDepth(int midiChan, int depth) { addControlChange(midiChan, CTRL_CHORUS_DEPTH, depth); } + EventGroup emptyToNull() { if (messages.isEmpty()) { return null; @@ -230,43 +231,56 @@ EventGroup emptyToNull() { return this; } } + void expression(int midiChan, int expr) { addControlChange(midiChan, CTRL_EXPRESSION_POT, expr); } + void noteOn(int midiChan, int note, int velocity) { addShortMessage(midiChan, ShortMessage.NOTE_ON, note, velocity); } + void noteOff(int midiChan, int note) { addShortMessage(midiChan, ShortMessage.NOTE_OFF, note, 0); } + void pan(int midiChan, int pan) { addControlChange(midiChan, CTRL_PAN, pan); } + void patchChange(int midiChan, int patchId) { addShortMessage(midiChan, ShortMessage.PROGRAM_CHANGE, patchId, 0); } + void pitchBend(int midiChan, int wheelVal) { int pb14 = wheelVal * 64; addShortMessage(midiChan, ShortMessage.PITCH_BEND, pb14 % 128, pb14 / 128); } + void resetAllControllers(int midiChan) { addControlChange(midiChan, CHM_RESET_ALL, 0); } + void reverbDepth(int midiChan, int depth) { addControlChange(midiChan, CTRL_REVERB_DEPTH, depth); } + void sustain(int midiChan, int on) { addControlChange(midiChan, CTRL_SUSTAIN, on); } + void vibratoChange(int midiChan, int depth) { addControlChange(midiChan, CTRL_MODULATION_POT, depth); } + void volume(int midiChan, int vol) { addControlChange(midiChan, CTRL_VOLUME, vol); } + private void addControlChange(int midiChan, int ctrlId, int ctrlVal) { addShortMessage(midiChan, ShortMessage.CONTROL_CHANGE, ctrlId, ctrlVal); } + private void addShortMessage(int midiChan, int cmd, int data1, int data2) { try { ShortMessage msg = new ShortMessage(); diff --git a/src/s/QMusToMid.java b/src/s/QMusToMid.java index 7e6a982a..b088092c 100644 --- a/src/s/QMusToMid.java +++ b/src/s/QMusToMid.java @@ -8,514 +8,522 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; public class QMusToMid { - public static final int NOTMUSFILE = 1; /* Not a MUS file */ - public static final int COMUSFILE = 2; /* Can't open MUS file */ - public static final int COTMPFILE = 3; /* Can't open TMP file */ - public static final int CWMIDFILE = 4; /* Can't write MID file */ - public static final int MUSFILECOR = 5; /* MUS file corrupted */ - public static final int TOOMCHAN = 6; /* Too many channels */ - public static final int MEMALLOC = 7; /* Memory allocation error */ - - /* some (old) compilers mistake the "MUS\x1A" construct (interpreting + private static final Logger LOGGER = Loggers.getLogger(QMusToMid.class.getName()); + + public static final int NOTMUSFILE = 1; + /* Not a MUS file */ + public static final int COMUSFILE = 2; + /* Can't open MUS file */ + public static final int COTMPFILE = 3; + /* Can't open TMP file */ + public static final int CWMIDFILE = 4; + /* Can't write MID file */ + public static final int MUSFILECOR = 5; + /* MUS file corrupted */ + public static final int TOOMCHAN = 6; + /* Too many channels */ + public static final int MEMALLOC = 7; + /* Memory allocation error */ + + /* some (old) compilers mistake the "MUS\x1A" construct (interpreting it as "MUSx1A") */ - - public static final String MUSMAGIC = "MUS\032"; /* this seems to work */ - public static final String MIDIMAGIC = "MThd\000\000\000\006\000\001"; - public static final String TRACKMAGIC1 = "\000\377\003\035"; - public static final String TRACKMAGIC2 = "\000\377\057\000"; - public static final String TRACKMAGIC3 = "\000\377\002\026"; - public static final String TRACKMAGIC4 = "\000\377\131\002\000\000"; - public static final String TRACKMAGIC5 = "\000\377\121\003\011\243\032"; - public static final String TRACKMAGIC6 = "\000\377\057\000"; - - public static final int EOF = -1; - public static class Ptr { - a val; - - public Ptr(a val) { - this.val = val; - } - - public a get() { - return val; - } - - public void set(a newval) { - val = newval; - } - } - - public static class MUSheader - { - byte[] ID = new byte[4]; /* identifier "MUS" 0x1A */ - int ScoreLength; - int ScoreStart; - int channels; /* count of primary channels */ - int SecChannels; /* count of secondary channels (?) */ - int InstrCnt; - int dummy; - /* variable-length part starts here */ - int[] instruments; - } - - public static class Track - { - long current; - byte vel; - long DeltaTime; - byte LastEvent; - byte[] data; /* Primary data */ - } - - - long TRACKBUFFERSIZE = 65536L ; /* 64 Ko */ - - - void TWriteByte( int MIDItrack, byte byte_, Track track[] ) - { - long pos ; - - pos = track[MIDItrack].current ; - if( pos < TRACKBUFFERSIZE ) - track[MIDItrack].data[(int)pos] = byte_ ; - else - { - System.out.println("ERROR : Track buffer full.\n"+ - "Increase the track buffer size (option -size).\n" ) ; - System.exit(1); - } - track[MIDItrack].current++ ; - } - - - void TWriteVarLen( int tracknum, long value, - Track[] track ) - { - long buffer ; - - buffer = value & 0x7f ; - while( (value >>= 7) != 0 ) - { - buffer <<= 8 ; - buffer |= 0x80 ; - buffer += (value & 0x7f) ; - } - while( true ) - { - TWriteByte( tracknum, (byte)buffer, track ) ; - if( (buffer & 0x80) != 0 ) - buffer >>= 8 ; - else - break; - } - } - - int ReadMUSheader( MUSheader MUSh, InputStream file ) - { - try { - if( DoomIO.fread( MUSh.ID, 4, 1, file ) != 1 ) return COMUSFILE ; - - /*if( strncmp( MUSh->ID, MUSMAGIC, 4 ) ) + public static final String MUSMAGIC = "MUS\032"; + /* this seems to work */ + public static final String MIDIMAGIC = "MThd\000\000\000\006\000\001"; + public static final String TRACKMAGIC1 = "\000\377\003\035"; + public static final String TRACKMAGIC2 = "\000\377\057\000"; + public static final String TRACKMAGIC3 = "\000\377\002\026"; + public static final String TRACKMAGIC4 = "\000\377\131\002\000\000"; + public static final String TRACKMAGIC5 = "\000\377\121\003\011\243\032"; + public static final String TRACKMAGIC6 = "\000\377\057\000"; + + public static final int EOF = -1; + + public static class Ptr { + + a val; + + public Ptr(a val) { + this.val = val; + } + + public a get() { + return val; + } + + public void set(a newval) { + val = newval; + } + } + + public static class MUSheader { + + byte[] ID = new byte[4]; + /* identifier "MUS" 0x1A */ + int ScoreLength; + int ScoreStart; + int channels; + /* count of primary channels */ + int SecChannels; + /* count of secondary channels (?) */ + int InstrCnt; + int dummy; + /* variable-length part starts here */ + int[] instruments; + } + + public static class Track { + + long current; + byte vel; + long DeltaTime; + byte LastEvent; + byte[] data; + /* Primary data */ + } + + long TRACKBUFFERSIZE = 65536L; + + /* 64 Ko */ + void TWriteByte(int MIDItrack, byte byte_, Track track[]) { + long pos; + + pos = track[MIDItrack].current; + if (pos < TRACKBUFFERSIZE) { + track[MIDItrack].data[(int) pos] = byte_; + } else { + LOGGER.log(Level.SEVERE, "ERROR: Track buffer full. Increase the track buffer size (option -size)."); + System.exit(1); + } + track[MIDItrack].current++; + } + + void TWriteVarLen(int tracknum, long value, + Track[] track) { + long buffer; + + buffer = value & 0x7f; + while ((value >>= 7) != 0) { + buffer <<= 8; + buffer |= 0x80; + buffer += (value & 0x7f); + } + while (true) { + TWriteByte(tracknum, (byte) buffer, track); + if ((buffer & 0x80) != 0) { + buffer >>= 8; + } else { + break; + } + } + } + + int ReadMUSheader(MUSheader MUSh, InputStream file) { + try { + if (DoomIO.fread(MUSh.ID, 4, 1, file) != 1) { + return COMUSFILE; + } + + /*if( strncmp( MUSh->ID, MUSMAGIC, 4 ) ) return NOTMUSFILE ;*/ - if( (MUSh.ScoreLength = DoomIO.freadint(file)) == -1 ) return COMUSFILE ; - if( (MUSh.ScoreStart = DoomIO.freadint(file)) == -1 ) return COMUSFILE ; - if( (MUSh.channels = DoomIO.freadint(file)) == -1 ) return COMUSFILE ; - if( (MUSh.SecChannels = DoomIO.freadint(file)) == -1 ) return COMUSFILE ; - if( (MUSh.InstrCnt = DoomIO.freadint(file)) == -1 ) return COMUSFILE ; - if( (MUSh.dummy = DoomIO.freadint(file)) == -1 ) return COMUSFILE ; - - MUSh.instruments = new int[MUSh.InstrCnt]; - for (int i = 0; i < MUSh.InstrCnt; i++) { - if ((MUSh.instruments[i] = DoomIO.freadint(file)) == -1) { - return COMUSFILE ; - } - } - - return 0 ; - } - catch (Exception e) { - e.printStackTrace(); - return COMUSFILE; - } - } - - int WriteMIDheader( int ntrks, int division, Object file ) - { - try { - //_D_: those two lines for testing purposes only - //fisTest.close(); - //fisTest = new FileInputStream("C:\\Users\\David\\Desktop\\qmus2mid\\test.mid"); - - DoomIO.fwrite( MIDIMAGIC , 10, 1, file ) ; - DoomIO.fwrite2( DoomIO.toByteArray(ntrks), 2, file) ; - DoomIO.fwrite2( DoomIO.toByteArray(division), 2, file ) ; - } catch (IOException e) { - e.printStackTrace(); - } - - return 0 ; - } - - byte last(int e) { - return (byte)(e & 0x80); - } - byte event_type(int e) { - return (byte)((e & 0x7F) >> 4); - } - byte channel(int e) { - return (byte)(e & 0x0F); - } - - void TWriteString( char tracknum, String string, int length, - Track[] track ) - { - int i ; - - for( i = 0 ; i < length ; i++ ) - TWriteByte( tracknum, (byte)string.charAt(i), track ) ; - } - - - void WriteTrack( int tracknum, Object file, Track[] track ) - { - long size ; - int quot, rem ; - - try { - /* Do we risk overflow here ? */ - size = track[tracknum].current+4 ; - DoomIO.fwrite( "MTrk", 4, 1, file ); - if( tracknum == 0) size += 33 ; - - DoomIO.fwrite2( DoomIO.toByteArray((int)size, 4), 4, file ) ; - if( tracknum == 0) - DoomIO.fwrite( TRACKMAGIC1 + "Quick MUS->MID ! by S.Bacquet", 33, 1, file ) ; - - quot = (int) (track[tracknum].current / 4096) ; - rem = (int) (track[tracknum].current - quot*4096) ; - - DoomIO.fwrite(track[tracknum].data, (int)track[tracknum].current, 1, file ) ; - DoomIO.fwrite( TRACKMAGIC2, 4, 1, file ) ; - } - catch (Exception e) { - e.printStackTrace(); - } - } - - void WriteFirstTrack( Object file ) - { - try { - byte[] size = DoomIO.toByteArray(43, 4); - - DoomIO.fwrite( "MTrk", 4, 1, file ) ; - DoomIO.fwrite2( size, 4, file ) ; - DoomIO.fwrite( TRACKMAGIC3 , 4, 1, file ) ; - DoomIO.fwrite( "QMUS2MID (C) S.Bacquet", 22, 1, file ) ; - DoomIO.fwrite( TRACKMAGIC4, 6, 1, file ) ; - DoomIO.fwrite( TRACKMAGIC5, 7, 1, file ) ; - DoomIO.fwrite( TRACKMAGIC6, 4, 1, file ) ; - - } - catch (Exception e) { - e.printStackTrace(); - } - } - - long ReadTime( InputStream file ) throws IOException - { - long time = 0 ; - int byte_ ; - - do - { - byte_ = getc( file ) ; - if( byte_ != EOF ) time = (time << 7) + (byte_ & 0x7F) ; - } while( (byte_ != EOF) && ((byte_ & 0x80) != 0) ) ; - - return time ; - } - - byte FirstChannelAvailable( byte[] MUS2MIDchannel ) - { - int i ; - byte old15 = MUS2MIDchannel[15], max = -1 ; - - MUS2MIDchannel[15] = -1 ; - for( i = 0 ; i < 16 ; i++ ) - if( MUS2MIDchannel[i] > max ) max = MUS2MIDchannel[i] ; - MUS2MIDchannel[15] = old15 ; - - return (max == 8 ? 10 : (byte)(max+1)) ; - } - - - int getc(InputStream is) throws IOException { - return is.read(); - } - - int qmus2mid( InputStream mus, Object mid, boolean nodisplay, - int division, int BufferSize, boolean nocomp ) throws IOException - { - Track[] track = new Track[16] ; - for (int i = 0; i < track.length; i++) - track[i] = new Track(); - - int TrackCnt = 0 ; - byte et, MUSchannel, MIDIchannel, MIDItrack, NewEvent ; - int i, event, data, r ; - MUSheader MUSh = new MUSheader() ; - long DeltaTime, TotalTime = 0, time, min, n = 0 ; - byte[] MUS2MIDcontrol = new byte[] { - 0, /* Program change - not a MIDI control change */ - 0x00, /* Bank select */ - 0x01, /* Modulation pot */ - 0x07, /* Volume */ - 0x0A, /* Pan pot */ - 0x0B, /* Expression pot */ - 0x5B, /* Reverb depth */ - 0x5D, /* Chorus depth */ - 0x40, /* Sustain pedal */ - 0x43, /* Soft pedal */ - 0x78, /* All sounds off */ - 0x7B, /* All notes off */ - 0x7E, /* Mono */ - 0x7F, /* Poly */ - 0x79 /* Reset all controllers */ - }; - byte[] MIDIchan2track = new byte[16]; - byte[] MUS2MIDchannel = new byte[16] ; - char ouch = 0, sec ; - - DoomIO.writeEndian = DoomIO.Endian.LITTLE; - - r = ReadMUSheader( MUSh, mus ) ; - if( r != 0) - { - return r ; - } - /* if( fseek( file_mus, MUSh.ScoreStart, SEEK_SET ) ) + if ((MUSh.ScoreLength = DoomIO.freadint(file)) == -1) { + return COMUSFILE; + } + if ((MUSh.ScoreStart = DoomIO.freadint(file)) == -1) { + return COMUSFILE; + } + if ((MUSh.channels = DoomIO.freadint(file)) == -1) { + return COMUSFILE; + } + if ((MUSh.SecChannels = DoomIO.freadint(file)) == -1) { + return COMUSFILE; + } + if ((MUSh.InstrCnt = DoomIO.freadint(file)) == -1) { + return COMUSFILE; + } + if ((MUSh.dummy = DoomIO.freadint(file)) == -1) { + return COMUSFILE; + } + + MUSh.instruments = new int[MUSh.InstrCnt]; + for (int i = 0; i < MUSh.InstrCnt; i++) { + if ((MUSh.instruments[i] = DoomIO.freadint(file)) == -1) { + return COMUSFILE; + } + } + + return 0; + } catch (Exception e) { + LOGGER.log(Level.WARNING, "Could not read MUS header", e); + return COMUSFILE; + } + } + + int WriteMIDheader(int ntrks, int division, Object file) { + try { + //_D_: those two lines for testing purposes only + //fisTest.close(); + //fisTest = new FileInputStream("C:\\Users\\David\\Desktop\\qmus2mid\\test.mid"); + + DoomIO.fwrite(MIDIMAGIC, 10, 1, file); + DoomIO.fwrite2(DoomIO.toByteArray(ntrks), 2, file); + DoomIO.fwrite2(DoomIO.toByteArray(division), 2, file); + } catch (IOException e) { + LOGGER.log(Level.WARNING, "Could not write MID header", e); + } + + return 0; + } + + byte last(int e) { + return (byte) (e & 0x80); + } + + byte event_type(int e) { + return (byte) ((e & 0x7F) >> 4); + } + + byte channel(int e) { + return (byte) (e & 0x0F); + } + + void TWriteString(char tracknum, String string, int length, + Track[] track) { + int i; + + for (i = 0; i < length; i++) { + TWriteByte(tracknum, (byte) string.charAt(i), track); + } + } + + void WriteTrack(int tracknum, Object file, Track[] track) { + long size; + int quot, rem; + + try { + /* Do we risk overflow here ? */ + size = track[tracknum].current + 4; + DoomIO.fwrite("MTrk", 4, 1, file); + if (tracknum == 0) { + size += 33; + } + + DoomIO.fwrite2(DoomIO.toByteArray((int) size, 4), 4, file); + if (tracknum == 0) { + DoomIO.fwrite(TRACKMAGIC1 + "Quick MUS->MID ! by S.Bacquet", 33, 1, file); + } + + quot = (int) (track[tracknum].current / 4096); + rem = (int) (track[tracknum].current - quot * 4096); + + DoomIO.fwrite(track[tracknum].data, (int) track[tracknum].current, 1, file); + DoomIO.fwrite(TRACKMAGIC2, 4, 1, file); + } catch (Exception e) { + LOGGER.log(Level.WARNING, "Could not write track", e); + } + } + + void WriteFirstTrack(Object file) { + try { + byte[] size = DoomIO.toByteArray(43, 4); + + DoomIO.fwrite("MTrk", 4, 1, file); + DoomIO.fwrite2(size, 4, file); + DoomIO.fwrite(TRACKMAGIC3, 4, 1, file); + DoomIO.fwrite("QMUS2MID (C) S.Bacquet", 22, 1, file); + DoomIO.fwrite(TRACKMAGIC4, 6, 1, file); + DoomIO.fwrite(TRACKMAGIC5, 7, 1, file); + DoomIO.fwrite(TRACKMAGIC6, 4, 1, file); + + } catch (Exception e) { + LOGGER.log(Level.WARNING, "Could not write first track", e); + } + } + + long ReadTime(InputStream file) throws IOException { + long time = 0; + int byte_; + + do { + byte_ = getc(file); + if (byte_ != EOF) { + time = (time << 7) + (byte_ & 0x7F); + } + } while ((byte_ != EOF) && ((byte_ & 0x80) != 0)); + + return time; + } + + byte FirstChannelAvailable(byte[] MUS2MIDchannel) { + int i; + byte old15 = MUS2MIDchannel[15], max = -1; + + MUS2MIDchannel[15] = -1; + for (i = 0; i < 16; i++) { + if (MUS2MIDchannel[i] > max) { + max = MUS2MIDchannel[i]; + } + } + MUS2MIDchannel[15] = old15; + + return (max == 8 ? 10 : (byte) (max + 1)); + } + + int getc(InputStream is) throws IOException { + return is.read(); + } + + int qmus2mid(InputStream mus, Object mid, boolean nodisplay, + int division, int BufferSize, boolean nocomp) throws IOException { + Track[] track = new Track[16]; + for (int i = 0; i < track.length; i++) { + track[i] = new Track(); + } + + int TrackCnt = 0; + byte et, MUSchannel, MIDIchannel, MIDItrack, NewEvent; + int i, event, data, r; + MUSheader MUSh = new MUSheader(); + long DeltaTime, TotalTime = 0, time, min, n = 0; + byte[] MUS2MIDcontrol = new byte[]{ + 0, /* Program change - not a MIDI control change */ + 0x00, /* Bank select */ + 0x01, /* Modulation pot */ + 0x07, /* Volume */ + 0x0A, /* Pan pot */ + 0x0B, /* Expression pot */ + 0x5B, /* Reverb depth */ + 0x5D, /* Chorus depth */ + 0x40, /* Sustain pedal */ + 0x43, /* Soft pedal */ + 0x78, /* All sounds off */ + 0x7B, /* All notes off */ + 0x7E, /* Mono */ + 0x7F, /* Poly */ + 0x79 /* Reset all controllers */}; + byte[] MIDIchan2track = new byte[16]; + byte[] MUS2MIDchannel = new byte[16]; + char ouch = 0, sec; + + DoomIO.writeEndian = DoomIO.Endian.LITTLE; + + r = ReadMUSheader(MUSh, mus); + if (r != 0) { + return r; + } + /* if( fseek( file_mus, MUSh.ScoreStart, SEEK_SET ) ) { Close() ; return MUSFILECOR ; }*/ - if( !nodisplay ) - System.out.println( mus+" ("+mus.available()+" bytes) contains "+MUSh.channels+" melodic channel"+ (MUSh.channels >= 2 ? "s" : "")+"\n"); - - if( MUSh.channels > 15 ) /* <=> MUSchannels+drums > 16 */ - { - return TOOMCHAN ; - } - - for( i = 0 ; i < 16 ; i++ ) - { - MUS2MIDchannel[i] = -1 ; - track[i].current = 0 ; - track[i].vel = 64 ; - track[i].DeltaTime = 0 ; - track[i].LastEvent = 0 ; - track[i].data = null ; - } - if( BufferSize != 0) - { - TRACKBUFFERSIZE = ((long) BufferSize) << 10 ; - if( !nodisplay ) - System.out.println( "Track buffer size set to "+BufferSize+" KB.\n") ; - } - - if( !nodisplay ) - { - System.out.println( "Converting..." ) ; - } - event = getc( mus ) ; - et = event_type( event ) ; - MUSchannel = channel( event ) ; - while( (et != 6) && mus.available() > 0 && (event != EOF) ) - { - if( MUS2MIDchannel[MUSchannel] == -1 ) - { - MIDIchannel = MUS2MIDchannel[MUSchannel ] = - (MUSchannel == 15 ? 9 : FirstChannelAvailable( MUS2MIDchannel)) ; - MIDItrack = MIDIchan2track[MIDIchannel] = (byte)TrackCnt++ ; - if( (track[MIDItrack].data = new byte[(int)TRACKBUFFERSIZE]) == null ) - { - return MEMALLOC ; - } - } - else - { - MIDIchannel = MUS2MIDchannel[MUSchannel] ; - MIDItrack = MIDIchan2track [MIDIchannel] ; - } - TWriteVarLen( MIDItrack, track[MIDItrack].DeltaTime, track ) ; - track[MIDItrack].DeltaTime = 0 ; - switch( et ) - { - case 0 : /* release note */ - NewEvent = (byte)(0x90 | MIDIchannel) ; - if( (NewEvent != track[MIDItrack].LastEvent) || (nocomp) ) - { - TWriteByte( MIDItrack, NewEvent, track ) ; - track[MIDItrack].LastEvent = NewEvent ; - } - else - n++ ; - data = getc( mus ) ; - TWriteByte( MIDItrack, (byte)data, track ) ; - TWriteByte( MIDItrack, (byte)0, track ) ; - break ; - case 1 : - NewEvent = (byte)(0x90 | MIDIchannel) ; - if( (NewEvent != track[MIDItrack].LastEvent) || (nocomp) ) - { - TWriteByte( MIDItrack, NewEvent, track ) ; - track[MIDItrack].LastEvent = NewEvent ; - } - else - n++ ; - data = getc( mus ) ; - TWriteByte( MIDItrack, (byte)(data & 0x7F), track ) ; - if( (data & 0x80) != 0 ) - track[MIDItrack].vel = (byte)getc( mus ) ; - TWriteByte( MIDItrack, (byte)track[MIDItrack].vel, track ) ; - break ; - case 2 : - NewEvent = (byte)(0xE0 | MIDIchannel) ; - if( (NewEvent != track[MIDItrack].LastEvent) || (nocomp) ) - { - TWriteByte( MIDItrack, NewEvent, track ) ; - track[MIDItrack].LastEvent = NewEvent ; - } - else - n++ ; - data = getc( mus ) ; - TWriteByte( MIDItrack, (byte)((data & 1) << 6), track ) ; - TWriteByte( MIDItrack, (byte)(data >> 1), track ) ; - break ; - case 3 : - NewEvent = (byte)(0xB0 | MIDIchannel) ; - if( (NewEvent != track[MIDItrack].LastEvent) || (nocomp) ) - { - TWriteByte( MIDItrack, NewEvent, track ) ; - track[MIDItrack].LastEvent = NewEvent ; - } - else - n++ ; - data = getc( mus ) ; - TWriteByte( MIDItrack, MUS2MIDcontrol[data], track ) ; - if( data == 12 ) - TWriteByte( MIDItrack, (byte)(MUSh.channels+1), track ) ; - else - TWriteByte( MIDItrack, (byte)0, track ) ; - break ; - case 4 : - data = getc( mus ) ; - if( data != 0 ) - { - NewEvent = (byte)(0xB0 | MIDIchannel) ; - if( (NewEvent != track[MIDItrack].LastEvent) || (nocomp) ) - { - TWriteByte( MIDItrack, NewEvent, track ) ; - track[MIDItrack].LastEvent = NewEvent ; - } - else - n++ ; - TWriteByte( MIDItrack, MUS2MIDcontrol[data], track ) ; - } - else - { - NewEvent = (byte)(0xC0 | MIDIchannel) ; - if( (NewEvent != track[MIDItrack].LastEvent) || (nocomp) ) - { - TWriteByte( MIDItrack, NewEvent, track ) ; - track[MIDItrack].LastEvent = NewEvent ; - } - else - n++ ; - } - data = getc( mus ) ; - TWriteByte( MIDItrack, (byte)data, track ) ; - break ; - case 5 : - case 7 : - return MUSFILECOR ; - default : break ; - } - if( last( event ) != 0 ) - { - DeltaTime = ReadTime( mus ) ; - TotalTime += DeltaTime ; - for( i = 0 ; i < (int) TrackCnt ; i++ ) - track[i].DeltaTime += DeltaTime ; - } - event = getc( mus ) ; - if( event != EOF ) - { - et = event_type( event ) ; - MUSchannel = channel( event ) ; - } - else - ouch = 1 ; - } - if( !nodisplay ) System.out.println( "done !\n" ) ; - if( ouch != 0 ) - System.out.println( "WARNING : There are bytes missing at the end of "+mus+".\n "+ - "The end of the MIDI file might not fit the original one.\n") ; - if( division == 0 ) - division = 89 ; - else - if( !nodisplay ) System.out.println( "Ticks per quarter note set to "+division+".\n") ; - if( !nodisplay ) - { - if( division != 89 ) - { - time = TotalTime / 140 ; - min = time / 60 ; - sec = (char) (time - min*60) ; - //System.out.println( "Playing time of the MUS file : %u'%.2u''.\n", min, sec ) ; - } - time = (TotalTime * 89) / (140 * division) ; - min = time / 60 ; - sec = (char) (time - min*60) ; - if( division != 89 ) - System.out.println( " MID file" ) ; - else - System.out.println( "Playing time: "+min+"min "+sec+"sec") ; - } - if( !nodisplay ) - { - System.out.println("Writing..." ) ; - } - WriteMIDheader( TrackCnt+1, division, mid ) ; - WriteFirstTrack( mid ) ; - for( i = 0 ; i < (int) TrackCnt ; i++ ) - WriteTrack( i, mid, track ) ; - if( !nodisplay ) - System.out.println( "done !\n" ) ; - if( !nodisplay && (!nocomp) ) - System.out.println( "Compression : %u%%.\n"/*, - (100 * n) / (n+ (long) ftell( mid ))*/ ) ; - - return 0 ; - } - - - int convert( String mus, String mid, boolean nodisplay, int div, - int size, boolean nocomp, Ptr ow ) throws IOException -{ - InputStream is = new BufferedInputStream(new FileInputStream(new File(mid))); - OutputStream os = new BufferedOutputStream(new FileOutputStream(new File(mid))); - - int error; - //struct stat file_data ; - char[] buffer = new char[30] ; - - - /* we don't need _all_ that checking, do we ? */ - /* Answer : it's more user-friendly */ - /*#ifdef MSDOG + if (!nodisplay) { + LOGGER.log(Level.FINE, String.format("stream (%d bytes) contains %d melodic channel(s)", mus.available(), MUSh.channels)); + } + + if (MUSh.channels > 15) /* <=> MUSchannels+drums > 16 */ { + return TOOMCHAN; + } + + for (i = 0; i < 16; i++) { + MUS2MIDchannel[i] = -1; + track[i].current = 0; + track[i].vel = 64; + track[i].DeltaTime = 0; + track[i].LastEvent = 0; + track[i].data = null; + } + if (BufferSize != 0) { + TRACKBUFFERSIZE = ((long) BufferSize) << 10; + if (!nodisplay) { + LOGGER.log(Level.FINE, String.format("Track buffer size set to %d KB.", BufferSize)); + } + } + + if (!nodisplay) { + LOGGER.log(Level.FINE, "Converting..."); + } + event = getc(mus); + et = event_type(event); + MUSchannel = channel(event); + while ((et != 6) && mus.available() > 0 && (event != EOF)) { + if (MUS2MIDchannel[MUSchannel] == -1) { + MIDIchannel = MUS2MIDchannel[MUSchannel] + = (MUSchannel == 15 ? 9 : FirstChannelAvailable(MUS2MIDchannel)); + MIDItrack = MIDIchan2track[MIDIchannel] = (byte) TrackCnt++; + if ((track[MIDItrack].data = new byte[(int) TRACKBUFFERSIZE]) == null) { + return MEMALLOC; + } + } else { + MIDIchannel = MUS2MIDchannel[MUSchannel]; + MIDItrack = MIDIchan2track[MIDIchannel]; + } + TWriteVarLen(MIDItrack, track[MIDItrack].DeltaTime, track); + track[MIDItrack].DeltaTime = 0; + switch (et) { + case 0: + /* release note */ + NewEvent = (byte) (0x90 | MIDIchannel); + if ((NewEvent != track[MIDItrack].LastEvent) || (nocomp)) { + TWriteByte(MIDItrack, NewEvent, track); + track[MIDItrack].LastEvent = NewEvent; + } else { + n++; + } + data = getc(mus); + TWriteByte(MIDItrack, (byte) data, track); + TWriteByte(MIDItrack, (byte) 0, track); + break; + case 1: + NewEvent = (byte) (0x90 | MIDIchannel); + if ((NewEvent != track[MIDItrack].LastEvent) || (nocomp)) { + TWriteByte(MIDItrack, NewEvent, track); + track[MIDItrack].LastEvent = NewEvent; + } else { + n++; + } + data = getc(mus); + TWriteByte(MIDItrack, (byte) (data & 0x7F), track); + if ((data & 0x80) != 0) { + track[MIDItrack].vel = (byte) getc(mus); + } + TWriteByte(MIDItrack, (byte) track[MIDItrack].vel, track); + break; + case 2: + NewEvent = (byte) (0xE0 | MIDIchannel); + if ((NewEvent != track[MIDItrack].LastEvent) || (nocomp)) { + TWriteByte(MIDItrack, NewEvent, track); + track[MIDItrack].LastEvent = NewEvent; + } else { + n++; + } + data = getc(mus); + TWriteByte(MIDItrack, (byte) ((data & 1) << 6), track); + TWriteByte(MIDItrack, (byte) (data >> 1), track); + break; + case 3: + NewEvent = (byte) (0xB0 | MIDIchannel); + if ((NewEvent != track[MIDItrack].LastEvent) || (nocomp)) { + TWriteByte(MIDItrack, NewEvent, track); + track[MIDItrack].LastEvent = NewEvent; + } else { + n++; + } + data = getc(mus); + TWriteByte(MIDItrack, MUS2MIDcontrol[data], track); + if (data == 12) { + TWriteByte(MIDItrack, (byte) (MUSh.channels + 1), track); + } else { + TWriteByte(MIDItrack, (byte) 0, track); + } + break; + case 4: + data = getc(mus); + if (data != 0) { + NewEvent = (byte) (0xB0 | MIDIchannel); + if ((NewEvent != track[MIDItrack].LastEvent) || (nocomp)) { + TWriteByte(MIDItrack, NewEvent, track); + track[MIDItrack].LastEvent = NewEvent; + } else { + n++; + } + TWriteByte(MIDItrack, MUS2MIDcontrol[data], track); + } else { + NewEvent = (byte) (0xC0 | MIDIchannel); + if ((NewEvent != track[MIDItrack].LastEvent) || (nocomp)) { + TWriteByte(MIDItrack, NewEvent, track); + track[MIDItrack].LastEvent = NewEvent; + } else { + n++; + } + } + data = getc(mus); + TWriteByte(MIDItrack, (byte) data, track); + break; + case 5: + case 7: + return MUSFILECOR; + default: + break; + } + if (last(event) != 0) { + DeltaTime = ReadTime(mus); + TotalTime += DeltaTime; + for (i = 0; i < (int) TrackCnt; i++) { + track[i].DeltaTime += DeltaTime; + } + } + event = getc(mus); + if (event != EOF) { + et = event_type(event); + MUSchannel = channel(event); + } else { + ouch = 1; + } + } + if (!nodisplay) { + LOGGER.log(Level.FINE, "done!"); + } + if (ouch != 0) { + LOGGER.log(Level.WARNING, "WARNING: There are bytes missing at the end of stream. The end of the MIDI file might not fit the original one."); + } + if (division == 0) { + division = 89; + } else if (!nodisplay) { + LOGGER.log(Level.FINE, String.format("Ticks per quarter note set to %d", division)); + } + if (!nodisplay) { + if (division != 89) { + time = TotalTime / 140; + min = time / 60; + sec = (char) (time - min * 60); + //System.out.println( "Playing time of the MUS file : %u'%.2u''.\n", min, sec ) ; + } + time = (TotalTime * 89) / (140 * division); + min = time / 60; + sec = (char) (time - min * 60); + if (division != 89) { + LOGGER.log(Level.FINE, "MID file"); + } else { + LOGGER.log(Level.FINE, String.format("Playing time: %dmin %dsec", (int) min, (int) sec)); + } + } + if (!nodisplay) { + LOGGER.log(Level.FINE, "Writing..."); + } + WriteMIDheader(TrackCnt + 1, division, mid); + WriteFirstTrack(mid); + for (i = 0; i < (int) TrackCnt; i++) { + WriteTrack(i, mid, track); + } + if (!nodisplay) { + LOGGER.log(Level.FINE, "done !"); + } + //if (!nodisplay && (!nocomp)) { + // System.out.println("Compression : %u%%.\n"/*, + // (100 * n) / (n+ (long) ftell( mid ))*/); + //} + return 0; + } + + int convert(String mus, String mid, boolean nodisplay, int div, + int size, boolean nocomp, Ptr ow) throws IOException { + InputStream is = new BufferedInputStream(new FileInputStream(new File(mid))); + OutputStream os = new BufferedOutputStream(new FileOutputStream(new File(mid))); + + int error; + //struct stat file_data ; + char[] buffer = new char[30]; + + + /* we don't need _all_ that checking, do we ? */ + /* Answer : it's more user-friendly */ + /*#ifdef MSDOG if( access( mus, 0 ) ) { @@ -558,7 +566,7 @@ int convert( String mus, String mid, boolean nodisplay, int div, } } #else*/ - /*if ( ow.get() == 0 ) { + /*if ( ow.get() == 0 ) { file = fopen(mid, "r"); if ( file ) { fclose(file); @@ -566,57 +574,58 @@ int convert( String mus, String mid, boolean nodisplay, int div, return 2 ; } }*/ - /*#endif*/ - - return convert(is, os, nodisplay, div, size, nocomp, ow); -} - - int convert( InputStream mus, Object mid, boolean nodisplay, int div, - int size, boolean nocomp, Ptr ow ) throws IOException -{ - int error = qmus2mid( mus, mid, nodisplay, div, size, nocomp ) ; - - if( error != 0 ) - { - System.out.println( "ERROR : " ) ; - switch( error ) - { - case NOTMUSFILE : - System.out.println( "%s is not a MUS file.\n"/*, mus*/ ) ; break ; - case COMUSFILE : - System.out.println( "Can't open %s for read.\n"/*, mus*/ ) ; break ; - case COTMPFILE : - System.out.println( "Can't open temp file.\n" ) ; break ; - case CWMIDFILE : - System.out.println( "Can't write %s (?).\n"/*, mid */) ; break ; - case MUSFILECOR : - System.out.println( "%s is corrupted.\n"/*, mus*/) ; break ; - case TOOMCHAN : - System.out.println( "%s contains more than 16 channels.\n"/*, mus*/ ) ; break ; - case MEMALLOC : - System.out.println( "Not enough memory.\n" ) ; break ; - default : break ; - } - return 4 ; - } - - if( !nodisplay ) - { - System.out.println( mus+" converted successfully.\n") ; - /*if( (file = fopen( mid, "rb" )) != NULL ) + /*#endif*/ + return convert(is, os, nodisplay, div, size, nocomp, ow); + } + + int convert(InputStream mus, Object mid, boolean nodisplay, int div, + int size, boolean nocomp, Ptr ow) throws IOException { + int error = qmus2mid(mus, mid, nodisplay, div, size, nocomp); + + if (error != 0) { + switch (error) { + case NOTMUSFILE: + LOGGER.log(Level.SEVERE, "ERROR: stream is not a MUS file."/*, mus*/); + break; + case COMUSFILE: + LOGGER.log(Level.SEVERE, "ERROR: Can't open stream for read."/*, mus*/); + break; + case COTMPFILE: + LOGGER.log(Level.SEVERE, "ERROR: Can't open temp file."); + break; + case CWMIDFILE: + LOGGER.log(Level.SEVERE, "ERROR: Can't write stream (?)."/*, mid */); + break; + case MUSFILECOR: + LOGGER.log(Level.SEVERE, "ERROR: stream is corrupted."/*, mus*/); + break; + case TOOMCHAN: + LOGGER.log(Level.SEVERE, "ERROR: stream contains more than 16 channels."/*, mus*/); + break; + case MEMALLOC: + LOGGER.log(Level.SEVERE, "ERROR: Not enough memory."); + break; + default: + break; + } + return 4; + } + + if (!nodisplay) { + LOGGER.log(Level.FINE, "stream converted successfully."); + /*if( (file = fopen( mid, "rb" )) != NULL ) { //stat( mid, &file_data ) ; fclose( file ) ; sSystem.out.println( buffer, " : %lu bytes", (long) file_data.st_size ) ; }*/ - - /*System.out.println( "%s (%scompressed) written%s.\n", mid, nocomp ? "NOT " : "", - file ? buffer : "" ) ;*/ - } - return 0 ; - } + /*System.out.println( "%s (%scompressed) written%s.\n", mid, nocomp ? "NOT " : "", + file ? buffer : "" ) ;*/ + } + return 0; + } // int CheckParm( char[] check, int argc, char *argv[] ) // { @@ -632,19 +641,14 @@ int convert( InputStream mus, Object mid, boolean nodisplay, int div, // // return 0; // } - - - void PrintHeader( ) - { + void PrintHeader() { // System.out.println( "===============================================================================\n" // " Quick MUS->MID v2.0 ! (C) 1995,96 Sebastien Bacquet\n" // " E-mail : bacquet@iie.cnam.fr\n" // "===============================================================================\n" ) ; - } + } - - void PrintSyntax( ) - { + void PrintSyntax() { // PrintHeader() ; // System.out.println( // #ifdef MSDOG @@ -665,25 +669,23 @@ void PrintSyntax( ) // "Default = 64 KB\n" // " -t ### : Ticks per quarter note. Default = 89\n" // ) ; - } - + } - int main( int argc, char[] argv ) - { - int div = 0, ow = 1, nocomp = 0, size = 0, n ; - boolean nodisplay = false; - /*#ifdef MSDOG + int main(int argc, char[] argv) { + int div = 0, ow = 1, nocomp = 0, size = 0, n; + boolean nodisplay = false; + /*#ifdef MSDOG int FileCount, query = 0, i, line = 0 ; char mus[MAXPATH], mid[MAXPATH], drive[MAXDRIVE], middrive[MAXDRIVE], dir[MAXDIR], middir[MAXDIR], musname[MAXFILE], midname[MAXFILE], ext[MAXEXT] ; struct stat s ; #else*/ - String mus, mid; - /*#endif*/ + String mus, mid; + /*#endif*/ - /*#ifndef MSDOG + /*#ifndef MSDOG if ( !LittleEndian() ) { System.out.println("\nSorry, this program presently only works on " "little-endian machines... \n\n"); @@ -691,7 +693,7 @@ int main( int argc, char[] argv ) } #endif*/ - /*#ifdef MSDOG + /*#ifdef MSDOG if( (argc == 1) || (argv[1][0] == '-') ) #else if( argc < 3 ) @@ -701,7 +703,7 @@ int main( int argc, char[] argv ) exit( EXIT_FAILURE ) ; }*/ - /*#ifdef MSDOG + /*#ifdef MSDOG if( (strrchr( argv[1], '*' ) != NULL) || (strrchr( argv[1], '?' ) != NULL) ) { PrintHeader() ; @@ -716,24 +718,25 @@ int main( int argc, char[] argv ) exit( EXIT_FAILURE ) ; } #else*/ - //strncpy( mus, argv[1], FILENAME_MAX ) ; - //strncpy( mid, argv[2], FILENAME_MAX ) ; - /*#endif*/ + //strncpy( mus, argv[1], FILENAME_MAX ) ; + //strncpy( mid, argv[2], FILENAME_MAX ) ; + /*#endif*/ - /*#ifdef MSDOG + /*#ifdef MSDOG if( CheckParm( "-query", argc, argv ) ) query = 1 ; #endif*/ - /* if( CheckParm( "-nodisp", argc, argv ) ) + /* if( CheckParm( "-nodisp", argc, argv ) ) nodisplay = 1 ; - */ - if( !nodisplay ) - PrintHeader() ; - - /*if( (n = CheckParm( "-size", argc, argv )) != 0 ) + */ + if (!nodisplay) { + PrintHeader(); + } + + /*if( (n = CheckParm( "-size", argc, argv )) != 0 ) size = atoi( argv[n+1] ) ;*/ - /*#ifdef MSDOG + /*#ifdef MSDOG if( CheckParm( "-ow", argc, argv ) ) ow += 1 ; #endif @@ -744,7 +747,7 @@ int main( int argc, char[] argv ) if( CheckParm( "-nocomp", argc, argv ) ) nocomp = 1 ;*/ - /*#ifdef MSDOG + /*#ifdef MSDOG for( FileCount = 1 ; (FileCount < argc) && (argv[FileCount][0] != '-') ; FileCount++ ) ; FileCount-- ; @@ -827,11 +830,9 @@ int main( int argc, char[] argv ) System.out.println( "Sorry, there is no MUS file matching...\n" ) ; #else*/ - //convert( mus, mid, nodisplay, div, size, nocomp, ow ) ; + //convert( mus, mid, nodisplay, div, size, nocomp, ow ) ; /* #endif*/ - - return 0; - } - + return 0; + } } diff --git a/src/s/SpeakerDoomSoundDriver.java b/src/s/SpeakerDoomSoundDriver.java index 7bd7fcad..3300ef8a 100644 --- a/src/s/SpeakerDoomSoundDriver.java +++ b/src/s/SpeakerDoomSoundDriver.java @@ -1,6 +1,9 @@ package s; import doom.DoomMain; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; /** A variation of the Classic Sound Driver, decoding the DP-lumps * instead of the DS. A better way would be to build-in an @@ -9,32 +12,30 @@ * @author Maes * */ - public class SpeakerDoomSoundDriver extends ClassicDoomSoundDriver { + private static final Logger LOGGER = Loggers.getLogger(SpeakerDoomSoundDriver.class.getName()); + public SpeakerDoomSoundDriver(DoomMain DM, int numChannels) { super(DM, numChannels); // TODO Auto-generated constructor stub } - + /** Rigged so it gets SPEAKER sounds instead of regular ones */ - @Override - protected byte[] getsfx - ( String sfxname, - int[] len, int index ) - { - byte[] sfx; - byte[] paddedsfx; - int i; - int size; - int paddedsize; - String name; - int sfxlump; + protected byte[] getsfx(String sfxname, + int[] len, int index) { + byte[] sfx; + byte[] paddedsfx; + int i; + int size; + int paddedsize; + String name; + int sfxlump; // Get the sound data from the WAD, allocate lump // in zone memory. - name=String.format("dp%s", sfxname).toUpperCase(); + name = String.format("dp%s", sfxname).toUpperCase(); // Now, there is a severe problem with the // sound handling, in it is not (yet/anymore) @@ -46,44 +47,45 @@ public SpeakerDoomSoundDriver(DoomMain DM, int numChannels) { // I do not do runtime patches to that // variable. Instead, we will use a // default sound for replacement. - if ( DM.wadLoader.CheckNumForName(name) == -1 ) + if (DM.wadLoader.CheckNumForName(name) == -1) { sfxlump = DM.wadLoader.GetNumForName("dppistol"); - else + } else { sfxlump = DM.wadLoader.GetNumForName(name); + } // We must first load and convert it to raw samples. - - SpeakerSound SP=(SpeakerSound) DM.wadLoader.CacheLumpNum(sfxlump, 0,SpeakerSound.class); - + SpeakerSound SP = (SpeakerSound) DM.wadLoader.CacheLumpNum(sfxlump, 0, SpeakerSound.class); + sfx = SP.toRawSample(); - + size = sfx.length; // MAES: A-ha! So that's how they do it. // SOund effects are padded to the highest multiple integer of // the mixing buffer's size (with silence) - - paddedsize = ((size-8 + (SAMPLECOUNT-1)) / SAMPLECOUNT) * SAMPLECOUNT; + paddedsize = ((size - 8 + (SAMPLECOUNT - 1)) / SAMPLECOUNT) * SAMPLECOUNT; // Allocate from zone memory. paddedsfx = new byte[paddedsize]; // Now copy and pad. The first 8 bytes are header info, so we discard them. - System.arraycopy(sfx,8, paddedsfx, 0,size-8 ); - - for (i=size-8 ; i phonemes=new Hashtable(); - - public static byte[] getPhoneme(int phoneme){ - - if (!phonemes.containsKey(phoneme)){ - + + private static Hashtable phonemes = new Hashtable<>(); + + public static byte[] getPhoneme(int phoneme) { + + if (!phonemes.containsKey(phoneme)) { + // Generate a square wave with a duration of 1/140th of a second - int samples=11025/140; - byte[] tmp=new byte[samples]; + int samples = 11025 / 140; + byte[] tmp = new byte[samples]; - float frequency=f[phoneme]; - for (int i=0;i cachedSounds = - new HashMap(); + protected HashMap cachedSounds + = new HashMap<>(); protected final Timer MIXTIMER; - + public SuperDoomSoundDriver(DoomMain DM, int numChannels) { - super(DM,numChannels); + super(DM, numChannels); channels = new boolean[numChannels]; produce = new Semaphore(1); consume = new Semaphore(1); update_mixer = new Semaphore(1); produce.drainPermits(); update_mixer.drainPermits(); - this.MIXSRV=new MixServer(numChannels); - MIXTIMER= new Timer(true); + this.MIXSRV = new MixServer(numChannels); + MIXTIMER = new Timer(true); // Sound tics every 1/35th of a second. Grossly // inaccurate under Windows though, will get rounded // down to the closest multiple of 15 or 16 ms. - MIXTIMER.schedule(new SoundTimer(), 0,SOUND_PERIOD); + MIXTIMER.schedule(new SoundTimer(), 0, SOUND_PERIOD); } - - - /** These are still defined here to decouple them from the mixer's * ones, however they serve more as placeholders/status indicators; */ @@ -92,12 +92,11 @@ public SuperDoomSoundDriver(DoomMain DM, int numChannels) { * hardware channels (left and right, that is). This function currently * supports only 16bit. */ - public void UpdateSound() { - // This is pretty much a dummy. - // The mixing thread goes on by itself, guaranteeing that it will - // carry out at least currently enqueued mixing messages, regardless - // of how badly the engine lags. + // This is pretty much a dummy. + // The mixing thread goes on by itself, guaranteeing that it will + // carry out at least currently enqueued mixing messages, regardless + // of how badly the engine lags. } @@ -106,7 +105,6 @@ public void UpdateSound() { * the old DPMS based DOS version, this were simply dummies in the Linux * version. See soundserver initdata(). */ - @Override public void SetChannels(int numChannels) { // Init internal lookups (raw data, mixing buffer, channels). @@ -119,15 +117,15 @@ public void SetChannels(int numChannels) { for (int i = 0; i < this.numChannels; i++) { channels[i] = false; } - + generateStepTable(steptablemid); generateVolumeLUT(); } - - protected PlaybackServer SOUNDSRV; + + protected PlaybackServer SOUNDSRV; protected final MixServer MIXSRV; - + protected Thread MIXTHREAD; protected Thread SOUNDTHREAD; @@ -135,7 +133,7 @@ public void SetChannels(int numChannels) { public boolean InitSound() { // Secure and configure sound device first. - System.err.print("I_InitSound: "); + LOGGER.log(Level.INFO, "I_InitSound"); // We only need a single data line. // PCM, signed, 16-bit, stereo, 22025 KHz, 2048 bytes per "frame", @@ -146,20 +144,19 @@ public boolean InitSound() { if (AudioSystem.isLineSupported(info)) try { - line = (SourceDataLine) AudioSystem.getSourceDataLine(format); - line.open(format, AUDIOLINE_BUFFER); - } catch (Exception e) { - e.printStackTrace(); - System.err.print("Could not play signed 16 data\n"); - return false; - } + line = (SourceDataLine) AudioSystem.getSourceDataLine(format); + line.open(format, AUDIOLINE_BUFFER); + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "Could not play signed 16 data", e); + return false; + } if (line != null) { - System.err.print("configured audio device\n"); + LOGGER.log(Level.INFO, "configured audio device"); line.start(); } else { - System.err.print("could not configure audio device\n"); - return false; + LOGGER.log(Level.SEVERE, "could not configure audio device"); + return false; } SOUNDSRV = new PlaybackServer(line); @@ -167,20 +164,20 @@ public boolean InitSound() { SOUNDTHREAD.setDaemon(true); SOUNDTHREAD.start(); // Vroom! - MIXTHREAD= new Thread(MIXSRV); + MIXTHREAD = new Thread(MIXSRV); MIXTHREAD.setDaemon(true); MIXTHREAD.start(); - + // Initialize external data (all sounds) at start, keep static. - System.err.print("I_InitSound: "); + LOGGER.log(Level.INFO, "I_InitSound"); super.initSound8(); - System.err.print("pre-cached all sound data\n"); + LOGGER.log(Level.INFO, "pre-cached all sound data"); // Finished initialization. - System.err.print("I_InitSound: sound module ready\n"); - + LOGGER.log(Level.INFO, "I_InitSound: sound module ready"); + return true; } @@ -197,8 +194,8 @@ protected int addsfx(int sfxid, int volume, int step, int seperation) { int rightvol; int leftvol; - int broken=-1; - + int broken = -1; + // Chainsaw troubles. // Play these sound effects only one at a time. if (sfxid == sfxenum_t.sfx_sawup.ordinal() @@ -212,60 +209,62 @@ protected int addsfx(int sfxid, int volume, int step, int seperation) { // Active, and using the same SFX? if (channels[i] && (channelids[i] == sfxid)) { // Reset. - - MixMessage m=new MixMessage(); - m.stop=true; - + + MixMessage m = new MixMessage(); + m.stop = true; + // We are sure that iff, // there will only be one. - broken=i; + broken = i; break; } } } // Loop all channels to find oldest SFX. - if (broken>=0) { - i=broken; - oldestnum=broken; - } - else - for (i = 0; (i < numChannels) && channels[i]; i++) { - if (channelstart[i] < oldest) { - oldestnum = i; + if (broken >= 0) { + i = broken; + oldestnum = broken; + } else { + for (i = 0; (i < numChannels) && channels[i]; i++) { + if (channelstart[i] < oldest) { + oldestnum = i; + } } } oldest = channelstart[oldestnum]; - + // Tales from the cryptic. // If we found a channel, fine. // If not, we simply overwrite the first one, 0. // Probably only happens at startup. - if (i == numChannels) + if (i == numChannels) { slot = oldestnum; - else + } else { slot = i; + } + + MixMessage m = new MixMessage(); - - MixMessage m=new MixMessage(); - // Okay, in the less recent channel, // we will handle the new SFX. // Set pointer to raw data. - channels[slot]=true; - m.channel=slot; - m.data=S_sfx[sfxid].data; + channels[slot] = true; + m.channel = slot; + m.data = S_sfx[sfxid].data; // MAES: if you don't zero-out the channel pointer here, it gets ugly - m.pointer= 0; + m.pointer = 0; // Set pointer to end of raw data. m.end = lengths[sfxid]; // Reset current handle number, limited to 0..100. if (handlenums == 0) // was !handlenums, so it's actually 1...100? + { handlenums = 100; + } // Assign current handle number. // Preserved so sounds could be stopped (unused). @@ -276,7 +275,7 @@ protected int addsfx(int sfxid, int volume, int step, int seperation) { // Set stepping??? // Kinda getting the impression this is never used. // MAES: you're wrong amigo. - m.step= step; + m.step = step; // ??? m.remainder = 0; // Should be gametic, I presume. @@ -294,12 +293,13 @@ protected int addsfx(int sfxid, int volume, int step, int seperation) { rightvol = volume - ((volume * seperation * seperation) >> 16); // Sanity check, clamp volume. - - if (rightvol < 0 || rightvol > 127) + if (rightvol < 0 || rightvol > 127) { DM.doomSystem.Error("rightvol out of bounds"); + } - if (leftvol < 0 || leftvol > 127) + if (leftvol < 0 || leftvol > 127) { DM.doomSystem.Error("leftvol out of bounds"); + } // Get the proper lookup table piece // for this volume level??? @@ -310,14 +310,17 @@ protected int addsfx(int sfxid, int volume, int step, int seperation) { // e.g. for avoiding duplicates of chainsaw. channelids[slot] = sfxid; - if (D) System.err.println(channelStatus()); - if (D) System.err.printf( - "Playing sfxid %d handle %d length %d vol %d on channel %d\n", - sfxid, rc, S_sfx[sfxid].data.length, volume, slot); + if (D) { + LOGGER.log(Level.FINE, String.valueOf(channelStatus())); + } + if (D) { + LOGGER.log(Level.FINE, String.format( + "Playing sfxid %d handle %d length %d vol %d on channel %d", + sfxid, rc, S_sfx[sfxid].data.length, volume, slot)); + } - MIXSRV.submitMixMessage(m); - + // You tell me. return rc; } @@ -331,21 +334,19 @@ public void ShutdownSound() { produce.release(); update_mixer.release(); - int i=0; + int i = 0; do { - done=true; - for (i=0; i < numChannels; i++) { - // If even one channel is playing, loop again. - done&=!channels[i]; - } - //System.out.println(done+" "+this.channelStatus()); - - } while (!done); - - + done = true; + for (i = 0; i < numChannels; i++) { + // If even one channel is playing, loop again. + done &= !channels[i]; + } + //System.out.println(done+" "+this.channelStatus()); + + } while (!done); + this.line.flush(); - - + SOUNDSRV.terminate = true; MIXSRV.terminate = true; produce.release(); @@ -354,11 +355,11 @@ public void ShutdownSound() { SOUNDTHREAD.join(); MIXTHREAD.join(); } catch (InterruptedException e) { - // Well, I don't care. + // Well, I don't care. } - System.err.printf("3\n"); + //System.err.printf("3\n"); line.close(); - System.err.printf("4\n"); + //System.err.printf("4\n"); } @@ -373,8 +374,8 @@ public PlaybackServer(SourceDataLine line) { private SourceDataLine auline; - private ArrayBlockingQueue audiochunks = - new ArrayBlockingQueue(BUFFER_CHUNKS * 2); + private ArrayBlockingQueue audiochunks + = new ArrayBlockingQueue<>(BUFFER_CHUNKS * 2); public void addChunk(AudioChunk chunk) { audiochunks.offer(chunk); @@ -387,28 +388,24 @@ public void run() { while (!terminate) { // while (timing[mixstate]<=mytime){ - // Try acquiring a produce permit before going on. - try { //System.err.print("Waiting for a permit..."); produce.acquire(); //System.err.print("...got it\n"); } catch (InterruptedException e) { // Well, ouch. - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "PlaybackServer run failure", e); } int chunks = 0; // System.err.printf("Audio queue has %d chunks\n",audiochunks.size()); - // Play back only at most a given number of chunks once you reach // this spot. - - int atMost=Math.min(ISoundDriver.BUFFER_CHUNKS,audiochunks.size()); - - while (atMost-->0){ + int atMost = Math.min(ISoundDriver.BUFFER_CHUNKS, audiochunks.size()); + + while (atMost-- > 0) { AudioChunk chunk = null; try { @@ -423,16 +420,15 @@ public void run() { chunk.free = true; audiochunkpool.checkIn(chunk); } - + //System.err.println(">>>>>>>>>>>>>>>>> CHUNKS " +chunks); // Signal that we consumed a whole buffer and we are ready for // another one. - consume.release(); } } } - + /** A single channel does carry a lot of crap, figuratively speaking. * Instead of making updates to ALL channel parameters, it makes more * sense having a "mixing queue" with instructions that tell the @@ -442,28 +438,29 @@ public void run() { * */ protected class MixMessage { - /** If this is set, the mixer considers that channel "muted" */ - public boolean stop; - - /** This signals an update of a currently active channel. - * Therefore pointer, remainder and data should remain untouched. - * However volume and step of a particular channel can change. - */ - public boolean update; - - public int remainder; - public int end; - public int channel; - public byte[] data; - public int step; - public int stepremainder; - public int[] leftvol_lookup; - public int[] rightvol_lookup; - - public int pointer; - + + /** If this is set, the mixer considers that channel "muted" */ + public boolean stop; + + /** This signals an update of a currently active channel. + * Therefore pointer, remainder and data should remain untouched. + * However volume and step of a particular channel can change. + */ + public boolean update; + + public int remainder; + public int end; + public int channel; + public byte[] data; + public int step; + public int stepremainder; + public int[] leftvol_lookup; + public int[] rightvol_lookup; + + public int pointer; + } - + /** Mixing thread. Mixing and submission must still go on even if * the engine lags behind due to excessive CPU load. * @@ -471,10 +468,10 @@ protected class MixMessage { * */ protected class MixServer - implements Runnable { + implements Runnable { private final ArrayBlockingQueue mixmessages; - + /** * MAES: we'll have to use this for actual pointing. channels[] holds just * the data. @@ -486,335 +483,324 @@ protected class MixServer */ protected int[] channelsend; - private final byte[][] channels; + private final byte[][] channels; /** The channel step amount... */ protected final int[] channelstep; /** ... and a 0.16 bit remainder of last step. */ protected final int[] channelstepremainder; - + protected final int[][] channelrightvol_lookup; protected final int[][] channelleftvol_lookup; - - private volatile boolean update=false; - - public MixServer(int numChannels){ - // We can put only so many messages "on hold" - mixmessages=new ArrayBlockingQueue(35*numChannels); - this.p_channels=new int[numChannels]; - this.channels=new byte[numChannels][]; - this.channelstepremainder=new int[numChannels]; - this.channelsend=new int[numChannels]; - this.channelstep=new int[numChannels]; - this.channelleftvol_lookup=new int[numChannels][]; - this.channelrightvol_lookup=new int[numChannels][]; - } - - /** Adds a channel mixing message to the queue */ - - public void submitMixMessage(MixMessage m){ - try{ - this.mixmessages.add(m); - } catch (IllegalStateException e){ - // Queue full. Force clear (VERY rare). - mixmessages.clear(); - mixmessages.add(m); - } - } - - public boolean terminate=false; - - @Override - public void run() { - - // Mix current sound data. - // Data, from raw sound, for right and left. - int sample = 0; - int dl; - int dr; - - // Pointers in global mixbuffer, left, right, end. - // Maes: those were explicitly signed short pointers... - - int leftout; - int rightout; - - // Step in mixbuffer, left and right, thus two. - final int step=4; - - // Mixing channel index. - int chan; - - // Determine end, for left channel only - // (right channel is implicit). - // MAES: this implies that the buffer will only mix - // that many samples at a time, and that the size is just right. - // Thus, it must be flushed (p_mixbuffer=0) before reusing it. - final int leftend = SAMPLECOUNT * step; - - // Mix the next chunk, regardless of what the rest of the game is doing. - while (!terminate) { - - // POINTERS to Left and right channel - // which are in global mixbuffer, alternating. - - leftout = 0; - rightout = 2; - - // Wait on interrupt semaphore anyway before draining queue. - // This allows continuing mixing even if the main game loop - // is stalled. This will result in continuous sounds, - // rather than choppy interruptions. - - try { - //System.err.print("Waiting on semaphore..."); - update_mixer.acquire(); - //System.err.print("...broke free\n"); - } catch (InterruptedException e) { - // Nothing to do. Suck it down. - } - - - - // Get current number of element in queue. - // At worse, there will be none. - int messages=mixmessages.size(); - - // Drain the queue, applying changes to currently - // looping channels, if applicable. This may result in new channels, - // older ones being stopped, or current ones being altered. Changes - // will be applied with priority either way. - if (messages>0) drainAndApply(messages); - - // This may have changed in the mean. - mixed=activeChannels(); - - if (mixed) {// Avoid mixing entirely if no active channel. - - // Get audio chunk NOW - gunk= audiochunkpool.checkOut(); - // Ha ha you're ass is mine! - gunk.free = false; - mixbuffer=gunk.buffer; - - while (leftout < leftend) { - // Reset left/right value. - dl = 0; - dr = 0; - - // Love thy L2 chache - made this a loop. - // Now more channels could be set at compile time - // as well. Thus loop those channels. - - for (chan = 0; chan < numChannels; chan++) { - - // Check channel, if active. - // MAES: this means that we must point to raw data here. - if (channels[chan] != null) { - int channel_pointer = p_channels[chan]; - - // Get the raw data from the channel. - // Maes: this is supposed to be an 8-bit unsigned value. - sample = 0x00FF & channels[chan][channel_pointer]; - - // Add left and right part for this channel (sound) - // to the current data. Adjust volume accordingly. - // Q: could this be optimized by converting samples to 16-bit - // at load time, while also allowing for stereo samples? - // A: Only for the stereo part. You would still look a lookup - // for the CURRENT volume level. - - dl += channelleftvol_lookup[chan][sample]; - dr += channelrightvol_lookup[chan][sample]; - - // This should increment the index inside a channel, but is - // expressed in 16.16 fixed point arithmetic. - channelstepremainder[chan] += channelstep[chan]; - - // The actual channel pointer is increased here. - // The above trickery allows playing back different pitches. - // The shifting retains only the integer part. - channel_pointer += channelstepremainder[chan] >> 16; - - // This limits it to the "decimal" part in order to - // avoid undue accumulation. - channelstepremainder[chan] &= 0xFFFF; - - // Check whether we are done. Also to avoid overflows. - if (channel_pointer >= channelsend[chan]) { - // Reset pointer for a channel. - if (D) System.err - .printf( - "Channel %d handle %d pointer %d thus done, stopping\n", - chan, channelhandles[chan], - channel_pointer); - channels[chan] = null; - - // Communicate back to driver. - SuperDoomSoundDriver.this.channels[chan]=false; - channel_pointer = 0; - } - - // Write pointer back, so we know where a certain channel - // is the next time UpdateSounds is called. - - p_channels[chan] = channel_pointer; - } - - } // for all channels. - - // MAES: at this point, the actual values for a single sample - // (YIKES!) are in d1 and d2. We must use the leftout/rightout - // pointers to write them back into the mixbuffer. - - // Clamp to range. Left hardware channel. - // Remnant of 8-bit mixing code? That must have raped ears - // and made them bleed. - // if (dl > 127) *leftout = 127; - // else if (dl < -128) *leftout = -128; - // else *leftout = dl; - - if (dl > 0x7fff) - dl = 0x7fff; - else if (dl < -0x8000) - dl = -0x8000; - - // Write left channel - mixbuffer[leftout] = (byte) ((dl & 0xFF00) >>> 8); - mixbuffer[leftout + 1] = (byte) (dl & 0x00FF); - - // Same for right hardware channel. - if (dr > 0x7fff) - dr = 0x7fff; - else if (dr < -0x8000) - dr = -0x8000; - - // Write right channel. - mixbuffer[rightout] = (byte) ((dr & 0xFF00) >>> 8); - mixbuffer[rightout + 1] = (byte) (dr & 0x00FF); - - // Increment current pointers in mixbuffer. - leftout += step; - rightout += step; - } // End leftend/leftout while - - // for (chan = 0; chan < numChannels; chan++) { - // if (channels[chan]!=null){ - // System.err.printf("Channel %d pointer %d\n",chan,this.p_channels[chan]); - // } - // } - - } // if-mixed - - // After an entire buffer has been mixed, we can apply any updates. - // This includes silent updates. - submitSound(); - - - } // terminate loop - } - - private AudioChunk gunk; - - private final void submitSound(){ - // It's possible to stay entirely silent and give the audio - // queue a chance to get drained. without sending any data. - // Saves BW and CPU cycles. - if (mixed) { - silence=0; - - - // System.err.printf("Submitted sound chunk %d to buffer %d \n",chunk,mixstate); - - // Copy the currently mixed chunk into its position inside the - // master buffer. - // System.arraycopy(mixbuffer, 0, gunk.buffer, 0, MIXBUFFERSIZE); - - SOUNDSRV.addChunk(gunk); - - // System.err.println(chunk++); - - chunk++; - // System.err.println(chunk); - - if (consume.tryAcquire()) - produce.release(); - - } else { - silence++; - // MAES: attempt to fix lingering noise error - if (silence >ISoundDriver.BUFFER_CHUNKS){ - line.flush(); - silence=0; - } - } - } - - /** Drains message queue and applies to individual channels. - * More recently enqueued messages will trump older ones. This method - * only changes the STATUS of channels, and actual message submissions - * can occur at most every sound frame. - * - * @param messages - */ - - private void drainAndApply(int messages ) { - MixMessage m; - for (int i=0;i(35 * numChannels); + this.p_channels = new int[numChannels]; + this.channels = new byte[numChannels][]; + this.channelstepremainder = new int[numChannels]; + this.channelsend = new int[numChannels]; + this.channelstep = new int[numChannels]; + this.channelleftvol_lookup = new int[numChannels][]; + this.channelrightvol_lookup = new int[numChannels][]; + } + + /** Adds a channel mixing message to the queue */ + public void submitMixMessage(MixMessage m) { + try { + this.mixmessages.add(m); + } catch (IllegalStateException e) { + // Queue full. Force clear (VERY rare). + mixmessages.clear(); + mixmessages.add(m); + } + } + + public boolean terminate = false; + + @Override + public void run() { + + // Mix current sound data. + // Data, from raw sound, for right and left. + int sample = 0; + int dl; + int dr; + + // Pointers in global mixbuffer, left, right, end. + // Maes: those were explicitly signed short pointers... + int leftout; + int rightout; + + // Step in mixbuffer, left and right, thus two. + final int step = 4; + + // Mixing channel index. + int chan; + + // Determine end, for left channel only + // (right channel is implicit). + // MAES: this implies that the buffer will only mix + // that many samples at a time, and that the size is just right. + // Thus, it must be flushed (p_mixbuffer=0) before reusing it. + final int leftend = SAMPLECOUNT * step; + + // Mix the next chunk, regardless of what the rest of the game is doing. + while (!terminate) { + + // POINTERS to Left and right channel + // which are in global mixbuffer, alternating. + leftout = 0; + rightout = 2; + + // Wait on interrupt semaphore anyway before draining queue. + // This allows continuing mixing even if the main game loop + // is stalled. This will result in continuous sounds, + // rather than choppy interruptions. + try { + //System.err.print("Waiting on semaphore..."); + update_mixer.acquire(); + //System.err.print("...broke free\n"); + } catch (InterruptedException e) { + // Nothing to do. Suck it down. + } + + // Get current number of element in queue. + // At worse, there will be none. + int messages = mixmessages.size(); + + // Drain the queue, applying changes to currently + // looping channels, if applicable. This may result in new channels, + // older ones being stopped, or current ones being altered. Changes + // will be applied with priority either way. + if (messages > 0) { + drainAndApply(messages); + } + + // This may have changed in the mean. + mixed = activeChannels(); + + if (mixed) {// Avoid mixing entirely if no active channel. + + // Get audio chunk NOW + gunk = audiochunkpool.checkOut(); + // Ha ha you're ass is mine! + gunk.free = false; + mixbuffer = gunk.buffer; + + while (leftout < leftend) { + // Reset left/right value. + dl = 0; + dr = 0; + + // Love thy L2 chache - made this a loop. + // Now more channels could be set at compile time + // as well. Thus loop those channels. + for (chan = 0; chan < numChannels; chan++) { + + // Check channel, if active. + // MAES: this means that we must point to raw data here. + if (channels[chan] != null) { + int channel_pointer = p_channels[chan]; + + // Get the raw data from the channel. + // Maes: this is supposed to be an 8-bit unsigned value. + sample = 0x00FF & channels[chan][channel_pointer]; + + // Add left and right part for this channel (sound) + // to the current data. Adjust volume accordingly. + // Q: could this be optimized by converting samples to 16-bit + // at load time, while also allowing for stereo samples? + // A: Only for the stereo part. You would still look a lookup + // for the CURRENT volume level. + dl += channelleftvol_lookup[chan][sample]; + dr += channelrightvol_lookup[chan][sample]; + + // This should increment the index inside a channel, but is + // expressed in 16.16 fixed point arithmetic. + channelstepremainder[chan] += channelstep[chan]; + + // The actual channel pointer is increased here. + // The above trickery allows playing back different pitches. + // The shifting retains only the integer part. + channel_pointer += channelstepremainder[chan] >> 16; + + // This limits it to the "decimal" part in order to + // avoid undue accumulation. + channelstepremainder[chan] &= 0xFFFF; + + // Check whether we are done. Also to avoid overflows. + if (channel_pointer >= channelsend[chan]) { + // Reset pointer for a channel. + if (D) { + LOGGER.log(Level.FINE, String.format( + "Channel %d handle %d pointer %d thus done, stopping", + chan, channelhandles[chan], + channel_pointer)); + } + channels[chan] = null; + + // Communicate back to driver. + SuperDoomSoundDriver.this.channels[chan] = false; + channel_pointer = 0; + } + + // Write pointer back, so we know where a certain channel + // is the next time UpdateSounds is called. + p_channels[chan] = channel_pointer; + } + + } // for all channels. + + // MAES: at this point, the actual values for a single sample + // (YIKES!) are in d1 and d2. We must use the leftout/rightout + // pointers to write them back into the mixbuffer. + // Clamp to range. Left hardware channel. + // Remnant of 8-bit mixing code? That must have raped ears + // and made them bleed. + // if (dl > 127) *leftout = 127; + // else if (dl < -128) *leftout = -128; + // else *leftout = dl; + if (dl > 0x7fff) { + dl = 0x7fff; + } else if (dl < -0x8000) { + dl = -0x8000; + } + + // Write left channel + mixbuffer[leftout] = (byte) ((dl & 0xFF00) >>> 8); + mixbuffer[leftout + 1] = (byte) (dl & 0x00FF); + + // Same for right hardware channel. + if (dr > 0x7fff) { + dr = 0x7fff; + } else if (dr < -0x8000) { + dr = -0x8000; + } + + // Write right channel. + mixbuffer[rightout] = (byte) ((dr & 0xFF00) >>> 8); + mixbuffer[rightout + 1] = (byte) (dr & 0x00FF); + + // Increment current pointers in mixbuffer. + leftout += step; + rightout += step; + } // End leftend/leftout while + + // for (chan = 0; chan < numChannels; chan++) { + // if (channels[chan]!=null){ + // System.err.printf("Channel %d pointer %d\n",chan,this.p_channels[chan]); + // } + // } + } // if-mixed + + // After an entire buffer has been mixed, we can apply any updates. + // This includes silent updates. + submitSound(); + + } // terminate loop + } + + private AudioChunk gunk; + + private final void submitSound() { + // It's possible to stay entirely silent and give the audio + // queue a chance to get drained. without sending any data. + // Saves BW and CPU cycles. + if (mixed) { + silence = 0; + + // System.err.printf("Submitted sound chunk %d to buffer %d \n",chunk,mixstate); + // Copy the currently mixed chunk into its position inside the + // master buffer. + // System.arraycopy(mixbuffer, 0, gunk.buffer, 0, MIXBUFFERSIZE); + SOUNDSRV.addChunk(gunk); + + // System.err.println(chunk++); + chunk++; + // System.err.println(chunk); + + if (consume.tryAcquire()) { + produce.release(); + } + + } else { + silence++; + // MAES: attempt to fix lingering noise error + if (silence > ISoundDriver.BUFFER_CHUNKS) { + line.flush(); + silence = 0; + } + } + } + + /** Drains message queue and applies to individual channels. + * More recently enqueued messages will trump older ones. This method + * only changes the STATUS of channels, and actual message submissions + * can occur at most every sound frame. + * + * @param messages + */ + private void drainAndApply(int messages) { + MixMessage m; + for (int i = 0; i < messages; i++) { + // There should be no problems, in theory. + m = this.mixmessages.remove(); + if (m.stop) { + stopChannel(m.channel); + } else if (m.update) { + updateChannel(m); + } else { + insertChannel(m); + } + } + } + + private final void stopChannel(int channel) { + //System.err.printf("Stopping channel %d\n",channel); + this.channels[channel] = null; + this.p_channels[channel] = 0; + } + + private final void updateChannel(MixMessage m) { + //System.err.printf("Updating channel %d\n",m.channel); + this.channelleftvol_lookup[m.channel] = m.leftvol_lookup; + this.channelrightvol_lookup[m.channel] = m.rightvol_lookup; + this.channelstep[m.channel] = m.step; + this.channelsend[m.channel] = m.end; + } + + private final void insertChannel(MixMessage m) { + int ch = m.channel; + //System.err.printf("Inserting channel %d\n",ch); + this.channels[ch] = m.data; + this.p_channels[ch] = m.pointer; + this.channelsend[ch] = m.end; + this.channelstepremainder[ch] = m.remainder; + this.channelleftvol_lookup[ch] = m.leftvol_lookup; + this.channelrightvol_lookup[ch] = m.rightvol_lookup; + this.channelstep[ch] = m.step; + } + + private final boolean activeChannels() { + for (int chan = 0; chan < numChannels; chan++) { + if (channels[chan] != null) // SOME mixing has taken place. + { + return true; + } + } + + return false; + } + + public final boolean channelIsPlaying(int num) { + return (channels[num] != null); + } + + } + @Override public boolean SoundIsPlaying(int handle) { @@ -832,8 +818,9 @@ public boolean SoundIsPlaying(int handle) { protected int getChannelFromHandle(int handle) { // Which channel has it? for (int i = 0; i < numChannels; i++) { - if (channelhandles[i] == handle) + if (channelhandles[i] == handle) { return i; + } } return BUSY_HANDLE; @@ -844,17 +831,16 @@ public void StopSound(int handle) { // Which channel has it? int hnd = getChannelFromHandle(handle); if (hnd >= 0) { - + channels[hnd] = false; - - + this.channelhandles[hnd] = IDLE_HANDLE; - - MixMessage m=new MixMessage(); - m.channel=hnd; - m.stop=true; - // We can only "ask" the mixer to stop at the next - //chunk. + + MixMessage m = new MixMessage(); + m.channel = hnd; + m.stop = true; + // We can only "ask" the mixer to stop at the next + //chunk. MIXSRV.submitMixMessage(m); } } @@ -863,10 +849,10 @@ public void StopSound(int handle) { public void SubmitSound() { // Also a dummy. The mixing thread is in a better position to - // judge when sound should be submitted. + // judge when sound should be submitted. } - - private int silence=0; + + private int silence = 0; @Override public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { @@ -880,32 +866,31 @@ public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { int rightvol = vol - ((vol * sep * sep) >> 16); // Sanity check, clamp volume. - - if (rightvol < 0 || rightvol > 127) + if (rightvol < 0 || rightvol > 127) { DM.doomSystem.Error("rightvol out of bounds"); + } - if (leftvol < 0 || leftvol > 127) + if (leftvol < 0 || leftvol > 127) { DM.doomSystem.Error("leftvol out of bounds"); + } + + MixMessage m = new MixMessage(); - MixMessage m=new MixMessage(); - // We are updating a currently active channel - m.update=true; - m.channel=chan; - + m.update = true; + m.channel = chan; + // Get the proper lookup table piece // for this volume level??? - m.leftvol_lookup = vol_lookup[leftvol]; m.rightvol_lookup = vol_lookup[rightvol]; // Well, if you can get pitch to change too... m.step = steptable[pitch]; - + // Oddly enough, we could be picking a different channel here? :-S m.end = lengths[channelids[chan]]; - - + MIXSRV.submitMixMessage(m); } @@ -914,28 +899,27 @@ public void UpdateSoundParams(int handle, int vol, int sep, int pitch) { public String channelStatus() { sb.setLength(0); for (int i = 0; i < numChannels; i++) { - if (MIXSRV.channelIsPlaying(i)) + if (MIXSRV.channelIsPlaying(i)) { sb.append(i); - else + } else { sb.append('-'); + } } return sb.toString(); } - // Schedule this to release the sound thread at regular intervals // so that it doesn't outrun the audioline's buffer and game updates. - protected class SoundTimer extends TimerTask { + public void run() { - update_mixer.release(); + update_mixer.release(); } - } - - + } + protected final AudioChunk SILENT_CHUNK = new AudioChunk(); protected final AudioChunkPool audiochunkpool = new AudioChunkPool(); -} \ No newline at end of file +} diff --git a/src/s/VolumeScalingReceiver.java b/src/s/VolumeScalingReceiver.java index 594e3911..48a42754 100644 --- a/src/s/VolumeScalingReceiver.java +++ b/src/s/VolumeScalingReceiver.java @@ -7,7 +7,8 @@ import java.util.Iterator; import java.util.List; import java.util.Locale; - +import java.util.logging.Level; +import java.util.logging.Logger; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiDevice; import javax.sound.midi.MidiMessage; @@ -17,6 +18,7 @@ import javax.sound.midi.Sequencer; import javax.sound.midi.ShortMessage; import javax.sound.midi.Synthesizer; +import mochadoom.Loggers; /** A {@link Receiver} that scales channel volumes. * @@ -29,6 +31,8 @@ */ public class VolumeScalingReceiver implements Receiver { + private static final Logger LOGGER = Loggers.getLogger(VolumeScalingReceiver.class.getName()); + /** Guess which is the "best" available synthesizer & create a * VolumeScalingReceiver that forwards to it. * @@ -38,11 +42,10 @@ public class VolumeScalingReceiver implements Receiver { */ public static VolumeScalingReceiver getInstance() { try { - List dInfos = - new ArrayList(Arrays.asList(MidiSystem.getMidiDeviceInfo())); + List dInfos + = new ArrayList<>(Arrays.asList(MidiSystem.getMidiDeviceInfo())); for (Iterator it = dInfos.iterator(); - it.hasNext(); - ) { + it.hasNext();) { MidiDevice.Info dInfo = it.next(); MidiDevice dev = MidiSystem.getMidiDevice(dInfo); if (dev.getMaxReceivers() == 0) { @@ -50,7 +53,9 @@ public static VolumeScalingReceiver getInstance() { it.remove(); } } - if (dInfos.isEmpty()) return null; + if (dInfos.isEmpty()) { + return null; + } Collections.sort(dInfos, new MidiDeviceComparator()); MidiDevice.Info dInfo = dInfos.get(0); MidiDevice dev = MidiSystem.getMidiDevice((MidiDevice.Info) dInfo); @@ -76,7 +81,7 @@ public void close() { /** Set the scaling factor to be applied to all channel volumes */ public synchronized void setGlobalVolume(float globalVolume) { this.globalVolume = globalVolume; - for (int chan = 0; chan < 16; ++ chan) { + for (int chan = 0; chan < 16; ++chan) { int volScaled = (int) Math.round(channelVolume[chan] * globalVolume); sendVolumeChange(chan, volScaled, -1); } @@ -84,6 +89,7 @@ public synchronized void setGlobalVolume(float globalVolume) { /** A collection of kludges to pick a synthesizer until cvars are implemented */ static class MidiDeviceComparator implements Comparator { + @Override public int compare(MidiDevice.Info o1, MidiDevice.Info o2) { float score1 = score(o1), score2 = score(o2); @@ -95,6 +101,7 @@ public int compare(MidiDevice.Info o1, MidiDevice.Info o2) { return 0; } } + /** Guess how suitable a MidiDevice is for music output. */ private float score(MidiDevice.Info info) { String lcName = info.getName().toLowerCase(Locale.ENGLISH); @@ -170,7 +177,7 @@ private void sendVolumeChange(int chan, int newVolScaled, long timeStamp) { message.setMessage(0xb0 | (chan & 15), 7, newVolScaled); synthReceiver.send(message, timeStamp); } catch (InvalidMidiDataException ex) { - System.err.println(ex); + LOGGER.log(Level.SEVERE, "sendVolumeChange failure", ex); } } @@ -182,8 +189,8 @@ private void sendVolumeChange(int chan, int newVolScaled, long timeStamp) { private int getVolumeChangeChannel(MidiMessage message) { if (message.getLength() >= 3) { byte[] mBytes = message.getMessage(); - if ((byte) 0xb0 <= mBytes[0] && mBytes[0] < (byte) 0xc0 && - mBytes[1] == 7) { + if ((byte) 0xb0 <= mBytes[0] && mBytes[0] < (byte) 0xc0 + && mBytes[1] == 7) { return mBytes[0] & 15; } } diff --git a/src/s/channel_t.java b/src/s/channel_t.java index d33df6e9..ae0789e1 100644 --- a/src/s/channel_t.java +++ b/src/s/channel_t.java @@ -1,32 +1,30 @@ package s; +import data.sfxinfo_t; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.SourceDataLine; - import p.mobj_t; -import data.sfxinfo_t; -public class channel_t -{ - - public channel_t(){ - sfxinfo=new sfxinfo_t(); - } - - /** Currently playing sound. If null, then it's free */ - DoomSound currentSound = null; - - sfxinfo_t sfxinfo; +public class channel_t { + + public channel_t() { + sfxinfo = new sfxinfo_t(); + } + + /** Currently playing sound. If null, then it's free */ + DoomSound currentSound = null; + + sfxinfo_t sfxinfo; // origin of sound (usually a mobj_t). - mobj_t origin; + mobj_t origin; // handle of the sound being played - int handle; - + int handle; + AudioFormat format; - - public int sfxVolume; - - SourceDataLine auline = null; + + public int sfxVolume; + + SourceDataLine auline = null; } diff --git a/src/savegame/IDoomSaveGame.java b/src/savegame/IDoomSaveGame.java index 4792b71b..475a45b5 100644 --- a/src/savegame/IDoomSaveGame.java +++ b/src/savegame/IDoomSaveGame.java @@ -5,9 +5,14 @@ import p.ThinkerList; public interface IDoomSaveGame { + void setThinkerList(ThinkerList li); + boolean doLoad(DataInputStream f); + IDoomSaveGameHeader getHeader(); + void setHeader(IDoomSaveGameHeader header); + boolean doSave(DataOutputStream f); } diff --git a/src/savegame/IDoomSaveGameHeader.java b/src/savegame/IDoomSaveGameHeader.java index 960d1c2d..9e5550d8 100644 --- a/src/savegame/IDoomSaveGameHeader.java +++ b/src/savegame/IDoomSaveGameHeader.java @@ -2,7 +2,6 @@ import defines.skill_t; - /** A Save Game Header should be able to be loaded quickly and return * some basic info about it (name, version, game time, etc.) in an unified * manner, no matter what actual format you use for saving. @@ -10,7 +9,6 @@ * @author admin * */ - public interface IDoomSaveGameHeader { String getName(); @@ -20,13 +18,13 @@ public interface IDoomSaveGameHeader { skill_t getGameskill(); void setGameskill(skill_t gameskill); - + String getVersion(); void setVersion(String vcheck); int getGameepisode(); - + void setGameepisode(int gameepisode); boolean isProperend(); diff --git a/src/savegame/ILoadSaveGame.java b/src/savegame/ILoadSaveGame.java index 9601405b..f5dea286 100644 --- a/src/savegame/ILoadSaveGame.java +++ b/src/savegame/ILoadSaveGame.java @@ -3,7 +3,10 @@ import p.ThinkerList; public interface ILoadSaveGame { + void setThinkerList(ThinkerList li); + void doSave(ThinkerList li); + void doLoad(ThinkerList li); } diff --git a/src/savegame/VanillaDSG.java b/src/savegame/VanillaDSG.java index 93753fee..2b2193b5 100644 --- a/src/savegame/VanillaDSG.java +++ b/src/savegame/VanillaDSG.java @@ -1,6 +1,7 @@ package savegame; -import static data.Limits.*; +import static data.Limits.MAXCEILINGS; +import static data.Limits.MAXPLAYERS; import data.info; import doom.DoomMain; import doom.SourceCode.P_SaveG; @@ -23,14 +24,28 @@ import java.util.HashMap; import java.util.List; import java.util.logging.Level; +import java.util.logging.Logger; import m.Settings; import mochadoom.Engine; import mochadoom.Loggers; -import p.*; import p.Actions.ActionsLights.glow_t; import p.Actions.ActionsLights.lightflash_t; -import static p.ActiveStates.*; - +import static p.ActiveStates.NOP; +import static p.ActiveStates.P_MobjThinker; +import static p.ActiveStates.T_Glow; +import static p.ActiveStates.T_LightFlash; +import static p.ActiveStates.T_MoveCeiling; +import static p.ActiveStates.T_MoveFloor; +import static p.ActiveStates.T_PlatRaise; +import static p.ActiveStates.T_StrobeFlash; +import static p.ActiveStates.T_VerticalDoor; +import p.ThinkerList; +import p.ceiling_t; +import p.floormove_t; +import p.mobj_t; +import p.plat_t; +import p.strobe_t; +import p.vldoor_t; import rr.line_t; import rr.sector_t; import rr.side_t; @@ -38,6 +53,8 @@ public class VanillaDSG implements IDoomSaveGame { + private static final Logger LOGGER = Loggers.getLogger(VanillaDSG.class.getName()); + VanillaDSGHeader header; final DoomMain DOOM; @@ -71,7 +88,7 @@ public boolean doLoad(DataInputStream f) { try { this.f = f; maxsize = f.available(); - System.out.println("Max size " + maxsize); + LOGGER.log(Level.FINE, String.format("Max size %d", maxsize)); this.header = new VanillaDSGHeader(); header.read(f); UnArchivePlayers(); @@ -81,8 +98,8 @@ public boolean doLoad(DataInputStream f) { byte terminator = f.readByte(); return terminator == 0x1D; } catch (IOException e) { - Loggers.getLogger(VanillaDSG.class.getName()).log(Level.WARNING, e, () -> - String.format("Error while loading savegame! Cause: %s", e.getMessage())); + LOGGER.log(Level.WARNING, e, () + -> String.format("Error while loading savegame! Cause: %s", e.getMessage())); return false; // Needed to shut up compiler. } @@ -117,7 +134,7 @@ protected void UnArchivePlayers() throws IOException { if (C2JUtils.eval(DOOM.players[i].psprites[j].state)) { // MAES HACK to accomoadate state_t type punning a-posteriori DOOM.players[i].psprites[j].state - = info.states[DOOM.players[i].psprites[j].readstate]; + = info.states[DOOM.players[i].psprites[j].readstate]; } } } @@ -304,7 +321,7 @@ protected void adaptSectors() { } default: - break; + break; } } @@ -361,7 +378,7 @@ protected void deAdaptSectors() { } default: - break; + break; } } @@ -401,7 +418,7 @@ protected void ArchiveThinkers() throws IOException { //mobj->player = (player_t *)((mobj->player-players) + 1); } - // I_Error ("P_ArchiveThinkers: Unknown thinker function"); + // I_Error ("P_ArchiveThinkers: Unknown thinker function"); } // add a terminating marker @@ -428,9 +445,9 @@ protected void UnArchiveThinkers() throws IOException { if (currentthinker.thinkerFunction == P_MobjThinker) { DOOM.actions.RemoveMobj((mobj_t) currentthinker); }// else { - //currentthinker.next.prev=currentthinker.prev; - //currentthinker.prev.next=currentthinker.next; - //currentthinker = null; + //currentthinker.next.prev=currentthinker.prev; + //currentthinker.prev.next=currentthinker.next; + //currentthinker = null; //} currentthinker = next; @@ -474,7 +491,7 @@ protected void UnArchiveThinkers() throws IOException { DOOM.doomSystem.Error("Unknown tclass %d in savegame", tclass); } } - + if (Engine.getConfig().equals(Settings.reconstruct_savegame_pointers, Boolean.TRUE)) { reconstructPointers(); rewirePointers(); @@ -503,8 +520,8 @@ protected void reconstructPointers() { } if (player == 0) { - Loggers.getLogger(VanillaDSG.class.getName()).log(Level.WARNING, - "Player not found, cannot reconstruct pointers!"); + LOGGER.log(Level.WARNING, + "Player not found, cannot reconstruct pointers!"); return; } @@ -852,8 +869,8 @@ public boolean doSave(DataOutputStream f) { // TODO: the rest... f.write(0x1D); } catch (IOException e) { - Loggers.getLogger(VanillaDSG.class.getName()).log(Level.WARNING, e, () -> - String.format("Error while saving savegame! Cause: %s", e.getMessage())); + LOGGER.log(Level.WARNING, e, () + -> String.format("Error while saving savegame! Cause: %s", e.getMessage())); return false; // Needed to shut up compiler. } return true; diff --git a/src/savegame/VanillaDSGHeader.java b/src/savegame/VanillaDSGHeader.java index 0ef310f4..12f27508 100644 --- a/src/savegame/VanillaDSGHeader.java +++ b/src/savegame/VanillaDSGHeader.java @@ -1,21 +1,20 @@ package savegame; + +import static data.Defines.VERSION; +import static data.Limits.MAXPLAYERS; +import static data.Limits.SAVESTRINGSIZE; +import static data.Limits.VERSIONSIZE; +import defines.skill_t; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; - import utils.C2JUtils; import w.CacheableDoomObject; import w.DoomBuffer; import w.DoomIO; import w.IReadableDoomObject; import w.IWritableDoomObject; -import defines.skill_t; - -import static data.Defines.VERSION; -import static data.Limits.MAXPLAYERS; -import static data.Limits.SAVESTRINGSIZE; -import static data.Limits.VERSIONSIZE; /** The header of a vanilla savegame. * @@ -34,179 +33,191 @@ * @author admin * */ +public class VanillaDSGHeader implements IDoomSaveGameHeader, IReadableDoomObject, IWritableDoomObject, CacheableDoomObject { - -public class VanillaDSGHeader implements IDoomSaveGameHeader,IReadableDoomObject, IWritableDoomObject, CacheableDoomObject{ - -public String name; // max size SAVEGAMENAME -public String vcheck; + public String name; // max size SAVEGAMENAME + public String vcheck; // These are for DS -public skill_t gameskill; -public int gameepisode; -public int gamemap; -public boolean[] playeringame; + public skill_t gameskill; + public int gameepisode; + public int gamemap; + public boolean[] playeringame; /** what bullshit, stored as 24-bit integer?! */ - public int leveltime; + public int leveltime; // These help checking shit. -public boolean wrongversion; - public boolean properend; - - public VanillaDSGHeader(){ - this.playeringame=new boolean[MAXPLAYERS]; - } - - - @Override - public void unpack(ByteBuffer buf) - throws IOException { - name=DoomBuffer.getNullTerminatedString(buf, SAVESTRINGSIZE); - vcheck=DoomBuffer.getNullTerminatedString(buf, VERSIONSIZE); - String vcheckb= ("version "+VERSION); - // no more unpacking, and report it. - if (wrongversion = !(vcheckb.equalsIgnoreCase(vcheck))) return; - gameskill = skill_t.values()[buf.get()]; - gameepisode = buf.get(); - gamemap = buf.get(); - - for (int i=0 ; i>16)); - byte b = (byte) (0x00FF&(leveltime>>8)); - byte c = (byte) (0x00FF&(leveltime)); - // Quite anomalous, leveltime is stored as a BIG ENDIAN, 24-bit unsigned integer :-S - f.writeByte(a); - f.writeByte(b); - f.writeByte(c); - - // The end. This is actually just the header, so we don't "end" here just yet. - // f.writeByte(0x1d); - - } - - @Override - public void read(DataInputStream f) - throws IOException { - name= DoomIO.readNullTerminatedString(f,SAVESTRINGSIZE); - vcheck=DoomIO.readNullTerminatedString(f,VERSIONSIZE); - gameskill=skill_t.values()[f.readUnsignedByte()]; - gameepisode=f.readByte(); - gamemap=f.readByte(); - for (int i=0 ; i> 16)); + byte b = (byte) (0x00FF & (leveltime >> 8)); + byte c = (byte) (0x00FF & (leveltime)); + // Quite anomalous, leveltime is stored as a BIG ENDIAN, 24-bit unsigned integer :-S + f.writeByte(a); + f.writeByte(b); + f.writeByte(c); + + // The end. This is actually just the header, so we don't "end" here just yet. + // f.writeByte(0x1d); + } + + @Override + public void read(DataInputStream f) + throws IOException { + name = DoomIO.readNullTerminatedString(f, SAVESTRINGSIZE); + vcheck = DoomIO.readNullTerminatedString(f, VERSIONSIZE); + gameskill = skill_t.values()[f.readUnsignedByte()]; + gameepisode = f.readByte(); + gamemap = f.readByte(); + for (int i = 0; i < MAXPLAYERS; i++) { + playeringame[i] = f.readBoolean(); + } + + // get the times + int a = f.readUnsignedByte(); + int b = f.readUnsignedByte(); + int c = f.readUnsignedByte(); + // Quite anomalous, leveltime is stored as a BIG ENDIAN, 24-bit unsigned integer :-S + leveltime = (a << 16) | (b << 8) | c; + + } + + ////////////////////////// NASTY GETTERS ////////////////////////////// @Override public String getName() { return name; } - + @Override public void setName(String name) { this.name = name; } + @Override public String getVersion() { return vcheck; } + @Override public void setVersion(String vcheck) { this.vcheck = vcheck; } + @Override public skill_t getGameskill() { return gameskill; } + @Override public void setGameskill(skill_t gameskill) { this.gameskill = gameskill; } + @Override public int getGameepisode() { return gameepisode; } + @Override public void setGameepisode(int gameepisode) { this.gameepisode = gameepisode; } + @Override public int getGamemap() { return gamemap; } + @Override public void setGamemap(int gamemap) { this.gamemap = gamemap; } + @Override public boolean[] getPlayeringame() { return playeringame; } + @Override public void setPlayeringame(boolean[] playeringame) { this.playeringame = playeringame; } + @Override public int getLeveltime() { return leveltime; } + @Override public void setLeveltime(int leveltime) { this.leveltime = leveltime; } + @Override public boolean isWrongversion() { return wrongversion; } + @Override public void setWrongversion(boolean wrongversion) { this.wrongversion = wrongversion; } + @Override public boolean isProperend() { return properend; diff --git a/src/st/AbstractStatusBar.java b/src/st/AbstractStatusBar.java index 0bc830ca..a8252368 100644 --- a/src/st/AbstractStatusBar.java +++ b/src/st/AbstractStatusBar.java @@ -3,6 +3,7 @@ import doom.DoomMain; public abstract class AbstractStatusBar implements IDoomStatusBar { + protected final DoomMain DOOM; public AbstractStatusBar(DoomMain DOOM) { diff --git a/src/st/IDoomStatusBar.java b/src/st/IDoomStatusBar.java index 784ed7d2..0d8e7c6d 100644 --- a/src/st/IDoomStatusBar.java +++ b/src/st/IDoomStatusBar.java @@ -31,7 +31,7 @@ public interface IDoomStatusBar { // // STATUS BAR // - + public void NotifyAMEnter(); public void NotifyAMExit(); @@ -58,12 +58,11 @@ public interface IDoomStatusBar { * HOMS). */ public int getHeight(); - + /** Forces a full refresh for reasons not handled otherwise, e.g. after full-page * draws of help screens, which normally don't trigger a complete redraw even if * they should, really. */ - void forceRefresh(); -} \ No newline at end of file +} diff --git a/src/st/StatusBar.java b/src/st/StatusBar.java index e5be6cb6..8c7f0c7b 100644 --- a/src/st/StatusBar.java +++ b/src/st/StatusBar.java @@ -23,23 +23,42 @@ // Does palette indicators as well (red pain/berserk, bright pickup) // // ----------------------------------------------------------------------------- - -import static data.Defines.*; +import static data.Defines.NUMAMMO; +import static data.Defines.NUMCARDS; +import static data.Defines.NUMWEAPONS; +import static data.Defines.PU_STATIC; +import static data.Defines.TICRATE; +import static data.Defines.pw_invulnerability; +import static data.Defines.pw_ironfeet; +import static data.Defines.pw_strength; import static data.Limits.MAXPLAYERS; -import static data.Tables.*; +import static data.Tables.ANG180; +import static data.Tables.ANG45; import data.sounds.musicenum_t; -import defines.*; +import defines.ammotype_t; import doom.DoomMain; import doom.SourceCode; import doom.SourceCode.CauseOfDesyncProbability; import doom.SourceCode.ST_Stuff; import static doom.SourceCode.ST_Stuff.ST_Responder; -import static doom.englsh.*; +import static doom.englsh.STSTR_BEHOLD; +import static doom.englsh.STSTR_BEHOLDX; +import static doom.englsh.STSTR_CHOPPERS; +import static doom.englsh.STSTR_CLEV; +import static doom.englsh.STSTR_DQDOFF; +import static doom.englsh.STSTR_DQDON; +import static doom.englsh.STSTR_FAADDED; +import static doom.englsh.STSTR_KFAADDED; +import static doom.englsh.STSTR_MUS; +import static doom.englsh.STSTR_NCOFF; +import static doom.englsh.STSTR_NCON; +import static doom.englsh.STSTR_NOMUS; import doom.event_t; import doom.evtype_t; -import static doom.items.*; +import static doom.items.weaponinfo; import doom.player_t; -import static doom.player_t.*; +import static doom.player_t.CF_GODMODE; +import static doom.player_t.CF_NOCLIP; import doom.weapontype_t; import g.Signals; import java.awt.Rectangle; @@ -47,22 +66,25 @@ import m.cheatseq_t; import p.mobj_t; import rr.patch_t; -import static v.DoomGraphicSystem.*; -import static v.renderers.DoomScreen.*; +import static v.DoomGraphicSystem.V_NOSCALESTART; +import static v.DoomGraphicSystem.V_PREDIVIDE; +import static v.DoomGraphicSystem.V_SAFESCALE; +import static v.DoomGraphicSystem.V_SCALEOFFSET; +import static v.DoomGraphicSystem.V_TRANSLUCENTPATCH; +import static v.renderers.DoomScreen.BG; +import static v.renderers.DoomScreen.FG; +import static v.renderers.DoomScreen.SB; public class StatusBar extends AbstractStatusBar { - public static final String rcsid = - "$Id: StatusBar.java,v 1.47 2011/11/01 23:46:37 velktron Exp $"; - - + public static final String rcsid + = "$Id: StatusBar.java,v 1.47 2011/11/01 23:46:37 velktron Exp $"; + // Size of statusbar. // Now sensitive for scaling. - // // STATUS BAR DATA // - // Palette indices. // For damage/bonus red-/gold-shifts private static int STARTREDPALS = 1; @@ -93,7 +115,6 @@ public class StatusBar extends AbstractStatusBar { // Should be set to patch width // for tall numbers later on // TODO: private static int ST_TALLNUMWIDTH = (tallnum[0].width); - // Number of status faces. private static int ST_NUMPAINFACES = 5; @@ -103,13 +124,13 @@ public class StatusBar extends AbstractStatusBar { private static int ST_NUMSPECIALFACES = 3; - private static int ST_FACESTRIDE = - (ST_NUMSTRAIGHTFACES + ST_NUMTURNFACES + ST_NUMSPECIALFACES); + private static int ST_FACESTRIDE + = (ST_NUMSTRAIGHTFACES + ST_NUMTURNFACES + ST_NUMSPECIALFACES); private static int ST_NUMEXTRAFACES = 2; - private static int ST_NUMFACES = - (ST_FACESTRIDE * ST_NUMPAINFACES + ST_NUMEXTRAFACES); + private static int ST_NUMFACES + = (ST_FACESTRIDE * ST_NUMPAINFACES + ST_NUMEXTRAFACES); private static int ST_TURNOFFSET = (ST_NUMSTRAIGHTFACES); @@ -146,14 +167,13 @@ public class StatusBar extends AbstractStatusBar { // Problem is, is the stuff rendered // into a buffer, // or into the frame buffer? - // AMMO number pos. private int ST_AMMOWIDTH; private int ST_AMMOX; private int ST_AMMOY; // HEALTH number pos. - private int ST_HEALTHWIDTH=3; + private int ST_HEALTHWIDTH = 3; private int ST_HEALTHX; private int ST_HEALTHY; @@ -242,7 +262,7 @@ public class StatusBar extends AbstractStatusBar { private int ST_MAXAMMO3X; private int ST_MAXAMMO3Y; - + // pistol private int ST_WEAPON0X; private int ST_WEAPON0Y; @@ -301,10 +321,8 @@ public class StatusBar extends AbstractStatusBar { // TODO private static int ST_MAPWIDTH = // (mapnames[(gameepisode-1)*9+(gamemap-1)].length)); - // TODO private static int ST_MAPTITLEX = (SCREENWIDTH - ST_MAPWIDTH * // ST_CHATFONTWIDTH); - private static int ST_MAPTITLEY = 0; private static int ST_MAPHEIGHT = 1; @@ -314,10 +332,10 @@ public class StatusBar extends AbstractStatusBar { // ST_Start() has just been called, OR we want to force an redraw anyway. private boolean st_firsttime; - + @Override - public void forceRefresh(){ - st_firsttime=true; + public void forceRefresh() { + st_firsttime = true; } // used to execute ST_Init() only once @@ -342,7 +360,7 @@ public void forceRefresh(){ * (and others like it) are necessary in order to have something * close to a pointer. */ - private boolean[] st_statusbaron={false}; + private boolean[] st_statusbaron = {false}; // whether status bar chat is active private boolean st_chat; @@ -351,16 +369,16 @@ public void forceRefresh(){ private boolean st_oldchat; // whether chat window has the cursor on - private boolean[] st_cursoron={false}; + private boolean[] st_cursoron = {false}; /** !deathmatch */ - private boolean[] st_notdeathmatch={true}; + private boolean[] st_notdeathmatch = {true}; /** !deathmatch && st_statusbaron */ - private boolean[] st_armson={true}; + private boolean[] st_armson = {true}; /** !deathmatch */ - private boolean[] st_fragson={false}; + private boolean[] st_fragson = {false}; // main bar left private patch_t sbar; @@ -388,9 +406,8 @@ public void forceRefresh(){ // weapon ownership patches private patch_t[][] arms = new patch_t[6][2]; - - // // WIDGETS ///// + // // WIDGETS ///// // ready-weapon widget private st_number_t w_ready; @@ -422,9 +439,8 @@ public void forceRefresh(){ private st_number_t[] w_maxammo = new st_number_t[4]; // / END WIDGETS //// - // number of frags so far in deathmatch - private int[] st_fragscount={0}; + private int[] st_fragscount = {0}; // used to use appopriately pained face private int st_oldhealth = -1; @@ -443,55 +459,55 @@ public void forceRefresh(){ // a random number per tick private int st_randomnumber; - + // idmypos toggle mode - private boolean st_idmypos=false; + private boolean st_idmypos = false; // Massive bunches of cheat shit // to keep it from being easy to figure them out. // Yeah, right... - private char cheat_mus_seq[] = - { 0xb2, 0x26, 0xb6, 0xae, 0xea, 1, 0, 0, 0xff }; + private char cheat_mus_seq[] + = {0xb2, 0x26, 0xb6, 0xae, 0xea, 1, 0, 0, 0xff}; - private char cheat_choppers_seq[] = - { 0xb2, 0x26, 0xe2, 0x32, 0xf6, 0x2a, 0x2a, 0xa6, 0x6a, 0xea, 0xff // id... + private char cheat_choppers_seq[] + = {0xb2, 0x26, 0xe2, 0x32, 0xf6, 0x2a, 0x2a, 0xa6, 0x6a, 0xea, 0xff // id... }; - private char cheat_god_seq[] = { 0xb2, 0x26, 0x26, 0xaa, 0x26, 0xff // iddqd - }; + private char cheat_god_seq[] = {0xb2, 0x26, 0x26, 0xaa, 0x26, 0xff // iddqd +}; - private char cheat_ammo_seq[] = { 0xb2, 0x26, 0xf2, 0x66, 0xa2, 0xff // idkfa - }; + private char cheat_ammo_seq[] = {0xb2, 0x26, 0xf2, 0x66, 0xa2, 0xff // idkfa +}; - private char cheat_ammonokey_seq[] = { 0xb2, 0x26, 0x66, 0xa2, 0xff // idfa - }; + private char cheat_ammonokey_seq[] = {0xb2, 0x26, 0x66, 0xa2, 0xff // idfa +}; // Smashing Pumpkins Into Samml Piles Of Putried Debris. - private char cheat_noclip_seq[] = { 0xb2, 0x26, 0xea, 0x2a, 0xb2, // idspispopd - 0xea, 0x2a, 0xf6, 0x2a, 0x26, 0xff }; + private char cheat_noclip_seq[] = {0xb2, 0x26, 0xea, 0x2a, 0xb2, // idspispopd + 0xea, 0x2a, 0xf6, 0x2a, 0x26, 0xff}; // - private char cheat_commercial_noclip_seq[] = - { 0xb2, 0x26, 0xe2, 0x36, 0xb2, 0x2a, 0xff // idclip + private char cheat_commercial_noclip_seq[] + = {0xb2, 0x26, 0xe2, 0x36, 0xb2, 0x2a, 0xff // idclip }; - private char cheat_powerup_seq[][] = - { { 0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0x6e, 0xff }, // beholdv - { 0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0xea, 0xff }, // beholds - { 0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0xb2, 0xff }, // beholdi - { 0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0x6a, 0xff }, // beholdr - { 0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0xa2, 0xff }, // beholda - { 0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0x36, 0xff }, // beholdl - { 0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0xff } // behold + private char cheat_powerup_seq[][] + = {{0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0x6e, 0xff}, // beholdv + {0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0xea, 0xff}, // beholds + {0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0xb2, 0xff}, // beholdi + {0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0x6a, 0xff}, // beholdr + {0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0xa2, 0xff}, // beholda + {0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0x36, 0xff}, // beholdl + {0xb2, 0x26, 0x62, 0xa6, 0x32, 0xf6, 0x36, 0x26, 0xff} // behold }; - private char cheat_clev_seq[] = - { 0xb2, 0x26, 0xe2, 0x36, 0xa6, 0x6e, 1, 0, 0, 0xff // idclev + private char cheat_clev_seq[] + = {0xb2, 0x26, 0xe2, 0x36, 0xa6, 0x6e, 1, 0, 0, 0xff // idclev }; // my position cheat - private char cheat_mypos_seq[] = - { 0xb2, 0x26, 0xb6, 0xba, 0x2a, 0xf6, 0xea, 0xff // idmypos + private char cheat_mypos_seq[] + = {0xb2, 0x26, 0xb6, 0xba, 0x2a, 0xf6, 0xea, 0xff // idmypos }; // Now what? @@ -505,25 +521,25 @@ public void forceRefresh(){ cheatseq_t cheat_noclip = new cheatseq_t(cheat_noclip_seq, 0); - cheatseq_t cheat_commercial_noclip = - new cheatseq_t(cheat_commercial_noclip_seq, 0); + cheatseq_t cheat_commercial_noclip + = new cheatseq_t(cheat_commercial_noclip_seq, 0); - cheatseq_t[] cheat_powerup = - { new cheatseq_t(cheat_powerup_seq[0], 0), + cheatseq_t[] cheat_powerup + = {new cheatseq_t(cheat_powerup_seq[0], 0), new cheatseq_t(cheat_powerup_seq[1], 0), new cheatseq_t(cheat_powerup_seq[2], 0), new cheatseq_t(cheat_powerup_seq[3], 0), new cheatseq_t(cheat_powerup_seq[4], 0), new cheatseq_t(cheat_powerup_seq[5], 0), - new cheatseq_t(cheat_powerup_seq[6], 0) }; + new cheatseq_t(cheat_powerup_seq[6], 0)}; cheatseq_t cheat_choppers = new cheatseq_t(cheat_choppers_seq, 0); cheatseq_t cheat_clev = new cheatseq_t(cheat_clev_seq, 0); cheatseq_t cheat_mypos = new cheatseq_t(cheat_mypos_seq, 0); - - cheatseq_t cheat_tnthom= new cheatseq_t("tnthom",false); + + cheatseq_t cheat_tnthom = new cheatseq_t("tnthom", false); // String[] mapnames; @@ -531,171 +547,167 @@ public void forceRefresh(){ // // STATUS BAR CODE // - public StatusBar(DoomMain DOOM) { - super(DOOM); - ST_HEIGHT =32*DOOM.vs.getSafeScaling(); - ST_WIDTH =DOOM.vs.getScreenWidth(); - ST_Y =(DOOM.vs.getScreenHeight() - ST_HEIGHT); - ST_X2 = (int) (104*DOOM.vs.getSafeScaling()); - ST_FX = (int) (143*DOOM.vs.getSafeScaling()); - ST_FY = (int) (169*DOOM.vs.getSafeScaling()); - ST_FACESX = (int) (143*DOOM.vs.getSafeScaling()); - - ST_FACESY = (int) (168*DOOM.vs.getSafeScaling()); - - // AMMO number pos. - ST_AMMOWIDTH= 3; - ST_AMMOX = (int) (44*DOOM.vs.getSafeScaling()); - ST_AMMOY = (int) (171*DOOM.vs.getSafeScaling()); - - // HEALTH number pos - ST_HEALTHWIDTH= 3; - ST_HEALTHX = (int) (90*DOOM.vs.getSafeScaling()); - ST_HEALTHY = (int) (171*DOOM.vs.getSafeScaling()); + super(DOOM); + ST_HEIGHT = 32 * DOOM.vs.getSafeScaling(); + ST_WIDTH = DOOM.vs.getScreenWidth(); + ST_Y = (DOOM.vs.getScreenHeight() - ST_HEIGHT); + ST_X2 = (int) (104 * DOOM.vs.getSafeScaling()); + ST_FX = (int) (143 * DOOM.vs.getSafeScaling()); + ST_FY = (int) (169 * DOOM.vs.getSafeScaling()); + ST_FACESX = (int) (143 * DOOM.vs.getSafeScaling()); + + ST_FACESY = (int) (168 * DOOM.vs.getSafeScaling()); + + // AMMO number pos. + ST_AMMOWIDTH = 3; + ST_AMMOX = (int) (44 * DOOM.vs.getSafeScaling()); + ST_AMMOY = (int) (171 * DOOM.vs.getSafeScaling()); + + // HEALTH number pos + ST_HEALTHWIDTH = 3; + ST_HEALTHX = (int) (90 * DOOM.vs.getSafeScaling()); + ST_HEALTHY = (int) (171 * DOOM.vs.getSafeScaling()); + + // Weapon pos. + ST_ARMSX = (int) (111 * DOOM.vs.getSafeScaling()); + ST_ARMSY = (int) (172 * DOOM.vs.getSafeScaling()); + ST_ARMSBGX = (int) (104 * DOOM.vs.getSafeScaling()); + ST_ARMSBGY = (int) (168 * DOOM.vs.getSafeScaling()); + ST_ARMSXSPACE = 12 * DOOM.vs.getSafeScaling();; + ST_ARMSYSPACE = 10 * DOOM.vs.getSafeScaling();; + + // Frags pos. + ST_FRAGSX = (int) (138 * DOOM.vs.getSafeScaling()); + ST_FRAGSY = (int) (171 * DOOM.vs.getSafeScaling()); + ST_FRAGSWIDTH = 2; - // Weapon pos. - ST_ARMSX = (int) (111*DOOM.vs.getSafeScaling()); - ST_ARMSY = (int) (172*DOOM.vs.getSafeScaling()); - ST_ARMSBGX = (int) (104*DOOM.vs.getSafeScaling()); - ST_ARMSBGY = (int) (168*DOOM.vs.getSafeScaling()); - ST_ARMSXSPACE = 12*DOOM.vs.getSafeScaling();; - ST_ARMSYSPACE = 10*DOOM.vs.getSafeScaling();; - - // Frags pos. - ST_FRAGSX = (int) (138*DOOM.vs.getSafeScaling()); - ST_FRAGSY = (int) (171*DOOM.vs.getSafeScaling()); - ST_FRAGSWIDTH=2; - - // - + // + ST_ARMORX = (int) (221 * DOOM.vs.getSafeScaling()); - - ST_ARMORX = (int) (221*DOOM.vs.getSafeScaling()); + ST_ARMORY = (int) (171 * DOOM.vs.getSafeScaling()); - ST_ARMORY = (int) (171*DOOM.vs.getSafeScaling()); + // Key icon positions. + ST_KEY0WIDTH = 8 * DOOM.vs.getSafeScaling();; + ST_KEY0HEIGHT = 5 * DOOM.vs.getSafeScaling(); - // Key icon positions. - ST_KEY0WIDTH = 8*DOOM.vs.getSafeScaling();; - ST_KEY0HEIGHT = 5*DOOM.vs.getSafeScaling();; - - ST_KEY0X = (int) (239*DOOM.vs.getSafeScaling()); - ST_KEY0Y = (int) (171*DOOM.vs.getSafeScaling()); + ST_KEY0X = (int) (239 * DOOM.vs.getSafeScaling()); + ST_KEY0Y = (int) (171 * DOOM.vs.getSafeScaling()); - ST_KEY1WIDTH = ST_KEY0WIDTH; - ST_KEY1X = (int) (239*DOOM.vs.getSafeScaling()); - ST_KEY1Y = (int) (181*DOOM.vs.getSafeScaling()); + ST_KEY1WIDTH = ST_KEY0WIDTH; + ST_KEY1X = (int) (239 * DOOM.vs.getSafeScaling()); + ST_KEY1Y = (int) (181 * DOOM.vs.getSafeScaling()); - ST_KEY2WIDTH = ST_KEY0WIDTH; - ST_KEY2X = (int) (239*DOOM.vs.getSafeScaling()); - ST_KEY2Y = (int) (191*DOOM.vs.getSafeScaling()); + ST_KEY2WIDTH = ST_KEY0WIDTH; + ST_KEY2X = (int) (239 * DOOM.vs.getSafeScaling()); + ST_KEY2Y = (int) (191 * DOOM.vs.getSafeScaling()); - // Ammunition counter. - ST_AMMO0WIDTH = 3*DOOM.vs.getSafeScaling(); - ST_AMMO0HEIGHT = 6*DOOM.vs.getSafeScaling(); + // Ammunition counter. + ST_AMMO0WIDTH = 3 * DOOM.vs.getSafeScaling(); + ST_AMMO0HEIGHT = 6 * DOOM.vs.getSafeScaling(); - ST_AMMO0X = (int) (288*DOOM.vs.getSafeScaling()); + ST_AMMO0X = (int) (288 * DOOM.vs.getSafeScaling()); - ST_AMMO0Y = (int) (173*DOOM.vs.getSafeScaling()); + ST_AMMO0Y = (int) (173 * DOOM.vs.getSafeScaling()); - ST_AMMO1WIDTH = ST_AMMO0WIDTH; + ST_AMMO1WIDTH = ST_AMMO0WIDTH; - ST_AMMO1X = (int) (288*DOOM.vs.getSafeScaling()); + ST_AMMO1X = (int) (288 * DOOM.vs.getSafeScaling()); - ST_AMMO1Y = (int) (179*DOOM.vs.getSafeScaling()); + ST_AMMO1Y = (int) (179 * DOOM.vs.getSafeScaling()); - ST_AMMO2WIDTH = ST_AMMO0WIDTH; + ST_AMMO2WIDTH = ST_AMMO0WIDTH; - ST_AMMO2X = (int) (288*DOOM.vs.getSafeScaling()); + ST_AMMO2X = (int) (288 * DOOM.vs.getSafeScaling()); - ST_AMMO2Y = (int) (191*DOOM.vs.getSafeScaling()); + ST_AMMO2Y = (int) (191 * DOOM.vs.getSafeScaling()); - ST_AMMO3WIDTH = ST_AMMO0WIDTH; + ST_AMMO3WIDTH = ST_AMMO0WIDTH; - ST_AMMO3X = (int) (288*DOOM.vs.getSafeScaling()); + ST_AMMO3X = (int) (288 * DOOM.vs.getSafeScaling()); - ST_AMMO3Y = (int) (185*DOOM.vs.getSafeScaling()); + ST_AMMO3Y = (int) (185 * DOOM.vs.getSafeScaling()); - // Indicate maximum ammunition. - // Only needed because backpack exists. - ST_MAXAMMO0WIDTH = 3*DOOM.vs.getSafeScaling(); - ST_MAXAMMO0HEIGHT = 5*DOOM.vs.getSafeScaling(); + // Indicate maximum ammunition. + // Only needed because backpack exists. + ST_MAXAMMO0WIDTH = 3 * DOOM.vs.getSafeScaling(); + ST_MAXAMMO0HEIGHT = 5 * DOOM.vs.getSafeScaling(); - ST_MAXAMMO0X = (int) (314*DOOM.vs.getSafeScaling()); - ST_MAXAMMO0Y = (int) (173*DOOM.vs.getSafeScaling()); + ST_MAXAMMO0X = (int) (314 * DOOM.vs.getSafeScaling()); + ST_MAXAMMO0Y = (int) (173 * DOOM.vs.getSafeScaling()); - ST_MAXAMMO1WIDTH = ST_MAXAMMO0WIDTH; - ST_MAXAMMO1X = 314*DOOM.vs.getSafeScaling(); - ST_MAXAMMO1Y = (int) (179*DOOM.vs.getSafeScaling()); + ST_MAXAMMO1WIDTH = ST_MAXAMMO0WIDTH; + ST_MAXAMMO1X = 314 * DOOM.vs.getSafeScaling(); + ST_MAXAMMO1Y = (int) (179 * DOOM.vs.getSafeScaling()); - ST_MAXAMMO2WIDTH = ST_MAXAMMO0WIDTH; - ST_MAXAMMO2X = (int) (314*DOOM.vs.getSafeScaling()); - ST_MAXAMMO2Y = (int) (191*DOOM.vs.getSafeScaling()); + ST_MAXAMMO2WIDTH = ST_MAXAMMO0WIDTH; + ST_MAXAMMO2X = (int) (314 * DOOM.vs.getSafeScaling()); + ST_MAXAMMO2Y = (int) (191 * DOOM.vs.getSafeScaling()); - ST_MAXAMMO3WIDTH = ST_MAXAMMO0WIDTH; - ST_MAXAMMO3X = (int) (314*DOOM.vs.getSafeScaling()); - ST_MAXAMMO3Y = (int) (185*DOOM.vs.getSafeScaling()); + ST_MAXAMMO3WIDTH = ST_MAXAMMO0WIDTH; + ST_MAXAMMO3X = (int) (314 * DOOM.vs.getSafeScaling()); + ST_MAXAMMO3Y = (int) (185 * DOOM.vs.getSafeScaling()); - // pistol - ST_WEAPON0X = (int) (110*DOOM.vs.getSafeScaling()); - ST_WEAPON0Y = (int) (172*DOOM.vs.getSafeScaling()); + // pistol + ST_WEAPON0X = (int) (110 * DOOM.vs.getSafeScaling()); + ST_WEAPON0Y = (int) (172 * DOOM.vs.getSafeScaling()); - // shotgun - ST_WEAPON1X = (int) (122*DOOM.vs.getSafeScaling()); - ST_WEAPON1Y = (int) (172*DOOM.vs.getSafeScaling()); + // shotgun + ST_WEAPON1X = (int) (122 * DOOM.vs.getSafeScaling()); + ST_WEAPON1Y = (int) (172 * DOOM.vs.getSafeScaling()); - // chain gun - ST_WEAPON2X = (int) (134*DOOM.vs.getSafeScaling()); + // chain gun + ST_WEAPON2X = (int) (134 * DOOM.vs.getSafeScaling()); - ST_WEAPON2Y = (int) (172*DOOM.vs.getSafeScaling()); + ST_WEAPON2Y = (int) (172 * DOOM.vs.getSafeScaling()); - // missile launcher - ST_WEAPON3X = (int) (110*DOOM.vs.getSafeScaling()); + // missile launcher + ST_WEAPON3X = (int) (110 * DOOM.vs.getSafeScaling()); - ST_WEAPON3Y = (int) (181*DOOM.vs.getSafeScaling()); + ST_WEAPON3Y = (int) (181 * DOOM.vs.getSafeScaling()); - // plasma gun - ST_WEAPON4X = (int) (122*DOOM.vs.getSafeScaling()); + // plasma gun + ST_WEAPON4X = (int) (122 * DOOM.vs.getSafeScaling()); - ST_WEAPON4Y = (int) (181*DOOM.vs.getSafeScaling()); + ST_WEAPON4Y = (int) (181 * DOOM.vs.getSafeScaling()); - // bfg - ST_WEAPON5X = (int) (134*DOOM.vs.getSafeScaling()); + // bfg + ST_WEAPON5X = (int) (134 * DOOM.vs.getSafeScaling()); - ST_WEAPON5Y = (int) (181*DOOM.vs.getSafeScaling()); + ST_WEAPON5Y = (int) (181 * DOOM.vs.getSafeScaling()); - // WPNS title - ST_WPNSX = (int) (109*DOOM.vs.getSafeScaling()); + // WPNS title + ST_WPNSX = (int) (109 * DOOM.vs.getSafeScaling()); - ST_WPNSY = (int) (191*DOOM.vs.getSafeScaling()); + ST_WPNSY = (int) (191 * DOOM.vs.getSafeScaling()); - // DETH title - ST_DETHX = (int) (109*DOOM.vs.getSafeScaling()); + // DETH title + ST_DETHX = (int) (109 * DOOM.vs.getSafeScaling()); - ST_DETHY = (int) (191*DOOM.vs.getSafeScaling()); + ST_DETHY = (int) (191 * DOOM.vs.getSafeScaling()); - ST_RECT = new Rectangle(ST_X, 0, ST_WIDTH, ST_HEIGHT); - //this.plyr=DM.players[DM.] + ST_RECT = new Rectangle(ST_X, 0, ST_WIDTH, ST_HEIGHT); + //this.plyr=DM.players[DM.] } public void refreshBackground() { if (st_statusbaron[0]) { - DOOM.graphicSystem.DrawPatchScaled(SB, sbar, DOOM.vs, ST_X, 0, V_SAFESCALE|V_NOSCALESTART); + DOOM.graphicSystem.DrawPatchScaled(SB, sbar, DOOM.vs, ST_X, 0, V_SAFESCALE | V_NOSCALESTART); //V.DrawPatch(ST_X, 0, BG, sbar); if (DOOM.netgame) { - DOOM.graphicSystem.DrawPatchScaled(SB, faceback, DOOM.vs, ST_FX, ST_Y, V_SAFESCALE|V_NOSCALESTART); + DOOM.graphicSystem.DrawPatchScaled(SB, faceback, DOOM.vs, ST_FX, ST_Y, V_SAFESCALE | V_NOSCALESTART); //V.DrawPatch(ST_FX, 0, BG, faceback); } - + // Buffers the background. DOOM.graphicSystem.CopyRect(SB, ST_RECT, FG, DOOM.graphicSystem.point(ST_X, ST_Y)); //V.CopyRect(ST_X, 0, SCREEN_SB, ST_WIDTH, ST_HEIGHT, ST_X, ST_Y, SCREEN_FG); } } - + public void Init() { veryfirsttime = 0; loadData(); @@ -717,8 +729,9 @@ public void Start() { } public void Stop() { - if (st_stopped) + if (st_stopped) { return; + } // Reset palette. DOOM.graphicSystem.setPalette(0); @@ -731,11 +744,10 @@ public void loadData() { } // Filter automap on/off. - @Override public void NotifyAMEnter() { - st_gamestate = st_stateenum_t.AutomapState; - st_firsttime = true; + st_gamestate = st_stateenum_t.AutomapState; + st_firsttime = true; } @Override @@ -746,7 +758,6 @@ public void NotifyAMExit() { // Respond to keyboard input events, // intercept cheats. - @Override @ST_Stuff.C(ST_Responder) public boolean Responder(event_t ev) { @@ -759,42 +770,42 @@ public boolean Responder(event_t ev) { if (ev.ifKeyAsciiChar(cheat_god::CheckCheat)) { plyr.cheats ^= CF_GODMODE; if ((plyr.cheats & CF_GODMODE) != 0) { - if (plyr.mo != null) + if (plyr.mo != null) { plyr.mo.health = 100; + } plyr.health[0] = 100; plyr.message = STSTR_DQDON; - } else + } else { plyr.message = STSTR_DQDOFF; - } - // 'fa' cheat for killer fucking arsenal + } + } // 'fa' cheat for killer fucking arsenal else if (ev.ifKeyAsciiChar(cheat_ammonokey::CheckCheat)) { plyr.armorpoints[0] = 200; plyr.armortype = 2; - for (int i = 0; i < NUMWEAPONS; i++) + for (int i = 0; i < NUMWEAPONS; i++) { plyr.weaponowned[i] = true; // true - + } System.arraycopy(plyr.maxammo, 0, plyr.ammo, 0, NUMAMMO); plyr.message = STSTR_FAADDED; - } - // 'kfa' cheat for key full ammo + } // 'kfa' cheat for key full ammo else if (ev.ifKeyAsciiChar(cheat_ammo::CheckCheat)) { plyr.armorpoints[0] = 200; plyr.armortype = 2; - for (int i = 0; i < NUMWEAPONS; i++) + for (int i = 0; i < NUMWEAPONS; i++) { plyr.weaponowned[i] = true; // true - + } System.arraycopy(plyr.maxammo, 0, plyr.ammo, 0, NUMAMMO); - for (int i = 0; i < NUMCARDS; i++) + for (int i = 0; i < NUMCARDS; i++) { plyr.cards[i] = true; + } plyr.message = STSTR_KFAADDED; - } - // 'mus' cheat for changing music + } // 'mus' cheat for changing music else if (ev.ifKeyAsciiChar(cheat_mus::CheckCheat)) { char[] buf = new char[3]; @@ -804,44 +815,47 @@ else if (ev.ifKeyAsciiChar(cheat_mus::CheckCheat)) { cheat_mus.GetParam(buf); if (DOOM.isCommercial()) { - musnum = - musicenum_t.mus_runnin.ordinal() + (buf[0] - '0') - * 10 + buf[1] - '0' - 1; + musnum + = musicenum_t.mus_runnin.ordinal() + (buf[0] - '0') + * 10 + buf[1] - '0' - 1; - if (((buf[0] - '0') * 10 + buf[1] - '0') > 35) + if (((buf[0] - '0') * 10 + buf[1] - '0') > 35) { plyr.message = STSTR_NOMUS; - else - DOOM.doomSound.ChangeMusic(musnum, true); + } else { + DOOM.doomSound.ChangeMusic(musnum, true); + } } else { - musnum = - musicenum_t.mus_e1m1.ordinal() + (buf[0] - '1') * 9 - + (buf[1] - '1'); + musnum + = musicenum_t.mus_e1m1.ordinal() + (buf[0] - '1') * 9 + + (buf[1] - '1'); - if (((buf[0] - '1') * 9 + buf[1] - '1') > 31) + if (((buf[0] - '1') * 9 + buf[1] - '1') > 31) { plyr.message = STSTR_NOMUS; - else - DOOM.doomSound.ChangeMusic(musnum, true); + } else { + DOOM.doomSound.ChangeMusic(musnum, true); + } } - } - // Simplified, accepting both "noclip" and "idspispopd". + } // Simplified, accepting both "noclip" and "idspispopd". // no clipping mode cheat else if (ev.ifKeyAsciiChar(cheat_noclip::CheckCheat) || ev.ifKeyAsciiChar(cheat_commercial_noclip::CheckCheat)) { plyr.cheats ^= CF_NOCLIP; - if ((plyr.cheats & CF_NOCLIP) != 0) + if ((plyr.cheats & CF_NOCLIP) != 0) { plyr.message = STSTR_NCON; - else + } else { plyr.message = STSTR_NCOFF; + } } // 'behold?' power-up cheats for (int i = 0; i < 6; i++) { if (ev.ifKeyAsciiChar(cheat_powerup[i]::CheckCheat)) { - if (plyr.powers[i] == 0) - plyr.GivePower(i); - else if (i != pw_strength) + if (plyr.powers[i] == 0) { + plyr.GivePower(i); + } else if (i != pw_strength) { plyr.powers[i] = 1; - else + } else { plyr.powers[i] = 0; + } plyr.message = STSTR_BEHOLDX; } @@ -850,22 +864,19 @@ else if (i != pw_strength) // 'behold' power-up menu if (ev.ifKeyAsciiChar(cheat_powerup[6]::CheckCheat)) { plyr.message = STSTR_BEHOLD; - } - // 'choppers' invulnerability & chainsaw + } // 'choppers' invulnerability & chainsaw else if (ev.ifKeyAsciiChar(cheat_choppers::CheckCheat)) { plyr.weaponowned[weapontype_t.wp_chainsaw.ordinal()] = true; plyr.powers[pw_invulnerability] = 1; // true plyr.message = STSTR_CHOPPERS; - } - // 'mypos' for player position + } // 'mypos' for player position else if (ev.ifKeyAsciiChar(cheat_mypos::CheckCheat)) { // MAES: made into a toggleable cheat. - this.st_idmypos=!st_idmypos; - } - else if (ev.ifKeyAsciiChar(cheat_tnthom::CheckCheat)) { + this.st_idmypos = !st_idmypos; + } else if (ev.ifKeyAsciiChar(cheat_tnthom::CheckCheat)) { // MAES: made into a toggleable cheat. - plyr.message = (DOOM.flashing_hom = !DOOM.flashing_hom) ? "HOM Detection On" : - "HOM Detection Off"; + plyr.message = (DOOM.flashing_hom = !DOOM.flashing_hom) ? "HOM Detection On" + : "HOM Detection Off"; } } @@ -887,29 +898,35 @@ else if (ev.ifKeyAsciiChar(cheat_tnthom::CheckCheat)) { } // Catch invalid maps. - if (epsd < 1 && (!DOOM.isCommercial())) + if (epsd < 1 && (!DOOM.isCommercial())) { return false; + } - if (map < 1) + if (map < 1) { return false; + } // Ohmygod - this is not going to work. if (DOOM.isRetail() - && ((epsd > 4) || (map > 9))) + && ((epsd > 4) || (map > 9))) { return false; + } // MAES: If it's doom.wad but not ultimate - if (DOOM.isRegistered()&& !DOOM.isRetail() - && ((epsd > 3) || (map > 9))) + if (DOOM.isRegistered() && !DOOM.isRetail() + && ((epsd > 3) || (map > 9))) { return false; + } if (DOOM.isShareware() - && ((epsd > 1) || (map > 9))) + && ((epsd > 1) || (map > 9))) { return false; + } if (DOOM.isCommercial() - && ((epsd > 1) || (map > 34))) + && ((epsd > 1) || (map > 34))) { return false; + } // So be it. plyr.message = STSTR_CLEV; @@ -929,8 +946,8 @@ public int calcPainOffset() { health = plyr.health[0] > 100 ? 100 : plyr.health[0]; if (health != oldhealth) { - lastcalc = - ST_FACESTRIDE * (((100 - health) * ST_NUMPAINFACES) / 101); + lastcalc + = ST_FACESTRIDE * (((100 - health) * ST_NUMPAINFACES) / 101); oldhealth = health; } return lastcalc; @@ -991,15 +1008,14 @@ public void updateFaceWidget() { * - Good Sign 2017/04/02 */ if ((DOOM.CM.equals(Settings.fix_ouch_face, Boolean.TRUE) - ? st_oldhealth - plyr.health[0] - : plyr.health[0] - st_oldhealth) > ST_MUCHPAIN) - { + ? st_oldhealth - plyr.health[0] + : plyr.health[0] - st_oldhealth) > ST_MUCHPAIN) { st_facecount = ST_TURNCOUNT; st_faceindex[0] = calcPainOffset() + ST_OUCHOFFSET; } else { - badguyangle = - DOOM.sceneRenderer.PointToAngle2(plyr.mo.x, plyr.mo.y, plyr.attacker.x, - plyr.attacker.y); + badguyangle + = DOOM.sceneRenderer.PointToAngle2(plyr.mo.x, plyr.mo.y, plyr.attacker.x, + plyr.attacker.y); boolean obtuse; // that's another "i" if (badguyangle > plyr.mo.angle) { @@ -1037,9 +1053,8 @@ public void updateFaceWidget() { * - Good Sign 2017/04/02 */ if ((DOOM.CM.equals(Settings.fix_ouch_face, Boolean.TRUE) - ? st_oldhealth - plyr.health[0] - : plyr.health[0] - st_oldhealth) > ST_MUCHPAIN) - { + ? st_oldhealth - plyr.health[0] + : plyr.health[0] - st_oldhealth) > ST_MUCHPAIN) { priority = 7; st_facecount = ST_TURNCOUNT; st_faceindex[0] = calcPainOffset() + ST_OUCHOFFSET; @@ -1056,16 +1071,17 @@ public void updateFaceWidget() { if (priority < 6) { // rapid firing if (plyr.attackdown) { - if (lastattackdown == -1) + if (lastattackdown == -1) { lastattackdown = ST_RAMPAGEDELAY; - else if (--lastattackdown == 0) { + } else if (--lastattackdown == 0) { priority = 5; st_faceindex[0] = calcPainOffset() + ST_RAMPAGEOFFSET; st_facecount = 1; lastattackdown = 1; } - } else + } else { lastattackdown = -1; + } } @@ -1107,7 +1123,6 @@ else if (--lastattackdown == 0) { * updates are performed by the Drawer. * */ - public void updateWidgets() { int i; @@ -1115,23 +1130,22 @@ public void updateWidgets() { // MAES: sticky idmypos cheat that is actually useful // TODO: this spams the player message queue at every tic. // A direct overlay with a widget would be more useful. - - if (this.st_idmypos){ + if (this.st_idmypos) { mobj_t mo = DOOM.players[DOOM.consoleplayer].mo; plyr.message = String.format("ang= 0x%x; x,y= (%x, %x)", - (int)mo.angle,mo.x,mo.y); + (int) mo.angle, mo.x, mo.y); } - // must redirect the pointer if the ready weapon has changed. // if (w_ready.data != plyr.readyweapon) // { - if (weaponinfo[plyr.readyweapon.ordinal()].ammo == ammotype_t.am_noammo) + if (weaponinfo[plyr.readyweapon.ordinal()].ammo == ammotype_t.am_noammo) { w_ready.numindex = largeammo; - else - w_ready.numindex = - weaponinfo[plyr.readyweapon.ordinal()].ammo.ordinal(); + } else { + w_ready.numindex + = weaponinfo[plyr.readyweapon.ordinal()].ammo.ordinal(); + } w_ready.data = plyr.readyweapon.ordinal(); @@ -1139,13 +1153,13 @@ public void updateWidgets() { // STlib_updateNum(&w_ready, true); // refresh weapon change // } - // update keycard multiple widgets for (i = 0; i < 3; i++) { keyboxes[i] = plyr.cards[i] ? i : -1; - if (plyr.cards[i + 3]) + if (plyr.cards[i + 3]) { keyboxes[i] = i + 3; + } } // refresh everything if this is him coming back to life @@ -1155,22 +1169,24 @@ public void updateWidgets() { st_notdeathmatch[0] = !DOOM.deathmatch; // used by w_arms[] widgets - st_armson[0] = st_statusbaron[0] && !(DOOM.altdeath||DOOM.deathmatch); + st_armson[0] = st_statusbaron[0] && !(DOOM.altdeath || DOOM.deathmatch); // used by w_frags widget - st_fragson[0] = (DOOM.altdeath||DOOM.deathmatch) && st_statusbaron[0]; + st_fragson[0] = (DOOM.altdeath || DOOM.deathmatch) && st_statusbaron[0]; st_fragscount[0] = 0; for (i = 0; i < MAXPLAYERS; i++) { - if (i != DOOM.consoleplayer) + if (i != DOOM.consoleplayer) { st_fragscount[0] += plyr.frags[i]; - else + } else { st_fragscount[0] -= plyr.frags[i]; + } } // get rid of chat window if up because of message - if (--st_msgcounter == 0) + if (--st_msgcounter == 0) { st_chat = st_oldchat; + } } @@ -1198,33 +1214,33 @@ public void doPaletteStuff() { // slowly fade the berzerk out bzc = 12 - (plyr.powers[pw_strength] >> 6); - if (bzc > cnt) + if (bzc > cnt) { cnt = bzc; + } } if (cnt != 0) { palette = (cnt + 7) >> 3; - if (palette >= NUMREDPALS) + if (palette >= NUMREDPALS) { palette = NUMREDPALS - 1; + } palette += STARTREDPALS; - } - - else if (plyr.bonuscount != 0) { + } else if (plyr.bonuscount != 0) { palette = (plyr.bonuscount + 7) >> 3; - if (palette >= NUMBONUSPALS) + if (palette >= NUMBONUSPALS) { palette = NUMBONUSPALS - 1; + } palette += STARTBONUSPALS; - } - - else if (plyr.powers[pw_ironfeet] > 4 * 32 - || (plyr.powers[pw_ironfeet] & 8) != 0) + } else if (plyr.powers[pw_ironfeet] > 4 * 32 + || (plyr.powers[pw_ironfeet] & 8) != 0) { palette = RADIATIONPAL; - else + } else { palette = 0; + } if (palette != st_palette) { st_palette = palette; @@ -1237,7 +1253,7 @@ public void drawWidgets(boolean refresh) { int i; // used by w_arms[] widgets - st_armson[0] = st_statusbaron[0] && !(DOOM.altdeath||DOOM.deathmatch); + st_armson[0] = st_statusbaron[0] && !(DOOM.altdeath || DOOM.deathmatch); // used by w_frags widget st_fragson[0] = DOOM.deathmatch && st_statusbaron[0]; @@ -1253,13 +1269,15 @@ public void drawWidgets(boolean refresh) { w_armsbg.update(refresh); - for (i = 0; i < 6; i++) + for (i = 0; i < 6; i++) { w_arms[i].update(refresh); + } w_faces.update(refresh); - for (i = 0; i < 3; i++) + for (i = 0; i < 3; i++) { w_keyboxes[i].update(refresh); + } w_frags.update(refresh); @@ -1292,11 +1310,12 @@ public void Drawer(boolean fullscreen, boolean refresh) { doPaletteStuff(); // If just after ST_Start(), refresh all - if (st_firsttime) + if (st_firsttime) { doRefresh(); - // Otherwise, update as little as possible - else + } // Otherwise, update as little as possible + else { diffDraw(); + } } @@ -1322,7 +1341,7 @@ public void loadGraphics() { // Note: why not load STMINUS here, too? tallpercent = DOOM.wadLoader.CachePatchName("STTPRCNT", PU_STATIC); // MAES: in fact, I do this for sanity. Fuck them. Seriously. - sttminus= DOOM.wadLoader.CachePatchName("STTMINUS"); + sttminus = DOOM.wadLoader.CachePatchName("STTMINUS"); // key cards for (i = 0; i < NUMCARDS; i++) { @@ -1375,54 +1394,50 @@ public void loadGraphics() { } public void unloadGraphics() { - - int i; // unload the numbers, tall and short - for (i=0;i<10;i++) { - DOOM.wadLoader.UnlockLumpNum(tallnum[i]); - tallnum[i]=null; - DOOM.wadLoader.UnlockLumpNum(shortnum[i]); - shortnum[i]=null; - } - - // unload tall percent - DOOM.wadLoader.UnlockLumpNum(tallpercent); - tallpercent=null; - - - // unload arms background - DOOM.wadLoader.UnlockLumpNum(armsbg); - armsbg=null; - // unload gray #'s - for (i=0;i<6;i++) { - DOOM.wadLoader.UnlockLumpNum(arms[i][0]); - arms[i][0]=null; - DOOM.wadLoader.UnlockLumpNum(arms[i][1]); - arms[i][1]=null; - - } - - // unload the key cards for (i=0;i> int find(final List list, - final Function converter, - final E key) - { return find(list, converter, 0, list.size(), key); } + final Function converter, + final E key) { + return find(list, converter, 0, list.size(), key); + } - /** - * Binary search supporting search for one type of objects - * using object of another type, given from any object of one type - * a function can get an object of another type - * - * @param array of one type of objects - * @param converter from one type of objects to another - * @param key a value of another object type - * @return - */ - public static > int find(final T[] array, - final Function converter, - final E key) - { return find(array, converter, 0, array.length, key); } + /** + * Binary search supporting search for one type of objects + * using object of another type, given from any object of one type + * a function can get an object of another type + * + * @param array of one type of objects + * @param converter from one type of objects to another + * @param key a value of another object type + * @return + */ + public static > int find(final T[] array, + final Function converter, + final E key) { + return find(array, converter, 0, array.length, key); + } - /** - * Binary search supporting search for one type of objects - * using object of another type, given from any object of one type - * a function can get an object of another type - * - * @param list of one type of objects - * @param comparator - a comparator for objects of type E - * @param converter from one type of objects to another - * @param key a value of another object type - * @return - */ - public static int find(final List list, - final Function converter, - final Comparator comparator, - final E key) - { return find(list, converter, comparator, 0, list.size(), key); } + /** + * Binary search supporting search for one type of objects + * using object of another type, given from any object of one type + * a function can get an object of another type + * + * @param list of one type of objects + * @param comparator - a comparator for objects of type E + * @param converter from one type of objects to another + * @param key a value of another object type + * @return + */ + public static int find(final List list, + final Function converter, + final Comparator comparator, + final E key) { + return find(list, converter, comparator, 0, list.size(), key); + } - /** - * Binary search supporting search for one type of objects - * using object of another type, given from any object of one type - * a function can get an object of another type - * - * @param array of one type of objects - * @param comparator - a comparator for objects of type E - * @param converter from one type of objects to another - * @param key a value of another object type - * @return - */ - public static int find(final T[] array, - final Function converter, - final Comparator comparator, - final E key) - { return find(array, converter, comparator, 0, array.length, key); } + /** + * Binary search supporting search for one type of objects + * using object of another type, given from any object of one type + * a function can get an object of another type + * + * @param array of one type of objects + * @param comparator - a comparator for objects of type E + * @param converter from one type of objects to another + * @param key a value of another object type + * @return + */ + public static int find(final T[] array, + final Function converter, + final Comparator comparator, + final E key) { + return find(array, converter, comparator, 0, array.length, key); + } - /** - * Binary search supporting search for one type of objects - * using primitive integer, given from any object - * of one type a function can get a primitive integer - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive integer - * @param a primitive integer key value - * @return - */ - public static int findByInt(final List list, - final ToIntFunction converter, - final int key) - { return findByInt(list, converter, 0, list.size(), key); } - - /** - * Binary search supporting search for one type of objects - * using primitive integer, given from any object - * of one type a function can get a primitive integer - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive integer - * @param a primitive integer key value - * @return - */ - public static int findByInt(final T[] array, - final ToIntFunction converter, - final int key) - { return findByInt(array, converter, 0, array.length, key); } - - /** - * Binary search supporting search for one type of objects - * using primitive integer, given from any object - * of one type a function can get a primitive integer - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive integer - * @param comparator - a comparator for primitive integer values - * @param a primitive integer key value - * @return - */ - public static int findByInt(final List list, - final ToIntFunction converter, - final IntBinaryOperator comparator, - final int key) - { return findByInt(list, converter, comparator, 0, list.size(), key); } - - /** - * Binary search supporting search for one type of objects - * using primitive integer, given from any object - * of one type a function can get a primitive integer - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive integer - * @param comparator - a comparator for primitive integer values - * @param a primitive integer key value - * @return - */ - public static int findByInt(final T[] array, - final ToIntFunction converter, - final IntBinaryOperator comparator, - final int key) - { return findByInt(array, converter, comparator, 0, array.length, key); } - - /** - * Binary search supporting search for one type of objects - * using primitive long, given from any object - * of one type a function can get a primitive long - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive long - * @param a primitive long key value - * @return - */ - public static int findByLong(final List list, - final ToLongFunction converter, - final long key) - { return findByLong(list, converter, 0, list.size(), key); } - - /** - * Binary search supporting search for one type of objects - * using primitive long, given from any object - * of one type a function can get a primitive long - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive long - * @param a primitive long key value - * @return - */ - public static int findByLong(final T[] array, - final ToLongFunction converter, - final long key) - { return findByLong(array, converter, 0, array.length, key); } - - /** - * Binary search supporting search for one type of objects - * using primitive long, given from any object - * of one type a function can get a primitive long - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive long - * @param comparator - a comparator for primitive long values - * @param a primitive long key value - * @return - */ - public static int findByLong(final List list, - final ToLongFunction converter, - final LongComparator comparator, - final long key) - { return findByLong(list, converter, comparator, 0, list.size(), key); } - - /** - * Binary search supporting search for one type of objects - * using primitive long, given from any object - * of one type a function can get a primitive long - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive long - * @param comparator - a comparator for primitive long values - * @param a primitive long key value - * @return - */ - public static int findByLong(final T[] array, - final ToLongFunction converter, - final LongComparator comparator, - final long key) - { return findByLong(array, converter, comparator, 0, array.length, key); } - - /** - * Binary search supporting search for one type of objects - * using primitive double, given from any object - * of one type a function can get a primitive double - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive double - * @param a primitive double key value - * @return - */ - public static int findByDouble(final List list, - final ToDoubleFunction converter, - final double key) - { return findByDouble(list, converter, 0, list.size(), key); } + /** + * Binary search supporting search for one type of objects + * using primitive integer, given from any object + * of one type a function can get a primitive integer + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive integer + * @param a primitive integer key value + * @return + */ + public static int findByInt(final List list, + final ToIntFunction converter, + final int key) { + return findByInt(list, converter, 0, list.size(), key); + } - /** - * Binary search supporting search for one type of objects - * using primitive double, given from any object - * of one type a function can get a primitive double - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive double - * @param a primitive double key value - * @return - */ - public static int findByDouble(final T[] array, - final ToDoubleFunction converter, - final double key) - { return findByDouble(array, converter, 0, array.length, key); } + /** + * Binary search supporting search for one type of objects + * using primitive integer, given from any object + * of one type a function can get a primitive integer + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive integer + * @param a primitive integer key value + * @return + */ + public static int findByInt(final T[] array, + final ToIntFunction converter, + final int key) { + return findByInt(array, converter, 0, array.length, key); + } - /** - * Binary search supporting search for one type of objects - * using primitive double, given from any object - * of one type a function can get a primitive double - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive double - * @param comparator - a comparator for primitive double values - * @param a primitive double key value - * @return - */ - public static int findByDouble(final List list, - final ToDoubleFunction converter, - final DoubleComparator comparator, - final double key) - { return findByDouble(list, converter, comparator, 0, list.size(), key); } + /** + * Binary search supporting search for one type of objects + * using primitive integer, given from any object + * of one type a function can get a primitive integer + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive integer + * @param comparator - a comparator for primitive integer values + * @param a primitive integer key value + * @return + */ + public static int findByInt(final List list, + final ToIntFunction converter, + final IntBinaryOperator comparator, + final int key) { + return findByInt(list, converter, comparator, 0, list.size(), key); + } - /** - * Binary search supporting search for one type of objects - * using primitive double, given from any object - * of one type a function can get a primitive double - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive double - * @param comparator - a comparator for primitive double values - * @param a primitive double key value - * @return - */ - public static int findByDouble(final T[] array, - final ToDoubleFunction converter, - final DoubleComparator comparator, - final double key) - { return findByDouble(array, converter, comparator, 0, array.length, key); } + /** + * Binary search supporting search for one type of objects + * using primitive integer, given from any object + * of one type a function can get a primitive integer + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive integer + * @param comparator - a comparator for primitive integer values + * @param a primitive integer key value + * @return + */ + public static int findByInt(final T[] array, + final ToIntFunction converter, + final IntBinaryOperator comparator, + final int key) { + return findByInt(array, converter, comparator, 0, array.length, key); + } - /** - * Binary search supporting search for one type of objects - * using object of another type, given from any object of one type - * a function can get an object of another type - * - * @param list of one type of objects - * @param converter from one type of objects to another - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key a value of another object type - * @return - */ - public static > int find(final List list, - final Function converter, - final int from, final int to, final E key) - { - final IntFunction getter = listGetter(list); - return findByIndex(i -> converter.apply(getter.apply(i)).compareTo(key), from, to); - } - - /** - * Binary search supporting search for one type of objects - * using object of another type, given from any object of one type - * a function can get an object of another type - * - * @param array of one type of objects - * @param converter from one type of objects to another - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key a value of another object type - * @return - */ - public static > int find(final T[] array, - final Function converter, - final int from, final int to, final E key) - { - rangeCheck(array.length, from, to); - return findByIndex(i -> converter.apply(array[i]).compareTo(key), from, to); - } - /** - * Binary search supporting search for one type of objects - * using object of another type, given from any object of one type - * a function can get an object of another type - * - * @param list of one type of objects - * @param converter from one type of objects to another - * @param comparator - a comparator for objects of type E - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key a value of another object type - * @return - */ - public static int find(final List list, - final Function converter, - final Comparator comparator, - final int from, final int to, final E key) - { - final IntFunction getter = listGetter(list); - return findByIndex(i -> comparator.compare(converter.apply(getter.apply(i)), key), from, to); - } - - /** - * Binary search supporting search for one type of objects - * using object of another type, given from any object of one type - * a function can get an object of another type - * - * @param array of one type of objects - * @param converter from one type of objects to another - * @param comparator - a comparator for objects of type E - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key a value of another object type - * @return - */ - public static int find(final T[] array, - final Function converter, - final Comparator comparator, - final int from, final int to, final E key) - { - rangeCheck(array.length, from, to); - return findByIndex(i -> comparator.compare(converter.apply(array[i]), key), from, to); - } - - /** - * Binary search supporting search for one type of objects - * using primitive integer, given from any object - * of one type a function can get a primitive integer - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive integer - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive integer key value - * @return - */ - public static int findByInt(final List list, - final ToIntFunction converter, - final int from, final int to, final int key) - { - final IntFunction getter = listGetter(list); - return findByInt(i -> converter.applyAsInt(getter.apply(i)), from, to, key); - } - - /** - * Binary search supporting search for one type of objects - * using primitive integer, given from any object - * of one type a function can get a primitive integer - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive integer - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive integer key value - * @return - */ - public static int findByInt(final T[] array, - final ToIntFunction converter, - final int from, final int to, final int key) - { - rangeCheck(array.length, from, to); - return findByInt(i -> converter.applyAsInt(array[i]), from, to, key); - } - - /** - * Binary search supporting search for one type of objects - * using primitive integer, given from any object - * of one type a function can get a primitive integer - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive integer - * @param comparator - a comparator for primitive integer values - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive integer key value - * @return - */ - public static int findByInt(final List list, - final ToIntFunction converter, - final IntBinaryOperator comparator, - final int from, final int to, final int key) - { - final IntFunction getter = listGetter(list); - return findByIndex(i -> comparator.applyAsInt(converter.applyAsInt(getter.apply(i)), key), from, to); - } - - /** - * Binary search supporting search for one type of objects - * using primitive integer, given from any object - * of one type a function can get a primitive integer - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive integer - * @param comparator - a comparator for primitive integer values - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive integer key value - * @return - */ - public static int findByInt(final T[] array, - final ToIntFunction converter, - final IntBinaryOperator comparator, - final int from, final int to, final int key) - { - rangeCheck(array.length, from, to); - return findByIndex(i -> comparator.applyAsInt(converter.applyAsInt(array[i]), key), from, to); - } - - /** - * Binary search supporting search for one type of objects - * using primitive long, given from any object - * of one type a function can get a primitive long - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive long - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive long key value - * @return - */ - public static int findByLong(final List list, - final ToLongFunction converter, - final int from, final int to, final long key) - { - final IntFunction getter = listGetter(list); - return findByLong(i -> converter.applyAsLong(getter.apply(i)), from, to, key); - } - - /** - * Binary search supporting search for one type of objects - * using primitive long, given from any object - * of one type a function can get a primitive long - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive long - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive long key value - * @return - */ - public static int findByLong(final T[] array, - final ToLongFunction converter, - final int from, final int to, final long key) - { - rangeCheck(array.length, from, to); - return findByLong(i -> converter.applyAsLong(array[i]), from, to, key); - } - - /** - * Binary search supporting search for one type of objects - * using primitive long, given from any object - * of one type a function can get a primitive long - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive long - * @param comparator - a comparator for primitive long values - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive long key value - * @return - */ - public static int findByLong(final List list, - final ToLongFunction converter, - final LongComparator comparator, - final int from, final int to, final long key) - { - final IntFunction getter = listGetter(list); - return findByIndex(i -> comparator.compareAsLong(converter.applyAsLong(getter.apply(i)), key), from, to); - } - - /** - * Binary search supporting search for one type of objects - * using primitive long, given from any object - * of one type a function can get a primitive long - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive long - * @param comparator - a comparator for primitive long values - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive long key value - * @return - */ - public static int findByLong(final T[] array, - final ToLongFunction converter, - final LongComparator comparator, - final int from, final int to, final long key) - { - rangeCheck(array.length, from, to); - return findByIndex(i -> comparator.compareAsLong(converter.applyAsLong(array[i]), key), from, to); - } - - /** - * Binary search supporting search for one type of objects - * using primitive double, given from any object - * of one type a function can get a primitive double - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive double - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive double key value - * @return - */ - public static int findByDouble(final List list, - final ToDoubleFunction converter, - final int from, final int to, final double key) - { - final IntFunction getter = listGetter(list); - return findByDouble(i -> converter.applyAsDouble(getter.apply(i)), from, to, key); - } - - /** - * Binary search supporting search for one type of objects - * using primitive double, given from any object - * of one type a function can get a primitive double - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive double - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive double key value - * @return - */ - public static int findByDouble(final T[] array, - final ToDoubleFunction converter, - final int from, final int to, final double key) - { - rangeCheck(array.length, from, to); - return findByDouble(i -> converter.applyAsDouble(array[i]), from, to, key); - } - - /** - * Binary search supporting search for one type of objects - * using primitive double, given from any object - * of one type a function can get a primitive double - * - * @param list of one type of objects - * @param converter from one type of objects to a primitive double - * @param comparator - a comparator for primitive double values - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive double key value - * @return - */ - public static int findByDouble(final List list, - final ToDoubleFunction converter, - final DoubleComparator comparator, - final int from, final int to, final double key) - { - final IntFunction getter = listGetter(list); - return findByIndex(i -> comparator.compareAsDouble(converter.applyAsDouble(getter.apply(i)), key), from, to); - } - - /** - * Binary search supporting search for one type of objects - * using primitive double, given from any object - * of one type a function can get a primitive double - * - * @param array of one type of objects - * @param converter from one type of objects to a primitive double - * @param comparator - a comparator for primitive double values - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param a primitive double key value - * @return - */ - public static int findByDouble(final T[] array, - final ToDoubleFunction converter, - final DoubleComparator comparator, - final int from, final int to, final double key) - { - rangeCheck(array.length, from, to); - return findByIndex(i -> comparator.compareAsDouble(converter.applyAsDouble(array[i]), key), from, to); - } - - /** - * Blind binary search, presuming there is some sorted structure, - * whose sorting is someway ensured by some key object, using the getter - * who, given an index in the invisible structure, can produce a key - * object someway used to sort it. - * - * @param getter - a function accepting indexes, producing a key object used for sort - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key - a key object - */ - public static > int find(final IntFunction getter, - final int from, final int to, final E key) - { return findByIndex(i -> getter.apply(i).compareTo(key), from, to); } + /** + * Binary search supporting search for one type of objects + * using primitive long, given from any object + * of one type a function can get a primitive long + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive long + * @param a primitive long key value + * @return + */ + public static int findByLong(final List list, + final ToLongFunction converter, + final long key) { + return findByLong(list, converter, 0, list.size(), key); + } - /** - * Blind binary search, presuming there is some sorted structure, - * whose sorting is someway ensured by some key object, using the getter - * who, given an index in the invisible structure, can produce a key - * object someway used to sort it. - * - * @param getter - a function accepting indexes, producing a key object used for sort - * @param comparator - a comparator for objects of type E - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key - a key object - */ - public static int find(final IntFunction getter, - final Comparator comparator, - final int from, final int to, final E key) - { return findByIndex(i -> comparator.compare(getter.apply(i), key), from, to); } - - /** - * Blind binary search, presuming there is some sorted structure, - * whose sorting is someway ensured by primitive integer key, - * using the getter who, given an index in the invisible structure, can produce - * the primitive integer key someway used to sort it. - * - * @param getter - a function accepting indexes, producing a primitive integer used for sort - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key - a primitive integer key - */ - public static int findByInt(final IntUnaryOperator getter, - final int from, final int to, final int key) - { return findByInt(getter, Integer::compare, from, to, key); } - - /** - * Blind binary search, presuming there is some sorted structure, - * whose sorting is someway ensured by primitive integer key, - * using the getter who, given an index in the invisible structure, can produce - * the primitive integer key someway used to sort it. - * - * @param getter - a function accepting indexes, producing a primitive integer used for sort - * @param comparator - a comparator for primitive integers - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key - a primitive integer key - */ - public static int findByInt(final IntUnaryOperator getter, - final IntBinaryOperator comparator, - final int from, final int to, final int key) - { return findByIndex(i -> comparator.applyAsInt(getter.applyAsInt(i), key), from, to); } - - /** - * Blind binary search, presuming there is some sorted structure, - * whose sorting is someway ensured by primitive long key, - * using the getter who, given an index in the invisible structure, can produce - * the primitive long key someway used to sort it. - * - * @param getter - a function accepting indexes, producing a primitive long used for sort - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key - a primitive long key - */ - public static int findByLong(final LongGetter getter, - final int from, final int to, final long key) - { return findByLong(getter, Long::compare, from, to, key); } - - /** - * Blind binary search, presuming there is some sorted structure, - * whose sorting is someway ensured by primitive long key, - * using the getter who, given an index in the invisible structure, can produce - * the primitive long key someway used to sort it. - * - * @param getter - a function accepting indexes, producing a primitive long used for sort - * @param comparator - a comparator for primitive long values - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key - a primitive long key - */ - public static int findByLong(final LongGetter getter, - final LongComparator comparator, - final int from, final int to, final long key) - { return findByIndex(i -> comparator.compareAsLong(getter.getAsLong(i), key), from, to); } - - /** - * Blind binary search, presuming there is some sorted structure, - * whose sorting is someway ensured by primitive double key, - * using the getter who, given an index in the invisible structure, can produce - * the primitive double key someway used to sort it. - * - * @param getter - a function accepting indexes, producing a primitive double used for sort - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key - a primitive double key - */ - public static int findByDouble(final DoubleGetter getter, - final int from, final int to, final double key) - { return findByDouble(getter, Double::compare, from, to, key); } - - /** - * Blind binary search, presuming there is some sorted structure, - * whose sorting is someway ensured by primitive double key, - * using the getter who, given an index in the invisible structure, can produce - * the primitive double key someway used to sort it. - * - * @param getter - a function accepting indexes, producing a primitive double used for sort - * @param comparator - a comparator for primitive double values - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - * @param key - a primitive double key - */ - public static int findByDouble(final DoubleGetter getter, - final DoubleComparator comparator, - final int from, final int to, final double key) - { return findByIndex(i -> comparator.compareAsDouble(getter.getAsDouble(i), key), from, to); } + /** + * Binary search supporting search for one type of objects + * using primitive long, given from any object + * of one type a function can get a primitive long + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive long + * @param a primitive long key value + * @return + */ + public static int findByLong(final T[] array, + final ToLongFunction converter, + final long key) { + return findByLong(array, converter, 0, array.length, key); + } - /** - * Blind binary search applying array elements to matching function until it returns 0 - * @param list of one type of objects - * @param matcher - a matcher returning comparison result based on single list element - **/ - public static int findByMatch(final T[] array, - final ToIntFunction matcher) - { return findByMatch(array, matcher, 0, array.length); } - - /** - * Blind binary search applying List elements to matching function until it returns 0 - * @param list of one type of objects - * @param matcher - a matcher returning comparison result based on single list element - **/ - public static int findByMatch(final List list, - final ToIntFunction matcher) - { return findByMatch(list, matcher, 0, list.size()); } - - /** - * Blind binary search applying array elements to matching function until it returns 0 - * @param list of one type of objects - * @param matcher - a matcher returning comparison result based on single list element - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - **/ - public static int findByMatch(final T[] array, - final ToIntFunction matcher, - final int from, - final int to) - { - rangeCheck(array.length, from, to); - return findByIndex(i -> matcher.applyAsInt(array[i]), from, to); - } - - /** - * Blind binary search applying List elements to matching function until it returns 0 - * @param list of one type of objects - * @param matcher - a matcher returning comparison result based on single list element - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - **/ - public static int findByMatch(final List list, - final ToIntFunction matcher, - final int from, - final int to) - { - final IntFunction getter = listGetter(list); - return findByIndex(i -> matcher.applyAsInt(getter.apply(i)), from, to); + /** + * Binary search supporting search for one type of objects + * using primitive long, given from any object + * of one type a function can get a primitive long + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive long + * @param comparator - a comparator for primitive long values + * @param a primitive long key value + * @return + */ + public static int findByLong(final List list, + final ToLongFunction converter, + final LongComparator comparator, + final long key) { + return findByLong(list, converter, comparator, 0, list.size(), key); + } + + /** + * Binary search supporting search for one type of objects + * using primitive long, given from any object + * of one type a function can get a primitive long + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive long + * @param comparator - a comparator for primitive long values + * @param a primitive long key value + * @return + */ + public static int findByLong(final T[] array, + final ToLongFunction converter, + final LongComparator comparator, + final long key) { + return findByLong(array, converter, comparator, 0, array.length, key); + } + + /** + * Binary search supporting search for one type of objects + * using primitive double, given from any object + * of one type a function can get a primitive double + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive double + * @param a primitive double key value + * @return + */ + public static int findByDouble(final List list, + final ToDoubleFunction converter, + final double key) { + return findByDouble(list, converter, 0, list.size(), key); + } + + /** + * Binary search supporting search for one type of objects + * using primitive double, given from any object + * of one type a function can get a primitive double + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive double + * @param a primitive double key value + * @return + */ + public static int findByDouble(final T[] array, + final ToDoubleFunction converter, + final double key) { + return findByDouble(array, converter, 0, array.length, key); + } + + /** + * Binary search supporting search for one type of objects + * using primitive double, given from any object + * of one type a function can get a primitive double + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive double + * @param comparator - a comparator for primitive double values + * @param a primitive double key value + * @return + */ + public static int findByDouble(final List list, + final ToDoubleFunction converter, + final DoubleComparator comparator, + final double key) { + return findByDouble(list, converter, comparator, 0, list.size(), key); + } + + /** + * Binary search supporting search for one type of objects + * using primitive double, given from any object + * of one type a function can get a primitive double + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive double + * @param comparator - a comparator for primitive double values + * @param a primitive double key value + * @return + */ + public static int findByDouble(final T[] array, + final ToDoubleFunction converter, + final DoubleComparator comparator, + final double key) { + return findByDouble(array, converter, comparator, 0, array.length, key); + } + + /** + * Binary search supporting search for one type of objects + * using object of another type, given from any object of one type + * a function can get an object of another type + * + * @param list of one type of objects + * @param converter from one type of objects to another + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key a value of another object type + * @return + */ + public static > int find(final List list, + final Function converter, + final int from, final int to, final E key) { + final IntFunction getter = listGetter(list); + return findByIndex(i -> converter.apply(getter.apply(i)).compareTo(key), from, to); + } + + /** + * Binary search supporting search for one type of objects + * using object of another type, given from any object of one type + * a function can get an object of another type + * + * @param array of one type of objects + * @param converter from one type of objects to another + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key a value of another object type + * @return + */ + public static > int find(final T[] array, + final Function converter, + final int from, final int to, final E key) { + rangeCheck(array.length, from, to); + return findByIndex(i -> converter.apply(array[i]).compareTo(key), from, to); + } + + /** + * Binary search supporting search for one type of objects + * using object of another type, given from any object of one type + * a function can get an object of another type + * + * @param list of one type of objects + * @param converter from one type of objects to another + * @param comparator - a comparator for objects of type E + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key a value of another object type + * @return + */ + public static int find(final List list, + final Function converter, + final Comparator comparator, + final int from, final int to, final E key) { + final IntFunction getter = listGetter(list); + return findByIndex(i -> comparator.compare(converter.apply(getter.apply(i)), key), from, to); + } + + /** + * Binary search supporting search for one type of objects + * using object of another type, given from any object of one type + * a function can get an object of another type + * + * @param array of one type of objects + * @param converter from one type of objects to another + * @param comparator - a comparator for objects of type E + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key a value of another object type + * @return + */ + public static int find(final T[] array, + final Function converter, + final Comparator comparator, + final int from, final int to, final E key) { + rangeCheck(array.length, from, to); + return findByIndex(i -> comparator.compare(converter.apply(array[i]), key), from, to); + } + + /** + * Binary search supporting search for one type of objects + * using primitive integer, given from any object + * of one type a function can get a primitive integer + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive integer + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive integer key value + * @return + */ + public static int findByInt(final List list, + final ToIntFunction converter, + final int from, final int to, final int key) { + final IntFunction getter = listGetter(list); + return findByInt(i -> converter.applyAsInt(getter.apply(i)), from, to, key); + } + + /** + * Binary search supporting search for one type of objects + * using primitive integer, given from any object + * of one type a function can get a primitive integer + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive integer + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive integer key value + * @return + */ + public static int findByInt(final T[] array, + final ToIntFunction converter, + final int from, final int to, final int key) { + rangeCheck(array.length, from, to); + return findByInt(i -> converter.applyAsInt(array[i]), from, to, key); + } + + /** + * Binary search supporting search for one type of objects + * using primitive integer, given from any object + * of one type a function can get a primitive integer + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive integer + * @param comparator - a comparator for primitive integer values + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive integer key value + * @return + */ + public static int findByInt(final List list, + final ToIntFunction converter, + final IntBinaryOperator comparator, + final int from, final int to, final int key) { + final IntFunction getter = listGetter(list); + return findByIndex(i -> comparator.applyAsInt(converter.applyAsInt(getter.apply(i)), key), from, to); + } + + /** + * Binary search supporting search for one type of objects + * using primitive integer, given from any object + * of one type a function can get a primitive integer + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive integer + * @param comparator - a comparator for primitive integer values + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive integer key value + * @return + */ + public static int findByInt(final T[] array, + final ToIntFunction converter, + final IntBinaryOperator comparator, + final int from, final int to, final int key) { + rangeCheck(array.length, from, to); + return findByIndex(i -> comparator.applyAsInt(converter.applyAsInt(array[i]), key), from, to); + } + + /** + * Binary search supporting search for one type of objects + * using primitive long, given from any object + * of one type a function can get a primitive long + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive long + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive long key value + * @return + */ + public static int findByLong(final List list, + final ToLongFunction converter, + final int from, final int to, final long key) { + final IntFunction getter = listGetter(list); + return findByLong(i -> converter.applyAsLong(getter.apply(i)), from, to, key); + } + + /** + * Binary search supporting search for one type of objects + * using primitive long, given from any object + * of one type a function can get a primitive long + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive long + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive long key value + * @return + */ + public static int findByLong(final T[] array, + final ToLongFunction converter, + final int from, final int to, final long key) { + rangeCheck(array.length, from, to); + return findByLong(i -> converter.applyAsLong(array[i]), from, to, key); + } + + /** + * Binary search supporting search for one type of objects + * using primitive long, given from any object + * of one type a function can get a primitive long + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive long + * @param comparator - a comparator for primitive long values + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive long key value + * @return + */ + public static int findByLong(final List list, + final ToLongFunction converter, + final LongComparator comparator, + final int from, final int to, final long key) { + final IntFunction getter = listGetter(list); + return findByIndex(i -> comparator.compareAsLong(converter.applyAsLong(getter.apply(i)), key), from, to); + } + + /** + * Binary search supporting search for one type of objects + * using primitive long, given from any object + * of one type a function can get a primitive long + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive long + * @param comparator - a comparator for primitive long values + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive long key value + * @return + */ + public static int findByLong(final T[] array, + final ToLongFunction converter, + final LongComparator comparator, + final int from, final int to, final long key) { + rangeCheck(array.length, from, to); + return findByIndex(i -> comparator.compareAsLong(converter.applyAsLong(array[i]), key), from, to); + } + + /** + * Binary search supporting search for one type of objects + * using primitive double, given from any object + * of one type a function can get a primitive double + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive double + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive double key value + * @return + */ + public static int findByDouble(final List list, + final ToDoubleFunction converter, + final int from, final int to, final double key) { + final IntFunction getter = listGetter(list); + return findByDouble(i -> converter.applyAsDouble(getter.apply(i)), from, to, key); + } + + /** + * Binary search supporting search for one type of objects + * using primitive double, given from any object + * of one type a function can get a primitive double + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive double + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive double key value + * @return + */ + public static int findByDouble(final T[] array, + final ToDoubleFunction converter, + final int from, final int to, final double key) { + rangeCheck(array.length, from, to); + return findByDouble(i -> converter.applyAsDouble(array[i]), from, to, key); + } + + /** + * Binary search supporting search for one type of objects + * using primitive double, given from any object + * of one type a function can get a primitive double + * + * @param list of one type of objects + * @param converter from one type of objects to a primitive double + * @param comparator - a comparator for primitive double values + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive double key value + * @return + */ + public static int findByDouble(final List list, + final ToDoubleFunction converter, + final DoubleComparator comparator, + final int from, final int to, final double key) { + final IntFunction getter = listGetter(list); + return findByIndex(i -> comparator.compareAsDouble(converter.applyAsDouble(getter.apply(i)), key), from, to); + } + + /** + * Binary search supporting search for one type of objects + * using primitive double, given from any object + * of one type a function can get a primitive double + * + * @param array of one type of objects + * @param converter from one type of objects to a primitive double + * @param comparator - a comparator for primitive double values + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param a primitive double key value + * @return + */ + public static int findByDouble(final T[] array, + final ToDoubleFunction converter, + final DoubleComparator comparator, + final int from, final int to, final double key) { + rangeCheck(array.length, from, to); + return findByIndex(i -> comparator.compareAsDouble(converter.applyAsDouble(array[i]), key), from, to); + } + + /** + * Blind binary search, presuming there is some sorted structure, + * whose sorting is someway ensured by some key object, using the getter + * who, given an index in the invisible structure, can produce a key + * object someway used to sort it. + * + * @param getter - a function accepting indexes, producing a key object used for sort + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key - a key object + */ + public static > int find(final IntFunction getter, + final int from, final int to, final E key) { + return findByIndex(i -> getter.apply(i).compareTo(key), from, to); + } + + /** + * Blind binary search, presuming there is some sorted structure, + * whose sorting is someway ensured by some key object, using the getter + * who, given an index in the invisible structure, can produce a key + * object someway used to sort it. + * + * @param getter - a function accepting indexes, producing a key object used for sort + * @param comparator - a comparator for objects of type E + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key - a key object + */ + public static int find(final IntFunction getter, + final Comparator comparator, + final int from, final int to, final E key) { + return findByIndex(i -> comparator.compare(getter.apply(i), key), from, to); + } + + /** + * Blind binary search, presuming there is some sorted structure, + * whose sorting is someway ensured by primitive integer key, + * using the getter who, given an index in the invisible structure, can produce + * the primitive integer key someway used to sort it. + * + * @param getter - a function accepting indexes, producing a primitive integer used for sort + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key - a primitive integer key + */ + public static int findByInt(final IntUnaryOperator getter, + final int from, final int to, final int key) { + return findByInt(getter, Integer::compare, from, to, key); + } + + /** + * Blind binary search, presuming there is some sorted structure, + * whose sorting is someway ensured by primitive integer key, + * using the getter who, given an index in the invisible structure, can produce + * the primitive integer key someway used to sort it. + * + * @param getter - a function accepting indexes, producing a primitive integer used for sort + * @param comparator - a comparator for primitive integers + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key - a primitive integer key + */ + public static int findByInt(final IntUnaryOperator getter, + final IntBinaryOperator comparator, + final int from, final int to, final int key) { + return findByIndex(i -> comparator.applyAsInt(getter.applyAsInt(i), key), from, to); + } + + /** + * Blind binary search, presuming there is some sorted structure, + * whose sorting is someway ensured by primitive long key, + * using the getter who, given an index in the invisible structure, can produce + * the primitive long key someway used to sort it. + * + * @param getter - a function accepting indexes, producing a primitive long used for sort + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key - a primitive long key + */ + public static int findByLong(final LongGetter getter, + final int from, final int to, final long key) { + return findByLong(getter, Long::compare, from, to, key); + } + + /** + * Blind binary search, presuming there is some sorted structure, + * whose sorting is someway ensured by primitive long key, + * using the getter who, given an index in the invisible structure, can produce + * the primitive long key someway used to sort it. + * + * @param getter - a function accepting indexes, producing a primitive long used for sort + * @param comparator - a comparator for primitive long values + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key - a primitive long key + */ + public static int findByLong(final LongGetter getter, + final LongComparator comparator, + final int from, final int to, final long key) { + return findByIndex(i -> comparator.compareAsLong(getter.getAsLong(i), key), from, to); + } + + /** + * Blind binary search, presuming there is some sorted structure, + * whose sorting is someway ensured by primitive double key, + * using the getter who, given an index in the invisible structure, can produce + * the primitive double key someway used to sort it. + * + * @param getter - a function accepting indexes, producing a primitive double used for sort + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key - a primitive double key + */ + public static int findByDouble(final DoubleGetter getter, + final int from, final int to, final double key) { + return findByDouble(getter, Double::compare, from, to, key); + } + + /** + * Blind binary search, presuming there is some sorted structure, + * whose sorting is someway ensured by primitive double key, + * using the getter who, given an index in the invisible structure, can produce + * the primitive double key someway used to sort it. + * + * @param getter - a function accepting indexes, producing a primitive double used for sort + * @param comparator - a comparator for primitive double values + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + * @param key - a primitive double key + */ + public static int findByDouble(final DoubleGetter getter, + final DoubleComparator comparator, + final int from, final int to, final double key) { + return findByIndex(i -> comparator.compareAsDouble(getter.getAsDouble(i), key), from, to); + } + + /** + * Blind binary search applying array elements to matching function until it returns 0 + * @param list of one type of objects + * @param matcher - a matcher returning comparison result based on single list element + **/ + public static int findByMatch(final T[] array, + final ToIntFunction matcher) { + return findByMatch(array, matcher, 0, array.length); + } + + /** + * Blind binary search applying List elements to matching function until it returns 0 + * @param list of one type of objects + * @param matcher - a matcher returning comparison result based on single list element + **/ + public static int findByMatch(final List list, + final ToIntFunction matcher) { + return findByMatch(list, matcher, 0, list.size()); + } + + /** + * Blind binary search applying array elements to matching function until it returns 0 + * @param list of one type of objects + * @param matcher - a matcher returning comparison result based on single list element + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + **/ + public static int findByMatch(final T[] array, + final ToIntFunction matcher, + final int from, + final int to) { + rangeCheck(array.length, from, to); + return findByIndex(i -> matcher.applyAsInt(array[i]), from, to); + } + + /** + * Blind binary search applying List elements to matching function until it returns 0 + * @param list of one type of objects + * @param matcher - a matcher returning comparison result based on single list element + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + **/ + public static int findByMatch(final List list, + final ToIntFunction matcher, + final int from, + final int to) { + final IntFunction getter = listGetter(list); + return findByIndex(i -> matcher.applyAsInt(getter.apply(i)), from, to); + } + + /** + * Blind binary search applying index to comparison function until it returns 0 + * @param comparator - index-comparing function + * @param from - an index (inclusive) from which to start search + * @param to - an index (exclusive) from which to start search + **/ + public static int findByIndex(final IntUnaryOperator comparator, final int from, final int to) { + int low = from; + int high = to - 1; + + while (low <= high) { + int mid = (low + high) >>> 1; + int cmp = comparator.applyAsInt(mid); + + if (cmp < 0) { + low = mid + 1; + } else if (cmp > 0) { + high = mid - 1; + } else { + return mid; // key found + } } - - /** - * Blind binary search applying index to comparison function until it returns 0 - * @param comparator - index-comparing function - * @param from - an index (inclusive) from which to start search - * @param to - an index (exclusive) from which to start search - **/ - public static int findByIndex(final IntUnaryOperator comparator, final int from, final int to) { - int low = from; - int high = to - 1; - - while (low <= high) { - int mid = (low + high) >>> 1; - int cmp = comparator.applyAsInt(mid); - - if (cmp < 0) - low = mid + 1; - else if (cmp > 0) - high = mid - 1; - else - return mid; // key found - } - return -(low + 1); // key not found + return -(low + 1); // key not found + } + + /** + * A copy of Arrays.rangeCheck private method from JDK + */ + private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) { + if (fromIndex > toIndex) { + throw new IllegalArgumentException( + "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } - - /** - * A copy of Arrays.rangeCheck private method from JDK - */ - private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) { - if (fromIndex > toIndex) - throw new IllegalArgumentException( - "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); - if (fromIndex < 0) - throw new ArrayIndexOutOfBoundsException(fromIndex); - if (toIndex > arrayLength) - throw new ArrayIndexOutOfBoundsException(toIndex); + if (fromIndex < 0) { + throw new ArrayIndexOutOfBoundsException(fromIndex); } - - /** - * A copy of Collections.get private method from JDK - */ - private static T get(ListIterator i, int index) { - T obj = null; - int pos = i.nextIndex(); - if (pos <= index) - do - obj = i.next(); - while (pos++ < index); - else - do - obj = i.previous(); - while (--pos > index); - return obj; + if (toIndex > arrayLength) { + throw new ArrayIndexOutOfBoundsException(toIndex); } + } - private static > IntFunction listGetter(final L list) { - if (list instanceof RandomAccess) - return ((List) list)::get; - - final ListIterator it = list.listIterator(); - return i -> get(it, i); + /** + * A copy of Collections.get private method from JDK + */ + private static T get(ListIterator i, int index) { + T obj = null; + int pos = i.nextIndex(); + if (pos <= index) { + do { + obj = i.next(); + } while (pos++ < index); + } else { + do { + obj = i.previous(); + } while (--pos > index); } + return obj; + } - @FunctionalInterface - public interface LongComparator { - int compareAsLong(long f1, long f2); + private static > IntFunction listGetter(final L list) { + if (list instanceof RandomAccess) { + return ((List) list)::get; } - @FunctionalInterface - public interface DoubleComparator { - int compareAsDouble(double f1, double f2); - } + final ListIterator it = list.listIterator(); + return i -> get(it, i); + } - @FunctionalInterface - public interface LongGetter { - long getAsLong(int i); - } + @FunctionalInterface + public interface LongComparator { - @FunctionalInterface - public interface DoubleGetter { - double getAsDouble(int i); - } -} \ No newline at end of file + int compareAsLong(long f1, long f2); + } + + @FunctionalInterface + public interface DoubleComparator { + + int compareAsDouble(double f1, double f2); + } + + @FunctionalInterface + public interface LongGetter { + + long getAsLong(int i); + } + + @FunctionalInterface + public interface DoubleGetter { + + double getAsDouble(int i); + } +} diff --git a/src/utils/C2JUtils.java b/src/utils/C2JUtils.java index 8509c295..f5fde187 100644 --- a/src/utils/C2JUtils.java +++ b/src/utils/C2JUtils.java @@ -8,9 +8,15 @@ import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import p.Resettable; import w.InputStreamSugar; @@ -20,9 +26,10 @@ * * @author Maes */ - public final class C2JUtils { + private static final Logger LOGGER = Loggers.getLogger(C2JUtils.class.getName()); + public static char[] strcpy(char[] s1, final char[] s2) { System.arraycopy(s2, 0, s1, 0, Math.min(s1.length, s2.length)); return s1; @@ -49,7 +56,6 @@ public static char[] strcpy(char[] s1, String s2) { return s1; } - /** Return a byte[] array from the string's chars, * ANDed to the lowest 8 bits. * @@ -79,7 +85,6 @@ public static byte[] toByteArray(String str) { * @param key * @return */ - public static int indexOf(Object[] array, Object key) { for (int i = 0; i < array.length; i++) { if (array[i] == key) { @@ -99,7 +104,6 @@ public static int indexOf(Object[] array, Object key) { * @param s2 * @return */ - public static boolean strcmp(char[] s1, final char[] s2) { boolean match = true; for (int i = 0; i < Math.min(s1.length, s2.length); i++) { @@ -122,13 +126,15 @@ public static boolean strcmp(char[] s1, String s2) { * @return */ public static int strlen(char[] s1) { - if (s1 == null) + if (s1 == null) { return 0; + } int len = 0; while (s1[len++] > 0) { - if (len >= s1.length) + if (len >= s1.length) { break; + } } return len - 1; @@ -141,13 +147,15 @@ public static int strlen(char[] s1) { * @return */ public static String nullTerminatedString(char[] s) { - if (s == null) + if (s == null) { return ""; + } int len = 0; while (s[len++] > 0) { - if (len >= s.length) + if (len >= s.length) { break; + } } return new String(s, 0, len - 1); @@ -163,16 +171,13 @@ public static String nullTerminatedString(char[] s) { * @throws Exception * @throws */ - public static void initArrayOfObjects(T[] os, Class c) { try { for (int i = 0; i < os.length; i++) { - os[i] = c.newInstance(); + os[i] = c.getDeclaredConstructor().newInstance(); } - } catch (IllegalAccessException | InstantiationException e) { - e.printStackTrace(); - System.err.println("Failure to allocate " + os.length - + " objects of class" + c.getName() + "!"); + } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { + LOGGER.log(Level.SEVERE, String.format("Failure to allocate %d objects of class %s", os.length, c.getName()), e); System.exit(-1); } } @@ -192,13 +197,10 @@ public static void initArrayOfObjects(T[] os) { Class c = (Class) os.getClass().getComponentType(); try { for (int i = 0; i < os.length; i++) { - os[i] = c.newInstance(); + os[i] = c.getDeclaredConstructor().newInstance(); } - } catch (IllegalAccessException | InstantiationException e) { - e.printStackTrace(); - System.err.println("Failure to allocate " + os.length - + " objects of class " + c.getName() + "!"); - + } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { + LOGGER.log(Level.SEVERE, String.format("Failure to allocate %d objects of class %s", os.length, c.getName()), e); System.exit(-1); } } @@ -225,21 +227,20 @@ public static void initArrayOfObjects(T[] os) { public static T[] createArrayOfObjects(Class c, int num) { T[] os; - os=getNewArray(c,num); + os = getNewArray(c, num); try { for (int i = 0; i < os.length; i++) { - os[i] = c.newInstance(); + os[i] = c.getDeclaredConstructor().newInstance(); } - } catch (IllegalAccessException | InstantiationException e) { - e.printStackTrace(); - System.err.println("Failure to instantiate " + os.length + " objects of class " + c.getName() + "!"); + } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { + LOGGER.log(Level.SEVERE, String.format("Failure to instantiate %d objects of class %s", os.length, c.getName()), e); System.exit(-1); } return os; } - + /** * Uses reflection to automatically create and initialize an array of * objects of the specified class. Does not require casting on "reception". @@ -253,30 +254,26 @@ public static T[] createArrayOfObjects(Class c, int num) { * @return * @return */ - @SuppressWarnings("unchecked") public static T[] createArrayOfObjects(T instance, int num) { T[] os; - - Class c=(Class) instance.getClass(); - os=getNewArray(c,num); + Class c = (Class) instance.getClass(); + + os = getNewArray(c, num); try { for (int i = 0; i < os.length; i++) { - os[i] = c.newInstance(); + os[i] = c.getDeclaredConstructor().newInstance(); } - } catch (IllegalAccessException | InstantiationException e) { - e.printStackTrace(); - System.err.println("Failure to instantiate " + os.length - + " objects of class " + c.getName() + "!"); + } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { + LOGGER.log(Level.SEVERE, String.format("Failure to instantiate %d objects of class %s", os.length, c.getName()), e); System.exit(-1); } return os; } - /** * Automatically "initializes" arrays of objects with their default * constuctor. It's better than doing it by hand, IMO. If you have a better @@ -288,63 +285,61 @@ public static T[] createArrayOfObjects(T instance, int num) { * @throws Exception * @throws */ - public static void initArrayOfObjects(T[] os, int startpos, int endpos) { @SuppressWarnings("unchecked") - Class c = (Class) os.getClass().getComponentType(); + Class c = (Class) os.getClass().getComponentType(); try { for (int i = startpos; i < endpos; i++) { - os[i] = c.newInstance(); + os[i] = c.getDeclaredConstructor().newInstance(); } - } catch (IllegalAccessException | InstantiationException e) { - e.printStackTrace(); - System.err.println("Failure to allocate " + os.length - + " objects of class " + c.getName() + "!"); - + } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { + LOGGER.log(Level.SEVERE, String.format("Failure to allocate %d objects of class %s", os.length, c.getName()), e); System.exit(-1); } } /** This method gets eventually inlined, becoming very fast */ - public static int toUnsignedByte(byte b) { return (0x000000FF & b); } // Optimized array-fill methods designed to operate like C's memset. - public static void memset(boolean[] array, boolean value, int len) { - if (len > 0) + if (len > 0) { array[0] = value; + } for (int i = 1; i < len; i += i) { System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i); } } public static void memset(byte[] array, byte value, int len) { - if (len > 0) + if (len > 0) { array[0] = value; + } for (int i = 1; i < len; i += i) { System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i); } } public static void memset(char[] array, char value, int len) { - if (len > 0) + if (len > 0) { array[0] = value; + } for (int i = 1; i < len; i += i) { System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i); } } public static void memset(int[] array, int value, int len) { - if (len > 0) + if (len > 0) { array[0] = value; + } for (int i = 1; i < len; i += i) { System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i); } } - + public static void memset(short[] array, short value, int len) { if (len > 0) { array[0] = value; @@ -374,25 +369,25 @@ public static void memcpy(Object dest, Object src, int length) { System.arraycopy(src, 0, dest, 0, length); } - public static boolean testReadAccess(String URI) { + public static boolean testReadAccess(String uri) { InputStream in; // This is bullshit. - if (URI == null) { + if (uri == null) { return false; } - if (URI.length() == 0) { + if (uri.length() == 0) { return false; } try { - in = new FileInputStream(URI); + in = new FileInputStream(uri); } catch (FileNotFoundException e) { // Not a file... URL u; try { - u = new URL(URI); - } catch (MalformedURLException e1) { + u = new URI(uri).toURL(); + } catch (URISyntaxException | MalformedURLException | IllegalArgumentException e1) { return false; } try { @@ -415,26 +410,26 @@ public static boolean testReadAccess(String URI) { return true; } - - public static boolean testWriteAccess(String URI) { + + public static boolean testWriteAccess(String uri) { OutputStream out; // This is bullshit. - if (URI == null) { + if (uri == null) { return false; } - if (URI.length() == 0) { + if (uri.length() == 0) { return false; } try { - out = new FileOutputStream(URI); + out = new FileOutputStream(uri); } catch (FileNotFoundException e) { // Not a file... URL u; try { - u = new URL(URI); - } catch (MalformedURLException e1) { + u = new URI(uri).toURL(); + } catch (URISyntaxException | MalformedURLException | IllegalArgumentException e1) { return false; } try { @@ -468,7 +463,7 @@ public static boolean testWriteAccess(String URI) { public static boolean flags(int flags, int arg) { return ((flags & arg) != 0); } - + public static boolean flags(long flags, long arg) { return ((flags & arg) != 0); } @@ -535,15 +530,15 @@ public static void resetAll(final Resettable[] r) { * @param c * @return */ - public static String unquote(String s, char c) { int firstq = s.indexOf(c); int lastq = s.lastIndexOf(c); // Indexes valid? - if (isQuoted(s,c)) - return s.substring(firstq + 1, lastq); - + if (isQuoted(s, c)) { + return s.substring(firstq + 1, lastq); + } + return null; } @@ -551,25 +546,26 @@ public static boolean isQuoted(String s, char c) { int q1 = s.indexOf(c); int q2 = s.lastIndexOf(c); - char c1,c2; - + char c1, c2; + // Indexes valid? if (q1 != -1 && q2 != -1) { if (q1 < q2) { - c1=s.charAt(q1); - c2=s.charAt(q2); - return (c1==c2); + c1 = s.charAt(q1); + c2 = s.charAt(q2); + return (c1 == c2); } } - + return false; } - + public static String unquoteIfQuoted(String s, char c) { String tmp = unquote(s, c); - if (tmp != null) + if (tmp != null) { return tmp; + } return s; } @@ -579,22 +575,22 @@ public static String unquoteIfQuoted(String s, char c) { * @param o */ public static int pointer(Object o) { - if (o == null) + if (o == null) { return 0; - else + } else { return o.hashCode(); + } } - public static boolean checkForExtension(String filename, String ext) { - + // Null filenames satisfy null extensions. if ((filename == null || filename.isEmpty()) && (ext == null || ext.isEmpty())) { return true; } else if (filename == null) { // avoid NPE - Good Sign 2017/05/07 filename = ""; } - + String separator = System.getProperty("file.separator"); // Remove the path upto the filename. @@ -609,10 +605,12 @@ public static boolean checkForExtension(String filename, String ext) { int pos = filename.lastIndexOf('.'); if (pos >= 0 && pos <= filename.length() - 2) { // Extension present - + // Null comparator on valid extension - if (ext == null || ext.isEmpty()) return false; - + if (ext == null || ext.isEmpty()) { + return false; + } + realext = filename.substring(pos + 1); return realext.compareToIgnoreCase(ext) == 0; } else if (ext == null || ext.isEmpty()) { // No extension, and null/empty comparator @@ -621,15 +619,14 @@ public static boolean checkForExtension(String filename, String ext) { // No extension, and non-null/nonempty comparator. return false; - } - + } + /** Return the filename without extension, and stripped * of the path. * * @param s * @return */ - public static String removeExtension(String s) { String separator = System.getProperty("file.separator"); @@ -652,7 +649,6 @@ public static String removeExtension(String s) { return filename.substring(0, extensionIndex); } - /** * This method is supposed to return the "name" part of a filename. It was * intended to return length-limited (max 8 chars) strings to use as lump @@ -665,42 +661,49 @@ public static String removeExtension(String s) { * @param whole keep extension if set to true * @return */ - public static String extractFileBase(String path, int limit, boolean whole) { - - if (path==null) return path; - + + if (path == null) { + return path; + } + int src = path.length() - 1; String separator = System.getProperty("file.separator"); - src = path.lastIndexOf(separator)+1; + src = path.lastIndexOf(separator) + 1; if (src < 0) // No separator + { src = 0; + } int len = path.lastIndexOf('.'); - if (whole || len<0 ) len=path.length()-src; // No extension. - else len-= src; + if (whole || len < 0) { + len = path.length() - src; // No extension. + } else { + len -= src; + } // copy UP to the specific number of characters, or all - if (limit > 0) len = Math.min(limit, len); - + if (limit > 0) { + len = Math.min(limit, len); + } + return path.substring(src, src + len); } - /** Maes: File intead of "inthandle" */ - + /** Maes: File instead of "inthandle" */ public static long filelength(File handle) { try { return handle.length(); } catch (Exception e) { - System.err.println("Error fstating"); + LOGGER.log(Level.SEVERE, "Error fstating", e); return -1; } } - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public static T[] resize(T[] oldarray, int newsize) { if (oldarray[0] != null) { return resize(oldarray[0], oldarray, newsize); @@ -708,24 +711,23 @@ public static T[] resize(T[] oldarray, int newsize) { T cls; try { - cls = (T) oldarray.getClass().getComponentType().newInstance(); + cls = (T) oldarray.getClass().getComponentType().getDeclaredConstructor().newInstance(); return resize(cls, oldarray, newsize); - } catch (IllegalAccessException | InstantiationException e) { - System.err.println("Cannot autodetect type in resizeArray.\n"); + } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { + LOGGER.log(Level.SEVERE, "Cannot autodetect type in resizeArray.", e); return null; } } - - /** Generic array resizing method. Calls Arrays.copyOf but then also - * uses initArrayOfObject for the "abundant" elements. - * - * @param - * @param instance - * @param oldarray - * @param newsize - * @return - */ - + + /** Generic array resizing method. Calls Arrays.copyOf but then also + * uses initArrayOfObject for the "abundant" elements. + * + * @param + * @param instance + * @param oldarray + * @param newsize + * @return + */ public static T[] resize(T instance, T[] oldarray, int newsize) { // Hmm... nope. if (newsize <= oldarray.length) { @@ -737,93 +739,88 @@ public static T[] resize(T instance, T[] oldarray, int newsize) { // Init the null portions as well C2JUtils.initArrayOfObjects(tmp, oldarray.length, tmp.length); - System.out.printf("Old array of type %s resized. New capacity: %d\n", instance.getClass(), newsize); + LOGGER.log(Level.INFO, String.format("Old array of type %s resized. New capacity: %d", instance.getClass(), newsize)); return tmp; } - - /** Resize an array without autoinitialization. Same as Arrays.copyOf(..), just - * prints a message. - * - * @param - * @param oldarray - * @param newsize - * @return - */ - - public static T[] resizeNoAutoInit(T[] oldarray, int newsize) { - // For non-autoinit types, this is enough. - T[] tmp = Arrays.copyOf(oldarray, newsize); - - System.out.printf("Old array of type %s resized without auto-init. New capacity: %d\n", - tmp.getClass().getComponentType(), newsize); - - return tmp; - } - - @SuppressWarnings("unchecked") + + /** Resize an array without autoinitialization. Same as Arrays.copyOf(..), just + * prints a message. + * + * @param + * @param oldarray + * @param newsize + * @return + */ + public static T[] resizeNoAutoInit(T[] oldarray, int newsize) { + // For non-autoinit types, this is enough. + T[] tmp = Arrays.copyOf(oldarray, newsize); + + LOGGER.log(Level.INFO, String.format("Old array of type %s resized without auto-init. New capacity: %d", + tmp.getClass().getComponentType(), newsize)); + + return tmp; + } + + @SuppressWarnings("unchecked") public static T[] getNewArray(T instance, int size) { Class c = (Class) instance.getClass(); try { return (T[]) Array.newInstance(c, size); } catch (NegativeArraySizeException e) { - e.printStackTrace(); - System.err.println("Failure to allocate " + size - + " objects of class " + c.getName() + "!"); + LOGGER.log(Level.SEVERE, String.format("Failure to allocate %d objects of class %s", size, c.getName()), e); System.exit(-1); } return null; } - - public final static T[] getNewArray(int size,T instance){ - @SuppressWarnings("unchecked") - Class c=(Class) instance.getClass(); - return getNewArray(c,size); - } - - @SuppressWarnings("unchecked") - public final static T[] getNewArray(Class c,int size){ + + public final static T[] getNewArray(int size, T instance) { + @SuppressWarnings("unchecked") + Class c = (Class) instance.getClass(); + return getNewArray(c, size); + } + + @SuppressWarnings("unchecked") + public final static T[] getNewArray(Class c, int size) { try { return (T[]) Array.newInstance(c, size); } catch (NegativeArraySizeException e) { - e.printStackTrace(); - System.err.println("Failure to allocate " + size - + " objects of class " + c.getName() + "!"); + LOGGER.log(Level.SEVERE, String.format("Failure to allocate %d objects of class %s", size, c.getName()), e); System.exit(-1); } - + return null; - } + } /** * Try to guess whether a URI represents a local file, a network any of the * above but zipped. Returns * - * @param URI + * @param uri * @return an int with flags set according to InputStreamSugar */ - public static int guessResourceType(String URI) { + public static int guessResourceType(String uri) { int result = 0; InputStream in; // This is bullshit. - if (URI == null || URI.length() == 0) { + if (uri == null || uri.length() == 0) { return InputStreamSugar.BAD_URI; } try { - in = new FileInputStream(new File(URI)); + in = new FileInputStream(new File(uri)); // It's a file result |= InputStreamSugar.FILE; } catch (FileNotFoundException e) { // Not a file... URL u; try { - u = new URL(URI); - } catch (MalformedURLException e1) { + u = new URI(uri).toURL(); + } catch (URISyntaxException | MalformedURLException | IllegalArgumentException e1) { return InputStreamSugar.BAD_URI; } try { @@ -839,7 +836,7 @@ public static int guessResourceType(String URI) { // TODO: add proper validation, and maybe MIME type checking // for network streams, for cases that we can't really // tell from extension alone. - if (checkForExtension(URI, "zip")) { + if (checkForExtension(uri, "zip")) { result |= InputStreamSugar.ZIP_FILE; } @@ -854,5 +851,6 @@ public static int guessResourceType(String URI) { return result; } - private C2JUtils() {} + private C2JUtils() { + } } diff --git a/src/utils/GenericCopy.java b/src/utils/GenericCopy.java index 92059a4a..67a11c68 100644 --- a/src/utils/GenericCopy.java +++ b/src/utils/GenericCopy.java @@ -21,6 +21,7 @@ import java.util.function.Supplier; public class GenericCopy { + private static final boolean[] BOOL_0 = {false}; private static final byte[] BYTE_0 = {0}; private static final short[] SHORT_0 = {0}; @@ -29,14 +30,14 @@ public class GenericCopy { private static final float[] FLOAT_0 = {0}; private static final long[] LONG_0 = {0}; private static final double[] DOUBLE_0 = {0}; - + public static void memset(long[] array, int start, int length, long... value) { if (length > 0) { if (value.length == 0) { value = LONG_0; } System.arraycopy(value, 0, array, start, value.length); - + for (int i = value.length; i < length; i += i) { System.arraycopy(array, start, array, start + i, ((length - i) < i) ? (length - i) : i); } @@ -49,7 +50,7 @@ public static void memset(int[] array, int start, int length, int... value) { value = INT_0; } System.arraycopy(value, 0, array, start, value.length); - + for (int i = value.length; i < length; i += i) { System.arraycopy(array, start, array, start + i, ((length - i) < i) ? (length - i) : i); } @@ -62,7 +63,7 @@ public static void memset(short[] array, int start, int length, short... value) value = SHORT_0; } System.arraycopy(value, 0, array, start, value.length); - + for (int i = value.length; i < length; i += i) { System.arraycopy(array, start, array, start + i, ((length - i) < i) ? (length - i) : i); } @@ -75,7 +76,7 @@ public static void memset(char[] array, int start, int length, char... value) { value = CHAR_0; } System.arraycopy(value, 0, array, start, value.length); - + for (int i = value.length; i < length; i += i) { System.arraycopy(array, start, array, start + i, ((length - i) < i) ? (length - i) : i); } @@ -88,7 +89,7 @@ public static void memset(byte[] array, int start, int length, byte... value) { value = BYTE_0; } System.arraycopy(value, 0, array, start, value.length); - + for (int i = value.length; i < length; i += i) { System.arraycopy(array, start, array, start + i, ((length - i) < i) ? (length - i) : i); } @@ -101,7 +102,7 @@ public static void memset(double[] array, int start, int length, double... value value = DOUBLE_0; } System.arraycopy(value, 0, array, start, value.length); - + for (int i = value.length; i < length; i += i) { System.arraycopy(array, start, array, start + i, ((length - i) < i) ? (length - i) : i); } @@ -114,7 +115,7 @@ public static void memset(float[] array, int start, int length, float... value) value = FLOAT_0; } System.arraycopy(value, 0, array, start, value.length); - + for (int i = value.length; i < length; i += i) { System.arraycopy(array, start, array, start + i, ((length - i) < i) ? (length - i) : i); } @@ -127,7 +128,7 @@ public static void memset(boolean[] array, int start, int length, boolean... val value = BOOL_0; } System.arraycopy(value, 0, array, start, value.length); - + for (int i = value.length; i < length; i += i) { System.arraycopy(array, start, array, start + i, ((length - i) < i) ? (length - i) : i); } @@ -138,29 +139,31 @@ public static void memset(boolean[] array, int start, int length, boolean... val public static void memset(T array, int start, int length, T value, int valueStart, int valueLength) { if (length > 0 && valueLength > 0) { System.arraycopy(value, valueStart, array, start, valueLength); - + for (int i = valueLength; i < length; i += i) { System.arraycopy(array, start, array, start + i, ((length - i) < i) ? (length - i) : i); } } } - + @SuppressWarnings("SuspiciousSystemArraycopy") public static void memcpy(T srcArray, int srcStart, T dstArray, int dstStart, int length) { System.arraycopy(srcArray, srcStart, dstArray, dstStart, length); } - + public static T[] malloc(final ArraySupplier supplier, final IntFunction generator, final int length) { final T[] array = generator.apply(length); Arrays.setAll(array, supplier::getWithInt); return array; } - + public interface ArraySupplier extends Supplier { + default T getWithInt(int ignoredInt) { return get(); } } - - private GenericCopy() {} + + private GenericCopy() { + } } diff --git a/src/utils/OSValidator.java b/src/utils/OSValidator.java index f5d6dd4b..928c1722 100644 --- a/src/utils/OSValidator.java +++ b/src/utils/OSValidator.java @@ -14,34 +14,33 @@ * @author velktron * */ +public class OSValidator { -public class OSValidator{ - - public static boolean isWindows(){ - - String os = System.getProperty("os.name").toLowerCase(); - //windows - return (os.indexOf( "win" ) >= 0); - - } - - public static boolean isMac(){ - - String os = System.getProperty("os.name").toLowerCase(); - //Mac - return (os.indexOf( "mac" ) >= 0); - - } - - public static boolean isUnix(){ - - String os = System.getProperty("os.name").toLowerCase(); - //linux or unix - return (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0); - - } - - public static boolean isUnknown(){ - return (!isWindows() && !isUnix() && !isMac()); - } + public static boolean isWindows() { + + String os = System.getProperty("os.name").toLowerCase(); + //windows + return (os.contains("win")); + + } + + public static boolean isMac() { + + String os = System.getProperty("os.name").toLowerCase(); + //Mac + return (os.contains("mac")); + + } + + public static boolean isUnix() { + + String os = System.getProperty("os.name").toLowerCase(); + //linux or unix + return (os.contains("nix") || os.contains("nux")); + + } + + public static boolean isUnknown() { + return (!isWindows() && !isUnix() && !isMac()); + } } diff --git a/src/utils/OrderedExecutor.java b/src/utils/OrderedExecutor.java index e07ad806..9665a759 100644 --- a/src/utils/OrderedExecutor.java +++ b/src/utils/OrderedExecutor.java @@ -7,7 +7,10 @@ import java.util.concurrent.Executor; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; - +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; + /** * An executor that make sure tasks submitted with the same key * will be executed in the same order as task submission @@ -24,10 +27,12 @@ * * @param type of keys. */ public class OrderedExecutor { - + + private static final Logger LOGGER = Loggers.getLogger(OrderedExecutor.class.getName()); + private final Executor executor; private final Map tasks; - + /** * Constructs a {@code OrderedExecutor}. * @@ -35,9 +40,9 @@ public class OrderedExecutor { */ public OrderedExecutor(Executor executor) { this.executor = executor; - this.tasks = new HashMap(); + this.tasks = new HashMap<>(); } - + /** * Adds a new task to run for the given key. * @@ -52,21 +57,21 @@ public synchronized void submit(K key, Runnable runnable) { } task.add(runnable); } - + /** * Private inner class for running tasks for each key. * Each key submitted will have one instance of this class. */ private class Task implements Runnable { - + private final Lock lock; private final Queue queue; - + Task() { this.lock = new ReentrantLock(); - this.queue = new LinkedList(); + this.queue = new LinkedList<>(); } - + public void add(Runnable runnable) { boolean runTask; lock.lock(); @@ -81,7 +86,7 @@ public void add(Runnable runnable) { executor.execute(this); } } - + @Override public void run() { // Pick a task to run. @@ -95,7 +100,7 @@ public void run() { try { runnable.run(); } catch (Exception ex) { - ex.printStackTrace(); + LOGGER.log(Level.SEVERE, "OrderedExecutor run failure", ex); } // Check to see if there are queued task, if yes, submit for execution. lock.lock(); @@ -109,4 +114,4 @@ public void run() { } } } -} \ No newline at end of file +} diff --git a/src/utils/ParseString.java b/src/utils/ParseString.java index e1c6c38f..b648c830 100644 --- a/src/utils/ParseString.java +++ b/src/utils/ParseString.java @@ -21,21 +21,22 @@ /** * @author Good Sign */ -public enum ParseString {; +public enum ParseString { + ; public static Object parseString(String stringSource) { final Optional qt = QuoteType.getQuoteType(stringSource); final boolean quoted = qt.isPresent(); if (quoted) { stringSource = qt.get().unQuote(stringSource); } - + if (quoted && stringSource.length() == 1) { final Character test = stringSource.charAt(0); if (test >= 0 && test < 255) { return test; } } - + Optional ret = checkInt(stringSource); if (!ret.isPresent()) { ret = checkDouble(stringSource); @@ -46,46 +47,50 @@ public static Object parseString(String stringSource) { } } } - + return ret.get(); } - + public static Optional checkInt(final String stringSource) { Optional ret; try { long longRet = Long.parseLong(stringSource); return longRet < Integer.MAX_VALUE - ? Optional.of((int) longRet) - : Optional.of(longRet); - } catch (NumberFormatException e) {} + ? Optional.of((int) longRet) + : Optional.of(longRet); + } catch (NumberFormatException e) { + } try { long longRet = Long.decode(stringSource); return longRet < Integer.MAX_VALUE - ? Optional.of((int) longRet) - : Optional.of(longRet); - } catch (NumberFormatException e) {} + ? Optional.of((int) longRet) + : Optional.of(longRet); + } catch (NumberFormatException e) { + } return Optional.empty(); } - + public static Optional checkDouble(final String stringSource) { try { return Optional.of(Double.parseDouble(stringSource)); - } catch (NumberFormatException e) {} + } catch (NumberFormatException e) { + } return Optional.empty(); } - + public static Optional checkBoolean(final String stringSource) { try { return Optional.of(Boolean.parseBoolean(stringSource)); - } catch (NumberFormatException e) {} - + } catch (NumberFormatException e) { + } + if ("false".compareToIgnoreCase(stringSource) == 0) { return Optional.of(Boolean.FALSE); } return Optional.empty(); } -} \ No newline at end of file +} diff --git a/src/utils/QuoteType.java b/src/utils/QuoteType.java index 75370274..d39cd95e 100644 --- a/src/utils/QuoteType.java +++ b/src/utils/QuoteType.java @@ -36,10 +36,10 @@ public boolean isQuoted(final String s) { public String unQuote(final String s) { return C2JUtils.unquote(s, quoteChar); } - + public static Optional getQuoteType(final String stringSource) { if (stringSource.length() > 2) { - for (final QuoteType type: QuoteType.values()) { + for (final QuoteType type : QuoteType.values()) { if (type.isQuoted(stringSource)) { return Optional.of(type); } @@ -48,4 +48,4 @@ public static Optional getQuoteType(final String stringSource) { return Optional.empty(); } -} \ No newline at end of file +} diff --git a/src/utils/ResourceIO.java b/src/utils/ResourceIO.java index 946884a0..505fd59d 100644 --- a/src/utils/ResourceIO.java +++ b/src/utils/ResourceIO.java @@ -27,6 +27,9 @@ import java.nio.file.Path; import java.util.function.Consumer; import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; /** * Resource IO to automate read/write on configuration/resources @@ -35,6 +38,8 @@ */ public class ResourceIO { + private static final Logger LOGGER = Loggers.getLogger(ResourceIO.class.getName()); + private final Path file; private final Charset charset = Charset.forName("US-ASCII"); @@ -56,15 +61,15 @@ public boolean exists() { public boolean readLines(final Consumer lineConsumer) { if (Files.exists(file)) { - try (BufferedReader reader = Files.newBufferedReader(file, charset)) { + try ( BufferedReader reader = Files.newBufferedReader(file, charset)) { String line; while ((line = reader.readLine()) != null) { lineConsumer.accept(line); } - + return true; } catch (IOException x) { - System.err.format("IOException: %s%n", x); + LOGGER.log(Level.WARNING, "ResourceIO read failure", x); return false; } } @@ -73,20 +78,20 @@ public boolean readLines(final Consumer lineConsumer) { } public boolean writeLines(final Supplier lineSupplier, final OpenOption... options) { - try (BufferedWriter writer = Files.newBufferedWriter(file, charset, options)) { + try ( BufferedWriter writer = Files.newBufferedWriter(file, charset, options)) { String line; while ((line = lineSupplier.get()) != null) { writer.write(line, 0, line.length()); writer.newLine(); } - + return true; } catch (IOException x) { - System.err.format("IOException: %s%n", x); + LOGGER.log(Level.WARNING, "ResourceIO write failure", x); return false; } } - + public String getFileame() { return file.toString(); } diff --git a/src/utils/TraitFactory.java b/src/utils/TraitFactory.java index 66694560..01104792 100644 --- a/src/utils/TraitFactory.java +++ b/src/utils/TraitFactory.java @@ -94,28 +94,26 @@ * as negligible as one level of indirection + array access by int. */ public class TraitFactory { + private final static Logger LOGGER = Loggers.getLogger(TraitFactory.class.getName()); - + public static SharedContext build(T traitUser, KeyChain usedChain) - throws IllegalArgumentException, IllegalAccessException - { + throws IllegalArgumentException, IllegalAccessException { return build(traitUser, usedChain.currentCapacity); } - + public static SharedContext build(T traitUser, int idCapacity) - throws IllegalArgumentException, IllegalAccessException - { + throws IllegalArgumentException, IllegalAccessException { final FactoryContext c = new FactoryContext(idCapacity); repeatRecursive(traitUser.getClass().getInterfaces(), c); return c; } private static void repeatRecursive(final Class[] traitUserInteraces, final FactoryContext c) - throws IllegalAccessException, SecurityException, IllegalArgumentException - { - for (Class cls: traitUserInteraces) { + throws IllegalAccessException, SecurityException, IllegalArgumentException { + for (Class cls : traitUserInteraces) { final Field[] declaredFields = cls.getDeclaredFields(); - for (final Field f: declaredFields) { + for (final Field f : declaredFields) { final int modifiers = f.getModifiers(); if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { final Class fieldClass = f.getType(); @@ -126,49 +124,50 @@ private static void repeatRecursive(final Class[] traitUserInteraces, final F } } } - + repeatRecursive(cls.getInterfaces(), c); } } - + public interface Trait { + SharedContext getContext(); - + default T contextGet(ContextKey key, T defaultValue) { final T got = getContext().get(key); return got == null ? defaultValue : got; } - + default T contextRequire(ContextKey key) { final T got = getContext().get(key); if (got == null) { throw defaultException(key).get(); } - + return got; } - + default T contextRequire(ContextKey key, Supplier exceptionSupplier) throws E { final T got = getContext().get(key); if (got == null) { throw exceptionSupplier.get(); } - + return got; } - + default boolean contextTest(ContextKey key, Predicate predicate) { final T got = getContext().get(key); return got == null ? false : predicate.test(got); } - + default void contextWith(ContextKey key, Consumer consumer) { final T got = getContext().get(key); if (got != null) { consumer.accept(got); } } - + default R contextMap(ContextKey key, Function mapper, R defaultValue) { final T got = getContext().get(key); if (got != null) { @@ -177,13 +176,14 @@ default R contextMap(ContextKey key, Function mapper, R defaultV return defaultValue; } } - + default Supplier defaultException(ContextKey key) { return () -> new SharedContextException(key, this.getClass()); } } - + public final static class ContextKey { + final Class traitClass; final int preferredId; final Supplier contextConstructor; @@ -199,20 +199,23 @@ public String toString() { return String.format("context in the Trait %s (preferred id: %d)", traitClass, preferredId); } } - + public final static class KeyChain { + int currentCapacity; - + public ContextKey newKey(final Class traitClass, Supplier contextConstructor) { return new ContextKey<>(traitClass, currentCapacity++, contextConstructor); } } public interface SharedContext { + T get(ContextKey key); } - + final static class FactoryContext implements InsertConveyor, SharedContext { + private HashMap, Object> traitMap; private ContextKey[] keys; private Object[] contexts; @@ -237,7 +240,7 @@ public void put(ContextKey key, Supplier context) { return; } } - + hasMap = true; for (int i = 0; i < keys.length; ++i) { traitMap.put(keys[i], contexts[i]); @@ -246,7 +249,7 @@ public void put(ContextKey key, Supplier context) { keys = null; contexts = null; } - + traitMap.put(key, context.get()); } @@ -258,36 +261,39 @@ public T get(ContextKey key) { } else if (key.preferredId >= 0 && key.preferredId < keys.length) { return (T) contexts[key.preferredId]; } - + return null; } } - + public interface InsertConveyor { + void put(ContextKey key, Supplier context); - + default void putObj(ContextKey key, Object context) { put(key, () -> context); } } - + private static class SharedContextException extends RuntimeException { - private static final long serialVersionUID = 5356800492346200764L; - SharedContextException(ContextKey key, Class topLevel) { + private static final long serialVersionUID = 5356800492346200764L; + + SharedContextException(ContextKey key, Class topLevel) { super(String.format("Trait context %s is not initialized when used by %s or" - + "is dereferencing a null pointer when required to do not", - key, topLevel)); - } + + "is dereferencing a null pointer when required to do not", + key, topLevel)); + } } - + private static Type[] getParameterizedTypes(Object object) { Type superclassType = object.getClass().getGenericSuperclass(); if (!ParameterizedType.class.isAssignableFrom(superclassType.getClass())) { return null; } - return ((ParameterizedType)superclassType).getActualTypeArguments(); + return ((ParameterizedType) superclassType).getActualTypeArguments(); + } + + private TraitFactory() { } - - private TraitFactory() {} } diff --git a/src/v/DoomGraphicSystem.java b/src/v/DoomGraphicSystem.java index 8371f254..ed4f85e4 100644 --- a/src/v/DoomGraphicSystem.java +++ b/src/v/DoomGraphicSystem.java @@ -14,7 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v; import f.Wiper; @@ -83,27 +82,26 @@ * * @author Maes */ - public interface DoomGraphicSystem { - + /** * Flags used by patch drawing functions * Now working as separate and optional varargs argument * Added by _D_. Unsure if I should use VSI objects instead, as they * already carry scaling information which doesn't need to be repacked... */ - final int V_NOSCALESTART = 0x00010000; // dont scale x,y, start coords - final int V_SCALESTART = 0x00020000; // scale x,y, start coords - final int V_SCALEPATCH = 0x00040000; // scale patch - final int V_NOSCALEPATCH = 0x00080000; // don't scale patch - final int V_WHITEMAP = 0x00100000; // draw white (for v_drawstring) - final int V_FLIPPEDPATCH = 0x00200000; // flipped in y - final int V_TRANSLUCENTPATCH = 0x00400000; // draw patch translucent - final int V_PREDIVIDE = 0x00800000; // pre-divide by best x/y scale. - final int V_SCALEOFFSET = 0x01000000; // Scale the patch offset - final int V_NOSCALEOFFSET = 0x02000000; // dont's cale patch offset - final int V_SAFESCALE = 0x04000000; // scale only by minimal scale of x/y instead of both - + final int V_NOSCALESTART = 0x00010000; // dont scale x,y, start coords + final int V_SCALESTART = 0x00020000; // scale x,y, start coords + final int V_SCALEPATCH = 0x00040000; // scale patch + final int V_NOSCALEPATCH = 0x00080000; // don't scale patch + final int V_WHITEMAP = 0x00100000; // draw white (for v_drawstring) + final int V_FLIPPEDPATCH = 0x00200000; // flipped in y + final int V_TRANSLUCENTPATCH = 0x00400000; // draw patch translucent + final int V_PREDIVIDE = 0x00800000; // pre-divide by best x/y scale. + final int V_SCALEOFFSET = 0x01000000; // Scale the patch offset + final int V_NOSCALEOFFSET = 0x02000000; // dont's cale patch offset + final int V_SAFESCALE = 0x04000000; // scale only by minimal scale of x/y instead of both + /** * Public API * See documentation in r2d package @@ -112,60 +110,84 @@ public interface DoomGraphicSystem { * Because using only these methods, it is minimal risk of breaking something. Actually, * the only problematic cases should be passing null instead of argument or invalid coordinates. */ - /* SCREENS */ V getScreen(DoomScreen screenType); + int getScalingX(); + int getScalingY(); + int getScreenWidth(); + int getScreenHeight(); + void screenCopy(V srcScreen, V dstScreen, Relocation relocation); + void screenCopy(DoomScreen srcScreen, DoomScreen dstScreen); /* PALETTES */ void setUsegamma(int gammalevel); + int getUsegamma(); + void setPalette(int palette); + int getPalette(); + int getBaseColor(byte color); + int getBaseColor(int color); - + /* POINTS */ int point(int x, int y); + int point(int x, int y, int width); - + /* LINES */ void drawLine(Plotter plotter, int x1, int x2); - + /* PATCHES */ void DrawPatch(DoomScreen screen, patch_t patch, int x, int y, int... flags); + void DrawPatchCentered(DoomScreen screen, patch_t patch, int y, int... flags); + void DrawPatchCenteredScaled(DoomScreen screen, patch_t patch, VideoScale vs, int y, int... flags); + void DrawPatchScaled(DoomScreen screen, patch_t patch, VideoScale vs, int x, int y, int... flags); + void DrawPatchColScaled(DoomScreen screen, patch_t patch, VideoScale vs, int x, int col); - + /* RECTANGLES */ void CopyRect(DoomScreen srcScreenType, Rectangle rectangle, DoomScreen dstScreenType); + void CopyRect(DoomScreen srcScreenType, Rectangle rectangle, DoomScreen dstScreenType, int dstPoint); + void FillRect(DoomScreen screenType, Rectangle rectangle, V patternSrc, Horizontal pattern); + void FillRect(DoomScreen screenType, Rectangle rectangle, V patternSrc, int point); + void FillRect(DoomScreen screenType, Rectangle rectangle, int color); + void FillRect(DoomScreen screenType, Rectangle rectangle, byte color); - + /* BLOCKS */ V convertPalettedBlock(byte... src); + V ScaleBlock(V block, VideoScale vs, int width, int height); + void TileScreen(DoomScreen dstScreen, V block, Rectangle blockArea); + void TileScreenArea(DoomScreen dstScreen, Rectangle screenArea, V block, Rectangle blockArea); + void DrawBlock(DoomScreen dstScreen, V block, Rectangle sourceArea, int destinationPoint); - + /** * No matter how complex/weird/arcane palette manipulations you do internally, the AWT module * must always be able to "tap" into what's the current, "correct" screen after all manipulation and * color juju was applied. Call after a palette/gamma change. */ Image getScreenImage(); - + /** * Saves screenshot to a file "filling a planar buffer to linear" * (I cannot guarantee I understood - Good Sign 2017/04/01) @@ -185,7 +207,7 @@ public interface DoomGraphicSystem { * Plotter for point-by-point drawing of AutoMap */ default Plotter createPlotter(DoomScreen screen) { - switch(Engine.getConfig().getValue(Settings.automap_plotter_style, Plotter.Style.class)) { + switch (Engine.getConfig().getValue(Settings.automap_plotter_style, Plotter.Style.class)) { case Thick: return new Plotter.Thick<>(getScreen(screen), getScreenWidth(), getScreenHeight()); case Deep: @@ -194,12 +216,14 @@ default Plotter createPlotter(DoomScreen screen) { return new Plotter.Thin<>(getScreen(screen), getScreenWidth()); } } - + Wiper createWiper(IRandom random); + BlurryTable getBlurryTable(); /** * Indexed renderer needs to reset its image */ - default void forcePalette() {} -} \ No newline at end of file + default void forcePalette() { + } +} diff --git a/src/v/graphics/Blocks.java b/src/v/graphics/Blocks.java index b2054566..399bc11c 100644 --- a/src/v/graphics/Blocks.java +++ b/src/v/graphics/Blocks.java @@ -26,20 +26,21 @@ * @author Good Sign */ public interface Blocks> extends Points, Palettes { + /** * Converts a block of paletted pixels into screen format pixels * It is advised that implementation should both perform caching * and be additionally optimized for 1-value src arrays */ V convertPalettedBlock(byte... src); - + /** * Fills the whole dstScreen tiling the copies of block across it */ default void TileScreen(E dstScreen, V block, Rectangle blockArea) { final int screenHeight = getScreenHeight(); final int screenWidth = getScreenWidth(); - + for (int y = 0; y < screenHeight; y += blockArea.height) { // Draw whole blocks. for (int x = 0; x < screenWidth; x += blockArea.width) { @@ -48,7 +49,7 @@ default void TileScreen(E dstScreen, V block, Rectangle blockArea) { } } } - + /** * Fills the rectangular part of dstScreen tiling the copies of block across it */ @@ -56,7 +57,7 @@ default void TileScreenArea(E dstScreen, Rectangle screenArea, V block, Rectangl final int screenWidth = getScreenWidth(); final int fiilLimitX = screenArea.x + screenArea.width; final int fiilLimitY = screenArea.y + screenArea.height; - + for (int y = screenArea.y; y < fiilLimitY; y += blockArea.height) { // Draw whole blocks. for (int x = screenArea.x; x < fiilLimitX; x += blockArea.width) { @@ -65,7 +66,7 @@ default void TileScreenArea(E dstScreen, Rectangle screenArea, V block, Rectangl } } } - + /** * Draws a linear block of pixels from the source buffer into screen buffer * V_DrawBlock @@ -75,10 +76,10 @@ default void DrawBlock(E dstScreen, V block, Rectangle sourceArea, int destinati final int bufferLength = Array.getLength(screen); final int screenWidth = getScreenWidth(); final Relocation rel = new Relocation( - point(sourceArea.x, sourceArea.y), - destinationPoint, - sourceArea.width); - + point(sourceArea.x, sourceArea.y), + destinationPoint, + sourceArea.width); + for (int h = sourceArea.height; h > 0; --h, rel.source += sourceArea.width, rel.destination += screenWidth) { if (rel.destination + rel.length >= bufferLength) { return; @@ -86,18 +87,18 @@ default void DrawBlock(E dstScreen, V block, Rectangle sourceArea, int destinati screenCopy(block, screen, rel); } } - + default V ScaleBlock(V block, VideoScale vs, int width, int height) { return ScaleBlock(block, width, height, vs.getScalingX(), vs.getScalingY()); } - + default V ScaleBlock(V block, int width, int height, int dupX, int dupY) { final int newWidth = width * dupX; final int newHeight = height * dupY; @SuppressWarnings("unchecked") final V newBlock = (V) Array.newInstance(block.getClass().getComponentType(), newWidth * newHeight); final Horizontal row = new Horizontal(0, dupX); - + for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { final int pointSource = point(i, j, width); @@ -109,7 +110,7 @@ default V ScaleBlock(V block, int width, int height, int dupX, int dupY) { RepeatRow(newBlock, row, dupY - 1, newWidth); } } - + return newBlock; } @@ -119,7 +120,7 @@ default V ScaleBlock(V block, int width, int height, int dupX, int dupY) { default void RepeatRow(V screen, final Horizontal row, int times) { RepeatRow(screen, row, times, getScreenWidth()); } - + /** * Given a row, repeats it down the screen */ diff --git a/src/v/graphics/ColorTransform.java b/src/v/graphics/ColorTransform.java index dad23d32..90c2dc54 100644 --- a/src/v/graphics/ColorTransform.java +++ b/src/v/graphics/ColorTransform.java @@ -17,27 +17,26 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v.graphics; import java.lang.reflect.Array; -import static utils.GenericCopy.*; +import static utils.GenericCopy.memcpy; public interface ColorTransform { - + default boolean initTransform(Wipers.WiperImpl wiper) { memcpy(wiper.wipeStartScr, 0, wiper.wipeEndScr, 0, Array.getLength(wiper.wipeEndScr)); return false; } - + default boolean colorTransformB(Wipers.WiperImpl wiper) { byte[] w = wiper.wipeStartScr, e = wiper.wipeEndScr; boolean changed = false; for (int i = 0, newval; i < w.length; ++i) { if (w[i] != e[i]) { w[i] = w[i] > e[i] - ? (newval = w[i] - wiper.ticks) < e[i] ? e[i] : (byte) newval - : (newval = w[i] + wiper.ticks) > e[i] ? e[i] : (byte) newval; + ? (newval = w[i] - wiper.ticks) < e[i] ? e[i] : (byte) newval + : (newval = w[i] + wiper.ticks) > e[i] ? e[i] : (byte) newval; changed = true; } } @@ -50,8 +49,8 @@ default boolean colorTransformS(Wipers.WiperImpl wiper) { for (int i = 0, newval; i < w.length; ++i) { if (w[i] != e[i]) { w[i] = w[i] > e[i] - ? (newval = w[i] - wiper.ticks) < e[i] ? e[i] : (byte) newval - : (newval = w[i] + wiper.ticks) > e[i] ? e[i] : (byte) newval; + ? (newval = w[i] - wiper.ticks) < e[i] ? e[i] : (byte) newval + : (newval = w[i] + wiper.ticks) > e[i] ? e[i] : (byte) newval; changed = true; } } @@ -64,8 +63,8 @@ default boolean colorTransformI(Wipers.WiperImpl wiper) { for (int i = 0, newval; i < w.length; ++i) { if (w[i] != e[i]) { w[i] = w[i] > e[i] - ? (newval = w[i] - wiper.ticks) < e[i] ? e[i] : (byte) newval - : (newval = w[i] + wiper.ticks) > e[i] ? e[i] : (byte) newval; + ? (newval = w[i] - wiper.ticks) < e[i] ? e[i] : (byte) newval + : (newval = w[i] + wiper.ticks) > e[i] ? e[i] : (byte) newval; changed = true; } } diff --git a/src/v/graphics/Colors.java b/src/v/graphics/Colors.java index 3d0e796f..e9810541 100644 --- a/src/v/graphics/Colors.java +++ b/src/v/graphics/Colors.java @@ -22,6 +22,7 @@ * Package containing individual color modification and transformation methods */ public interface Colors { + /** * Get alpha from packed argb long word. * @@ -31,7 +32,7 @@ public interface Colors { default int getAlpha(int argb8888) { return (argb8888 >>> 24) & 0xFF; } - + /** * Get red from packed argb long word. * @@ -81,7 +82,7 @@ default int getGreen5(int rgb555) { default int getBlue(int rgb888) { return 0xFF & rgb888; } - + /** * Get blue from packed rgb555 * @@ -102,7 +103,7 @@ default int[] getARGB8888(int argb8888, int[] container) { container[3] = getBlue(argb8888); return container; } - + /** * Get all four color channels into an array */ @@ -112,7 +113,7 @@ default int[] getRGB888(int rgb888, int[] container) { container[2] = getBlue(rgb888); return container; } - + /** * Get all three colors into an array */ @@ -122,28 +123,28 @@ default int[] getRGB555(int rgb555, int[] container) { container[2] = getBlue5(rgb555); return container; } - + /** * Compose rgb888 color (opaque) */ default int toRGB888(int r, int g, int b) { return 0xFF000000 + ((r & 0xFF) << 16) + ((g & 0xFF) << 8) + (b & 0xFF); } - + /** * Compose argb8888 color */ default int toARGB8888(int a, int r, int g, int b) { return ((a & 0xFF) << 24) + ((r & 0xFF) << 16) + ((g & 0xFF) << 8) + (b & 0xFF); } - + /** * Compose rgb888 color */ default short toRGB555(int r, int g, int b) { return (short) (((r & 0x1F) << 10) + ((g & 0x1F) << 5) + (b & 0x1F)); } - + /** * Alter rgb888 color by applying a tint to it * @param int[] rgbInput an array containing rgb888 color components @@ -165,11 +166,11 @@ default int[] tintRGB555(final ColorTint tint, final int[] rgbInput, int[] rgbOu rgbOutput[2] = tint.tintBlue5(rgbInput[2]); return rgbOutput; } - + default double sigmoid(double r) { return (1 / (1 + Math.pow(Math.E, (-1 * r)))); } - + default int sigmoidGradient(int component1, int component2, float ratio) { return (int) ((ratio * component1) + ((1 - ratio) * component2)); } @@ -181,7 +182,7 @@ default int CompareColors888(int rgb888_1, int rgb888_2) { final long distance = ColorDistance888(rgb888_1, rgb888_2); return distance > 0 ? 1 : distance < 0 ? -1 : 0; } - + /** * Computes simplified Euclidean color distance (without extracting square root) between two packed rbg888 ints */ @@ -192,7 +193,7 @@ default long ColorDistance888(int rgb888_1, int rgb888_2) { r2 = getRed(rgb888_2), g2 = getGreen(rgb888_2), b2 = getBlue(rgb888_2); - + final long dr = r1 - r2, dg = g1 - g2, db = b1 - b2; return dr * dr + dg * dg + db * db; } @@ -204,19 +205,19 @@ default int CompareColorsHSV888(int rgb888_1, int rgb888_2) { final long distance = ColorDistanceHSV888(rgb888_1, rgb888_2); return distance > 0 ? 1 : distance < 0 ? -1 : 0; } - + /** * Computes simplified Euclidean color distance (without extracting square root) between two packed rbg888 ints * based on hue, saturation and value */ default long ColorDistanceHSV888(int rgb888_1, int rgb888_2) { final int r1 = (int) (0.21 * getRed(rgb888_1)), - g1 = (int) (0.72 * getGreen(rgb888_1)), - b1 = (int) (0.07 * getBlue(rgb888_1)), - r2 = (int) (0.21 * getRed(rgb888_2)), - g2 = (int) (0.72 * getGreen(rgb888_2)), - b2 = (int) (0.07 * getBlue(rgb888_2)); - + g1 = (int) (0.72 * getGreen(rgb888_1)), + b1 = (int) (0.07 * getBlue(rgb888_1)), + r2 = (int) (0.21 * getRed(rgb888_2)), + g2 = (int) (0.72 * getGreen(rgb888_2)), + b2 = (int) (0.07 * getBlue(rgb888_2)); + final long dr = r1 - r2, dg = g1 - g2, db = b1 - b2; return dr * dr + dg * dg + db * db; } @@ -228,18 +229,18 @@ default int CompareColors555(short rgb555_1, short rgb555_2) { final long distance = ColorDistance555(rgb555_1, rgb555_2); return distance > 0 ? 1 : distance < 0 ? -1 : 0; } - + /** * Computes simplified Euclidean color distance (without extracting square root) between two packed rbg555 shorts */ default long ColorDistance555(short rgb1, short rgb2) { final int r1 = getRed5(rgb1), - g1 = getGreen5(rgb1), - b1 = getBlue5(rgb1), - r2 = getRed5(rgb2), - g2 = getGreen5(rgb2), - b2 = getBlue5(rgb2); - + g1 = getGreen5(rgb1), + b1 = getBlue5(rgb1), + r2 = getRed5(rgb2), + g2 = getGreen5(rgb2), + b2 = getBlue5(rgb2); + final long dr = r1 - r2, dg = g1 - g2, db = b1 - b2; return dr * dr + dg * dg + db * db; } @@ -251,19 +252,19 @@ default int CompareColorsHSV555(short rgb555_1, short rgb555_2) { final long distance = ColorDistanceHSV555(rgb555_1, rgb555_2); return distance > 0 ? 1 : distance < 0 ? -1 : 0; } - + /** * Computes simplified Euclidean color distance (without extracting square root) between two packed rbg888 ints * based on hue, saturation and value */ default long ColorDistanceHSV555(short rgb555_1, int rgb555_2) { final int r1 = (int) (0.21 * getRed5(rgb555_1)), - g1 = (int) (0.72 * getGreen5(rgb555_1)), - b1 = (int) (0.07 * getBlue5(rgb555_1)), - r2 = (int) (0.21 * getRed5(rgb555_2)), - g2 = (int) (0.72 * getGreen5(rgb555_2)), - b2 = (int) (0.07 * getBlue5(rgb555_2)); - + g1 = (int) (0.72 * getGreen5(rgb555_1)), + b1 = (int) (0.07 * getBlue5(rgb555_1)), + r2 = (int) (0.21 * getRed5(rgb555_2)), + g2 = (int) (0.72 * getGreen5(rgb555_2)), + b2 = (int) (0.07 * getBlue5(rgb555_2)); + final long dr = r1 - r2, dg = g1 - g2, db = b1 - b2; return dr * dr + dg * dg + db * db; } @@ -274,7 +275,7 @@ default float[] ColorRatio(int[] rgb1, int[] rgb2, float[] out) { } return out; } - + /** * Get ARGB_8888 from RGB_555, with proper higher-bit * replication. @@ -330,7 +331,7 @@ default short argb8888to555(int argb8888) { default short rgb888to555(int r, int g, int b) { return toRGB555(r >> 3, g >> 3, b >> 3); } - + /** * Finds a color in the palette's range from rangel to rangeh closest to specified r, g, b * by distortion, the lesst distorted color is the result. Used for rgb555 invulnerability colormap diff --git a/src/v/graphics/Columns.java b/src/v/graphics/Columns.java index 28d01da6..151d24b4 100644 --- a/src/v/graphics/Columns.java +++ b/src/v/graphics/Columns.java @@ -20,6 +20,7 @@ import java.util.concurrent.ForkJoinPool; import java.util.function.IntConsumer; import java.util.logging.Level; +import java.util.logging.Logger; import java.util.stream.IntStream; import m.Settings; import mochadoom.Engine; @@ -35,6 +36,9 @@ * @author Good Sign */ public interface Columns> extends Blocks { + + static final Logger LOGGER = Loggers.getLogger(Columns.class.getName()); + /** * We have to draw columns to the screen, not rows and is ineffective performance-wise because * System.arraycopy only speeds a lot row copying, where it only have to be called once @@ -48,9 +52,8 @@ default void DrawColumn(V screen, column_t col, Horizontal row, V data, int scrW * is transparent, so if we have delta 0xFF, then we've done with column drawing. */ for (int j = 0, delta = 0; - j < col.posts && col.postdeltas[j] != 0xFF; - ++j - ) { + j < col.posts && col.postdeltas[j] != 0xFF; + ++j) { // shift a row down by difference of current and previous delta with respect to scaling row.shift(point(0, (-delta + (delta = col.postdeltas[j])) * dupy, scrWidth)); final int saveRowStart = row.start; @@ -80,9 +83,9 @@ default void DrawPatchColumns(V screen, patch_t patch, int x, int y, int dupx, i final int startPoint = point(x + i * dupx, y, scrWidth); final column_t column = flip ? patch.columns[patch.width - 1 - i] : patch.columns[i]; DrawColumn(screen, column, new Horizontal(startPoint, dupx), - convertPalettedBlock(column.data), scrWidth, dupy); + convertPalettedBlock(column.data), scrWidth, dupy); }; - + /** * As vanilla DOOM does not parallel column computation, we should have the option to turn off * the parallelism. Just set it to 0 in cfg:parallelism_patch_columns, and it will process columns in serial. @@ -94,15 +97,20 @@ default void DrawPatchColumns(V screen, patch_t patch, int x, int y, int dupx, i if (U.COLUMN_THREADS > 0) try { U.pool.submit(() -> IntStream.range(0, patch.width).parallel().forEach(task)).get(); } catch (InterruptedException | ExecutionException ex) { - Loggers.getLogger(Columns.class.getName()).log(Level.SEVERE, null, ex); - } else for (int i = 0; i < patch.width; ++i) { - task.accept(i); + LOGGER.log(Level.SEVERE, null, ex); + } else { + for (int i = 0; i < patch.width; ++i) { + task.accept(i); + } } } - + class U { + static final int COLUMN_THREADS = Engine.getConfig().getValue(Settings.parallelism_patch_columns, Integer.class); private static final ForkJoinPool pool = COLUMN_THREADS > 0 ? new ForkJoinPool(COLUMN_THREADS) : null; - private U() {} + + private U() { + } } } diff --git a/src/v/graphics/Direction.java b/src/v/graphics/Direction.java index 59ee06c4..284f24dd 100644 --- a/src/v/graphics/Direction.java +++ b/src/v/graphics/Direction.java @@ -25,24 +25,23 @@ * @author Good Sign */ public enum Direction { - LEFT_UP, UP, RIGHT_UP, + LEFT_UP, UP, RIGHT_UP, /* \ || / */ /* \ || / */ /* \ || / */ /* \ || / */ - LEFT,/*===*/CENTER,/*===*/RIGHT, + LEFT,/*===*/ CENTER,/*===*/ RIGHT, /* / || \ */ /* / || \ */ /* / || \ */ /* / || \ */ - LEFT_DOWN, DOWN, RIGHT_DOWN; - + LEFT_DOWN, DOWN, RIGHT_DOWN; + public static final List directions = Collections.unmodifiableList(Arrays.asList(values())); /** * Categorization constants */ - // LEFT_UP, UP, RIGHT_UP public final boolean hasTop = ordinal() < 3; // LEFT_UP, LEFT, LEFT_DOWN @@ -52,25 +51,25 @@ public enum Direction { // LEFT_DOWN, DOWN, RIGHT_DOWN public final boolean hasBottom = ordinal() > 5; // UP, LEFT, RIGHT, DOWN - public final boolean straight = ordinal() % 2 != 0; + public final boolean straight = ordinal() % 2 != 0; public boolean isAdjacent(Direction dir) { return this.straight ^ dir.straight; } - + /** * Conversions */ - public Direction next() { - if (this == RIGHT_DOWN) + if (this == RIGHT_DOWN) { return LEFT_UP; - + } + return directions.get(ordinal() + 1); } - + public Direction opposite() { - switch(this) { + switch (this) { case LEFT_UP: return RIGHT_DOWN; case UP: @@ -91,12 +90,13 @@ public Direction opposite() { return LEFT_UP; } } - + public Direction rotationHor(int sign) { - if (sign == 0) + if (sign == 0) { return this; - - switch(this) { + } + + switch (this) { case LEFT_UP: return sign > 0 ? UP : LEFT; case UP: @@ -117,12 +117,13 @@ public Direction rotationHor(int sign) { return sign > 0 ? RIGHT : DOWN; } } - + public Direction rotationVert(int sign) { - if (sign == 0) + if (sign == 0) { return this; - - switch(this) { + } + + switch (this) { case LEFT_UP: return sign > 0 ? LEFT : UP; case UP: @@ -143,21 +144,22 @@ public Direction rotationVert(int sign) { return sign > 0 ? DOWN : RIGHT; } } - + public Direction rotation(int signX, int signY) { final Direction rotX = rotationHor(signX), rotY = rotationHor(signY); - + if (rotX.isAdjacent(rotY)) { - if (signX > 0 && signY > 0) + if (signX > 0 && signY > 0) { return RIGHT_DOWN; - else if (signX > 0 && signY < 0) + } else if (signX > 0 && signY < 0) { return RIGHT_UP; - else if (signX < 0 && signY > 0) + } else if (signX < 0 && signY > 0) { return LEFT_DOWN; - else if (signX < 0 && signY < 0) + } else if (signX < 0 && signY < 0) { return LEFT_UP; + } } - + // otherwise, 2nd takes precedence return rotY; } diff --git a/src/v/graphics/Horizontal.java b/src/v/graphics/Horizontal.java index 6132f654..c3ebbc85 100644 --- a/src/v/graphics/Horizontal.java +++ b/src/v/graphics/Horizontal.java @@ -22,7 +22,7 @@ * @author Good Sign */ public class Horizontal { - + public int start; public int length; diff --git a/src/v/graphics/Lights.java b/src/v/graphics/Lights.java index 6253f93a..21ef63c9 100644 --- a/src/v/graphics/Lights.java +++ b/src/v/graphics/Lights.java @@ -29,12 +29,13 @@ * @author Velktron */ public interface Lights extends Colors { + /** * Light levels. Binded to the colormap subsystem */ final int COLORMAP_LIGHTS_15 = 1 << 5; final int COLORMAP_LIGHTS_24 = 1 << 8; - + /** * Standard lengths for colormaps */ @@ -52,7 +53,7 @@ public interface Lights extends Colors { * - Good Sign 2017/04/15 */ final int COLORMAP_INVERSE = 32; - + /** * An index of of the lighted palette in colormap used for FUZZ effect and partial invisibility */ @@ -85,7 +86,7 @@ public interface Lights extends Colors { * - Good Sign 2017/04/17 */ final float LIGHT_INCREMENT_RATIO_24 = 1.0f / COLORMAP_LIGHTS_24; - + /** * Builds TrueColor lights based on standard COLORMAP lump in DOOM format * Currently only supports lightmap manipulation, but does not change colors @@ -100,15 +101,13 @@ public interface Lights extends Colors { * @author Good Sign */ default int[][] BuildLights24(int[] palette, byte[][] colormap) { - final int[][] targetColormap = new int[ - Math.max(colormap.length, COLORMAP_STD_LENGTH_15) - COLORMAP_LIGHTS_15 + COLORMAP_LIGHTS_24 - ][PAL_NUM_COLORS]; - + final int[][] targetColormap = new int[Math.max(colormap.length, COLORMAP_STD_LENGTH_15) - COLORMAP_LIGHTS_15 + COLORMAP_LIGHTS_24][PAL_NUM_COLORS]; + // init operation containers final int[] color0 = new int[3], color1 = new int[3], color2 = new int[3]; final float[] ratio0 = new float[3]; float weight = 0.0f; - + /** * Fixed color map - just copy it, only translating palette to real color * It is presumably the brightest colormap, but maybe not: we shall check weight of color ratios @@ -122,10 +121,10 @@ default int[][] BuildLights24(int[] palette, byte[][] colormap) { // add average ratio to the weight weight += GreyscaleFilter.component(ratio0[0], ratio0[1], ratio0[2]); } - + // initialize ratio to relate weight with number of colors, with default PLAYPAL should always be 1.0f float currentLightRatio = Math.min(weight / PAL_NUM_COLORS, 1.0f); - + // [1 .. 255]: all colormaps except 1 fixed, 1 inverse and 1 unused for (int i = 1; i < COLORMAP_LIGHTS_24; ++i) { // [1 .. 31] the index of the colormap to be target for gradations: max 31 of ceiling of i / 8 @@ -133,7 +132,7 @@ default int[][] BuildLights24(int[] palette, byte[][] colormap) { final int target = Math.min(div, COLORMAP_LIGHTS_15 - 1); final int remainder = div < COLORMAP_LIGHTS_15 ? i % 8 : 0; final float gradient = 1.0f - remainder * 0.125f; - + // calculate weight again for each colormap weight = 0.0f; for (int j = 0; j < PAL_NUM_COLORS; ++j) { @@ -147,28 +146,28 @@ default int[][] BuildLights24(int[] palette, byte[][] colormap) { weight += GreyscaleFilter.component(ratio0[0], ratio0[1], ratio0[2]); // to detect which color we will use, get the fixed colormap one getRGB888(targetColormap[0][j], color2); - + /** * set our color using smooth TrueColor formula: we well use the brighter color as a base * since the brighter color simply have more information not omitted * if we are going up in brightness, not down, it will be compensated by ratio */ targetColormap[i][j] = toRGB888( - sigmoidGradient(color1[0], (int) (Math.max(color2[0], color0[0]) * currentLightRatio + 0.5), gradient), - sigmoidGradient(color1[1], (int) (Math.max(color2[1], color0[1]) * currentLightRatio + 0.5), gradient), - sigmoidGradient(color1[2], (int) (Math.max(color2[2], color0[2]) * currentLightRatio + 0.5), gradient) + sigmoidGradient(color1[0], (int) (Math.max(color2[0], color0[0]) * currentLightRatio + 0.5), gradient), + sigmoidGradient(color1[1], (int) (Math.max(color2[1], color0[1]) * currentLightRatio + 0.5), gradient), + sigmoidGradient(color1[2], (int) (Math.max(color2[2], color0[2]) * currentLightRatio + 0.5), gradient) ); } - + // now detect if we are lightening or darkening currentLightRatio += weight > PAL_NUM_COLORS ? LIGHT_INCREMENT_RATIO_24 : -LIGHT_INCREMENT_RATIO_24; } - + // copy all other parts of colormap for (int i = COLORMAP_LIGHTS_24, j = COLORMAP_LIGHTS_15; j < colormap.length; ++i, ++j) { CopyMap24(targetColormap[i], palette, colormap[j]); } - + return targetColormap; } @@ -186,23 +185,23 @@ default int[][] BuildLights24(int[] palette, byte[][] colormap) { default int[][] BuildLights24(int[] palette) { final int[][] targetColormap = new int[COLORMAP_STD_LENGTH_24][PAL_NUM_COLORS]; final int[] palColor = new int[3]; - + // Don't repeat work more then necessary - loop first over colors, not lights for (int c = 0; c < PAL_NUM_COLORS; ++c) { getRGB888(palette[c], palColor); for (int l = 0; l < COLORMAP_LIGHTS_24; ++l) { // Full-quality truecolor. targetColormap[l][c] = toRGB888( - AddLight8(palColor[0], l), // R - AddLight8(palColor[1], l), // G - AddLight8(palColor[2], l) // B + AddLight8(palColor[0], l), // R + AddLight8(palColor[1], l), // G + AddLight8(palColor[2], l) // B ); } - + // Special map for invulnerability. Do not waste time, build it right now BuildSpecials24(targetColormap[COLORMAP_LIGHTS_24], palColor, c); } - + return targetColormap; } @@ -220,14 +219,14 @@ default int[][] BuildLights24(int[] palette) { */ default short[][] BuildLights15(int[] palette, byte[][] colormaps) { final short[][] targetColormap = new short[Math.max(colormaps.length, COLORMAP_STD_LENGTH_15)][PAL_NUM_COLORS]; - + for (int c = 0; c < colormaps.length; ++c) { CopyMap15(targetColormap[c], palette, colormaps[c]); } return targetColormap; } - + /** * RF_BuildLights lifted from dcolors.c * @@ -240,16 +239,16 @@ default short[][] BuildLights15(int[] palette, byte[][] colormaps) { default short[][] BuildLights15(int[] palette) { final short[][] targetColormap = new short[COLORMAP_STD_LENGTH_15][PAL_NUM_COLORS]; final int[] palColor = new int[3]; - + // Don't repeat work more then necessary - loop first over colors, not lights for (int c = 0; c < PAL_NUM_COLORS; ++c) { getRGB888(palette[c], palColor); for (int l = 0; l < COLORMAP_LIGHTS_15; ++l) { // RGB555 for HiColor, eight times less smooth then TrueColor version targetColormap[l][c] = toRGB555( - AddLight5(palColor[0], l), // R - AddLight5(palColor[1], l), // G - AddLight5(palColor[2], l) // B + AddLight5(palColor[0], l), // R + AddLight5(palColor[1], l), // G + AddLight5(palColor[2], l) // B ); } @@ -259,7 +258,7 @@ default short[][] BuildLights15(int[] palette) { return targetColormap; } - + /** * RF_BuildLights lifted from dcolors.c * @@ -274,17 +273,17 @@ default short[][] BuildLights15(int[] palette) { default byte[][] BuildLightsI(int[] palette) { final byte[][] targetColormap = new byte[COLORMAP_STD_LENGTH_15][PAL_NUM_COLORS]; final int[] palColor = new int[3]; - + // Don't repeat work more then necessary - loop first over colors, not lights for (int c = 0; c < PAL_NUM_COLORS; ++c) { getRGB888(palette[c], palColor); for (int l = 0; l < COLORMAP_LIGHTS_15; ++l) { // RGB555 for HiColor, eight times less smooth then TrueColor version targetColormap[l][c] = (byte) BestColor( - AddLightI(palColor[0], l), // R - AddLightI(palColor[1], l), // G - AddLightI(palColor[2], l), // B - palette, 0, PAL_NUM_COLORS - 1 + AddLightI(palColor[0], l), // R + AddLightI(palColor[1], l), // G + AddLightI(palColor[2], l), // B + palette, 0, PAL_NUM_COLORS - 1 ); } @@ -321,7 +320,7 @@ default int AddLight5(int c8, int light) { default int AddLightI(int c8, int light) { return (int) (c8 * (1 - (float) light / COLORMAP_LIGHTS_15) + 0.5); } - + /** * Decides the size of array for colormap and creates it * @param hasColormap whether the array have lump-read colormap @@ -331,13 +330,13 @@ default int AddLightI(int c8, int light) { default int[][] AllocateColormap24(final boolean hasColormap, byte[][][] colormap) { // if the lump-read COLORMAP is shorter, we must allocate enough final int targetLength = hasColormap - ? COLORMAP_STD_LENGTH_24 + Math.max(0, colormap[0].length - COLORMAP_STD_LENGTH_15) - : COLORMAP_STD_LENGTH_24; - + ? COLORMAP_STD_LENGTH_24 + Math.max(0, colormap[0].length - COLORMAP_STD_LENGTH_15) + : COLORMAP_STD_LENGTH_24; + final int[][] targetColormap = new int[targetLength][PAL_NUM_COLORS]; return targetColormap; } - + /** * Decides the size of array for colormap and creates it * @param hasColormap whether the array have lump-read colormap @@ -347,13 +346,13 @@ default int[][] AllocateColormap24(final boolean hasColormap, byte[][][] colorma default short[][] AllocateColormap15(final boolean hasColormap, byte[][][] colormap) { // if the lump-read COLORMAP is shorter, we must allocate enough final int targetLength = hasColormap - ? Math.max(COLORMAP_STD_LENGTH_15, colormap[0].length) - : COLORMAP_STD_LENGTH_15; - + ? Math.max(COLORMAP_STD_LENGTH_15, colormap[0].length) + : COLORMAP_STD_LENGTH_15; + final short[][] targetColormap = new short[targetLength][PAL_NUM_COLORS]; return targetColormap; } - + /** * Copy selected colormap from COLORMAP lump with respect to palette * @param int[] stuff a 256-entry part of target colormap diff --git a/src/v/graphics/Lines.java b/src/v/graphics/Lines.java index 6006f952..6a42b00d 100644 --- a/src/v/graphics/Lines.java +++ b/src/v/graphics/Lines.java @@ -20,6 +20,7 @@ package v.graphics; public interface Lines { + /** * Bresenham's line algorithm modified to use custom Plotter * @@ -27,11 +28,14 @@ public interface Lines { * @param x2 * @param y2 */ - default void drawLine(Plotter plotter, int x1, int x2) { drawLine(plotter, x1, x2, 1, 1); } + default void drawLine(Plotter plotter, int x1, int x2) { + drawLine(plotter, x1, x2, 1, 1); + } + default void drawLine(Plotter plotter, int x2, int y2, int dupX, int dupY) { // delta of exact value and rounded value of the dependant variable int d = 0, dy, dx, ix, iy; - + { final int x = plotter.getX(), y = plotter.getY(); @@ -41,33 +45,39 @@ default void drawLine(Plotter plotter, int x2, int y2, int dupX, int dupY) { ix = x < x2 ? 1 : -1; // increment direction iy = y < y2 ? 1 : -1; } - + int dy2 = (dy << 1); // slope scaling factors to avoid floating int dx2 = (dx << 1); // point - + if (dy <= dx) { for (;;) { plotter.plot(); - if (plotter.getX() == x2) + if (plotter.getX() == x2) { break; + } d += dy2; if (d > dx) { plotter.shift(ix, iy); d -= dx2; - } else plotter.shiftX(ix); + } else { + plotter.shiftX(ix); + } } } else { for (;;) { plotter.plot(); - if (plotter.getY() == y2) + if (plotter.getY() == y2) { break; + } d += dx2; if (d > dy) { plotter.shift(ix, iy); d -= dy2; - } else plotter.shiftY(iy); + } else { + plotter.shiftY(iy); + } } } } - + } diff --git a/src/v/graphics/Melt.java b/src/v/graphics/Melt.java index d1c2f42c..aa263122 100644 --- a/src/v/graphics/Melt.java +++ b/src/v/graphics/Melt.java @@ -17,20 +17,26 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v.graphics; -import static utils.C2JUtils.*; +import static utils.C2JUtils.memcpy; public interface Melt extends ColorTransform { + /** * No more fucking column-major transpose! * A funny fast thing for 1993, but able to make Intel i7 think hard in 2017 * (well, at least, in energy saving mode :p) * - Good Sign, 2017/04/10 */ - default boolean initMeltScaled(Wipers.WiperImpl wiper) { return initMelt(wiper, true); } - default boolean initMelt(Wipers.WiperImpl wiper) { return initMelt(wiper, false); } + default boolean initMeltScaled(Wipers.WiperImpl wiper) { + return initMelt(wiper, true); + } + + default boolean initMelt(Wipers.WiperImpl wiper) { + return initMelt(wiper, false); + } + default boolean initMelt(Wipers.WiperImpl wiper, boolean scaled) { // copy start screen to main screen memcpy(wiper.wipeStartScr, wiper.wipeScr, wiper.screenWidth * wiper.screenHeight); @@ -57,7 +63,7 @@ default void setupColumnPositions(Wipers.WiperImpl wiper, boolean scaled) } } } - + /** * The only place where we cannot have generic code, because it is 1 pixel copy operation * which to be called tens thousands times and will cause overhead on just literally any more intermediate function @@ -85,9 +91,11 @@ default void toScreen(Class bufType, Object src, Object dest, int width, int final int iWidth = width * i; to[pd + iWidth] = from[ps + iWidth]; } - } else throw new UnsupportedOperationException("Do not have support for: " + bufType); + } else { + throw new UnsupportedOperationException("Do not have support for: " + bufType); + } } - + /** * Completely opposite of the previous method. Only performant when scaling is on. * Stick to System.arraycopy since there is certainly several pixels to get and set. @@ -101,18 +109,24 @@ default void toScreenScaled(Wipers.WiperImpl wiper, Object from, int dy, i System.arraycopy(from, ps + iWidth, wiper.wipeScr, pd + iWidth, wiper.dupy); } } - + /** * Scrolls down columns ready for scroll and those who aren't makes a bit more ready * Finally no more shitty transpose! * - Good Sign 2017/04/10 */ - default boolean doMeltScaled(Wipers.WiperImpl wiper) { return doMelt(wiper, true); } - default boolean doMelt(Wipers.WiperImpl wiper) { return doMelt(wiper, false); } + default boolean doMeltScaled(Wipers.WiperImpl wiper) { + return doMelt(wiper, true); + } + + default boolean doMelt(Wipers.WiperImpl wiper) { + return doMelt(wiper, false); + } + default boolean doMelt(Wipers.WiperImpl wiper, boolean scaled) { final int lim = scaled ? wiper.screenWidth / wiper.dupy : wiper.screenWidth; boolean done = true; - + while (wiper.ticks-- > 0) { for (int i = 0; i < lim; i++) { // Column won't start yet. @@ -121,24 +135,28 @@ default boolean doMelt(Wipers.WiperImpl wiper, boolean scaled) { done = false; } else if (wiper.y[i] < wiper.screenHeight) { int dy = (wiper.y[i] < wiper.scaled_16) ? wiper.y[i] + (scaled ? wiper.dupy : 1) : wiper.scaled_8; - if (wiper.y[i] + dy >= wiper.screenHeight) dy = wiper.screenHeight - wiper.y[i]; + if (wiper.y[i] + dy >= wiper.screenHeight) { + dy = wiper.screenHeight - wiper.y[i]; + } int pd = wiper.y[i] * wiper.screenWidth + (scaled ? i * wiper.dupx : i); // MAES: this part should draw the END SCREEN "behind" the melt. - if (scaled) + if (scaled) { toScreenScaled(wiper, wiper.wipeEndScr, dy, pd, pd); - else + } else { toScreen(wiper.bufferType, wiper.wipeScr, wiper.wipeEndScr, wiper.screenWidth, dy, pd, pd); - + } + wiper.y[i] += dy; pd += dy * wiper.screenWidth; // This draws a column shifted by y[i] - if (scaled) + if (scaled) { toScreenScaled(wiper, wiper.wipeStartScr, wiper.screenHeight - wiper.y[i], i * wiper.dupy, pd); - else + } else { toScreen(wiper.bufferType, wiper.wipeScr, wiper.wipeStartScr, wiper.screenWidth, wiper.screenHeight - wiper.y[i], i, pd); - + } + done = false; } } diff --git a/src/v/graphics/Palettes.java b/src/v/graphics/Palettes.java index 9cb73d69..ab273cd7 100644 --- a/src/v/graphics/Palettes.java +++ b/src/v/graphics/Palettes.java @@ -35,7 +35,7 @@ public interface Palettes extends Lights { * Maximum number of colors in palette */ static int PAL_NUM_COLORS = 256; - + /** * There is 256 colors in standard PALYPAL lump, 3 bytes for each color (RGB value) * totaling 256 * 3 = 768 bytes @@ -53,7 +53,6 @@ public interface Palettes extends Lights { /** * Methods to be used by implementor */ - /** * Perform any action necessary so that palettes get modified according to specified gamma. * Consider this a TIME CONSUMING operation, so don't call it unless really necessary. @@ -61,14 +60,14 @@ public interface Palettes extends Lights { * @param gammalevel */ void setUsegamma(int gammalevel); - + /** * Getter for gamma level * * @return */ int getUsegamma(); - + /** * Perform any action necessary so that the screen output uses the specified palette * Consider this a TIME CONSUMING operation, so don't call it unless really necessary. @@ -76,14 +75,14 @@ public interface Palettes extends Lights { * @param palette */ void setPalette(int palette); - + /** * Getter for palette * * @return */ int getPalette(); - + /** * Get the value corresponding to a base color (0-255). * Depending on the implementation this might be indexed, @@ -93,8 +92,10 @@ public interface Palettes extends Lights { */ int getBaseColor(byte color); - default int getBaseColor(int color) { return getBaseColor((byte) color); } - + default int getBaseColor(int color) { + return getBaseColor((byte) color); + } + /** * Extracts RGB888 color from an index in the palette * @param byte[] pal proper playpal @@ -104,7 +105,7 @@ public interface Palettes extends Lights { default int paletteToRGB888(byte[] pal, int index) { return toRGB888(pal[index], pal[index + 1], pal[index + 2]); } - + /** * Extracts RGB555 color from an index in the palette * @param byte[] pal proper playpal @@ -114,7 +115,7 @@ default int paletteToRGB888(byte[] pal, int index) { default short paletteToRGB555(byte[] pal, int index) { return rgb888to555(pal[index], pal[index + 1], pal[index + 2]); } - + /** * Extracts RGB888 color components from an index in the palette to the container * @param byte[] pal proper playpal @@ -128,7 +129,7 @@ default int[] getPaletteRGB888(byte[] pal, int index, int[] container) { container[2] = pal[index + 2] & 0xFF; return container; } - + /** * ColorShiftPalette - lifted from dcolors.c Operates on RGB888 palettes in * separate bytes. at shift = 0, the colors are normal at shift = steps, the @@ -156,16 +157,16 @@ default void ColorShiftPalette(byte[] inpal, byte[] outpal, int r, int g, int b, */ default int[] paletteTrueColor(byte[] pal) { final int pal888[] = new int[PAL_NUM_COLORS]; - + // Initial palette can be neutral or based upon "gamma 0", // which is actually a bit biased and distorted for (int x = 0; x < PAL_NUM_COLORS; ++x) { pal888[x] = paletteToRGB888(pal, x * PAL_NUM_STRIDES); } - + return pal888; } - + /** * Given raw palette data, returns an array with proper HiColor data * @param byte[] pal proper palette @@ -180,7 +181,7 @@ default short[] paletteHiColor(byte[] pal) { for (int x = 0; x < PAL_NUM_COLORS; ++x) { pal555[x] = paletteToRGB555(pal, x * PAL_NUM_STRIDES); } - + return pal555; } @@ -190,10 +191,10 @@ default short[] paletteHiColor(byte[] pal) { * @param IndexColorModel[][] cmaps preallocated array, as it is often reconstructed for gamma, do not reallocate it * @param byte[] pal proper palette * @return the same araay as input, but all values set to new IndexColorModels - */ + */ default IndexColorModel[][] cmapIndexed(IndexColorModel icms[][], byte[] pal) { final int colorsXstride = PAL_NUM_COLORS * PAL_NUM_STRIDES; - + // Now we have our palettes. for (int i = 0; i < icms[0].length; ++i) { //new IndexColorModel(8, PAL_NUM_COLORS, pal, i * colorsXstride, false); diff --git a/src/v/graphics/Patches.java b/src/v/graphics/Patches.java index 9f17c066..d72188c8 100644 --- a/src/v/graphics/Patches.java +++ b/src/v/graphics/Patches.java @@ -17,6 +17,7 @@ package v.graphics; import java.util.logging.Level; +import java.util.logging.Logger; import mochadoom.Loggers; import rr.patch_t; import utils.C2JUtils; @@ -56,6 +57,8 @@ */ public interface Patches> extends Columns { + static final Logger LOGGER = Loggers.getLogger(Patches.class.getName()); + /** * V_DrawPatch * @@ -64,7 +67,7 @@ public interface Patches> extends Columns { default void DrawPatch(E screen, patch_t patch, int x, int y, int... flags) { DrawPatchScaled(screen, patch, null, x, y, flags); } - + /** * V_DrawPatch * @@ -73,7 +76,7 @@ default void DrawPatch(E screen, patch_t patch, int x, int y, int... flags) { default void DrawPatchCentered(E screen, patch_t patch, int y, int... flags) { Patches.this.DrawPatchCenteredScaled(screen, patch, null, y, flags); } - + /** * V_DrawScaledPatch like V_DrawPatch, but scaled with IVideoScale object scaling * Centers the x coordinate on a screen based on patch width and offset @@ -82,7 +85,7 @@ default void DrawPatchCentered(E screen, patch_t patch, int y, int... flags) { * * It uses FLAGS (see above) (now as a separate - Good Sign 2017/04/04) parameter, to be * parsed afterwards. Shamelessly ripped from Doom Legacy (for menus, etc) by _D_ ;-) - */ + */ default void DrawPatchCenteredScaled(E screen, patch_t patch, VideoScale vs, int y, int... flags) { final int flagsV = flags.length > 0 ? flags[0] : 0; int dupx, dupy; @@ -93,7 +96,9 @@ default void DrawPatchCenteredScaled(E screen, patch_t patch, VideoScale vs, int dupx = vs.getScalingX(); dupy = vs.getScalingY(); } - } else dupx = dupy = 1; + } else { + dupx = dupy = 1; + } final boolean predevide = C2JUtils.flags(flagsV, V_PREDIVIDE); // By default we scale, if V_NOSCALEOFFSET we dont scale unless V_SCALEOFFSET (restores Default Behavior) final boolean scaleOffset = !C2JUtils.flags(flagsV, V_NOSCALEOFFSET) || C2JUtils.flags(flagsV, V_SCALEOFFSET); @@ -105,11 +110,11 @@ default void DrawPatchCenteredScaled(E screen, patch_t patch, VideoScale vs, int final int halfWidth = noScalePatch ? patch.width / 2 : patch.width * dupx / 2; int x = getScreenWidth() / 2 - halfWidth - (scaleOffset ? patch.leftoffset * dupx : patch.leftoffset); y = applyScaling(y, patch.topoffset, dupy, predevide, scaleOffset, scaleStart); - + if (noScalePatch) { dupx = dupy = 1; } - + try { doRangeCheck(x, y, patch, dupx, dupy); DrawPatchColumns(getScreen(screen), patch, x, y, dupx, dupy, flip); @@ -123,27 +128,27 @@ default void DrawPatchCenteredScaled(E screen, patch_t patch, VideoScale vs, int * - Good Sign 2017/04/22 */ default void printDebugPatchInfo(patch_t patch, int x, int y, final boolean predevide, final boolean scaleOffset, final boolean scaleStart, int dupx, int dupy) { - Loggers.getLogger(Patches.class.getName()).log(Level.INFO, () -> String.format( - "V_DrawPatch: bad patch (ignored)\n" + - "Patch %s at %d, %d exceeds LFB\n" + - "\tpredevide: %s\n" + - "\tscaleOffset: %s\n" + - "\tscaleStart: %s\n" + - "\tdupx: %s, dupy: %s\n" + - "\tleftoffset: %s\n" + - "\ttopoffset: %s\n", - patch.name, x, y, - predevide, scaleOffset, scaleStart, dupx, dupy, patch.leftoffset, patch.topoffset + LOGGER.log(Level.INFO, () -> String.format( + "V_DrawPatch: bad patch (ignored)\n" + + "Patch %s at %d, %d exceeds LFB\n" + + "\tpredevide: %s\n" + + "\tscaleOffset: %s\n" + + "\tscaleStart: %s\n" + + "\tdupx: %s, dupy: %s\n" + + "\tleftoffset: %s\n" + + "\ttopoffset: %s\n", + patch.name, x, y, + predevide, scaleOffset, scaleStart, dupx, dupy, patch.leftoffset, patch.topoffset )); } - + /** * V_DrawPatch * * V_DrawScaledPatch like V_DrawPatch, but scaled with IVideoScale object scaling * I have completely reworked column drawing code, so it resides in another class, and supports parallelism * - Good Sign 2017/04/04 - */ + */ default void DrawPatchScaled(E screen, patch_t patch, VideoScale vs, int x, int y, int... flags) { final int flagsV = flags.length > 0 ? flags[0] : 0; int dupx, dupy; @@ -154,7 +159,9 @@ default void DrawPatchScaled(E screen, patch_t patch, VideoScale vs, int x, int dupx = vs.getScalingX(); dupy = vs.getScalingY(); } - } else dupx = dupy = 1; + } else { + dupx = dupy = 1; + } final boolean predevide = C2JUtils.flags(flagsV, V_PREDIVIDE); // By default we scale, if V_NOSCALEOFFSET we dont scale unless V_SCALEOFFSET (restores Default Behavior) final boolean scaleOffset = !C2JUtils.flags(flagsV, V_NOSCALEOFFSET) || C2JUtils.flags(flagsV, V_SCALEOFFSET); @@ -165,11 +172,11 @@ default void DrawPatchScaled(E screen, patch_t patch, VideoScale vs, int x, int final boolean flip = C2JUtils.flags(flagsV, V_FLIPPEDPATCH); x = applyScaling(x, patch.leftoffset, dupx, predevide, scaleOffset, scaleStart); y = applyScaling(y, patch.topoffset, dupy, predevide, scaleOffset, scaleStart); - + if (noScalePatch) { dupx = dupy = 1; } - + try { doRangeCheck(x, y, patch, dupx, dupy); DrawPatchColumns(getScreen(screen), patch, x, y, dupx, dupy, flip); @@ -178,7 +185,7 @@ default void DrawPatchScaled(E screen, patch_t patch, VideoScale vs, int x, int printDebugPatchInfo(patch, x, y, predevide, scaleOffset, scaleStart, dupx, dupy); } } - + /** * Replaces DrawPatchCol for bunny scrolled in Finale. * Also uses my reworked column code, but that one is not parallelized @@ -188,26 +195,28 @@ default void DrawPatchColScaled(E screen, patch_t patch, VideoScale vs, int x, i final int dupx = vs.getScalingX(), dupy = vs.getScalingY(); x -= patch.leftoffset; x *= dupx; - + DrawColumn( - getScreen(screen), - patch.columns[col], - new Horizontal(point(x, 0), dupx), - convertPalettedBlock(patch.columns[col].data), - getScreenWidth(), - dupy + getScreen(screen), + patch.columns[col], + new Horizontal(point(x, 0), dupx), + convertPalettedBlock(patch.columns[col].data), + getScreenWidth(), + dupy ); } - + default int applyScaling(int c, int offset, int dup, boolean predevide, boolean scaleOffset, boolean scaleStart) { // A very common operation, eliminates the need to pre-divide. - if (predevide) + if (predevide) { c /= getScalingX(); - + } + // Scale start before offsetting, it seems right to do so - Good Sign 2017/04/04 - if (scaleStart) + if (scaleStart) { c *= dup; - + } + // MAES: added this fix so that non-zero patch offsets can be // taken into account, regardless of whether we use pre-scaled // coords or not. Only Doomguy's face needs this hack for now. diff --git a/src/v/graphics/Plotter.java b/src/v/graphics/Plotter.java index d432128a..c0c2b0e2 100644 --- a/src/v/graphics/Plotter.java +++ b/src/v/graphics/Plotter.java @@ -18,26 +18,40 @@ import java.lang.reflect.Array; import java.util.Objects; -import static utils.GenericCopy.*; -import static v.graphics.Direction.*; +import static utils.GenericCopy.memcpy; +import static utils.GenericCopy.memset; +import static v.graphics.Direction.CENTER; /** * * @author Good Sign */ public interface Plotter { - default Plotter setColorSource(V colorSource) {return setColorSource(colorSource, 0);} + + default Plotter setColorSource(V colorSource) { + return setColorSource(colorSource, 0); + } + Plotter setColorSource(V colorSource, int colorPos); + Plotter setPosition(int x, int y); + Plotter setThickness(int dupX, int dupY); + Plotter plot(); + Plotter shiftX(int shift); + Plotter shiftY(int shift); + int getX(); + int getY(); - - enum Style { Thin, Thick, Deep } - + + enum Style { + Thin, Thick, Deep + } + default Plotter shift(int shiftX, int shiftY) { return shiftX(shiftX).shiftY(shiftY); } @@ -46,6 +60,7 @@ default Plotter shift(int shiftX, int shiftY) { * Abstract plotter - without a Plot method */ abstract class Abstract implements Plotter { + protected final V screen; protected final int rowShift; @@ -69,7 +84,7 @@ public Plotter setColorSource(V colorSource, int colorPos) { memcpy(colorSource, colorPos, this.colorSource, 0, 1); return this; } - + @Override public Plotter setThickness(int dupX, int dupY) { return this; @@ -113,19 +128,20 @@ public int getY() { return y; } } - + class Thin extends Abstract { + public Thin(V screen, int rowShift) { super(screen, rowShift); } - + @Override public Plotter plot() { memcpy(colorSource, 0, screen, point, 1); return this; } } - + static int getThickness(int dupX) { return Math.max(dupX >> 1, 1); } @@ -134,14 +150,15 @@ static int getThickness(int dupX) { * You give it desired scaling level, it makes lines thicker */ class Thick extends Abstract { + protected final int height; protected int xThick; protected int yThick; - + public Thick(V screen, int width, int height) { super(screen, width); this.height = height; - + // can overflow! this.xThick = 1;//dupX >> 1; this.yThick = 1;//dupX >> 1; @@ -153,7 +170,7 @@ public Plotter setThickness(int dupX, int dupY) { this.yThick = dupY; return this; } - + @Override public Plotter plot() { if (xThick == 0 || yThick == 0) { @@ -162,17 +179,17 @@ public Plotter plot() { } return plotThick(xThick, yThick); } - + protected Plotter plotThick(int modThickX, int modThickY) { final int rows = y < modThickY ? y : (height < y + modThickY ? height - y : modThickY); final int spaceLeft = x < modThickX ? 0 : modThickX; final int spaceRight = rowShift < x + modThickX ? rowShift - x : modThickX; - + for (int row = -rows; row < rows; ++row) { // color = colorSource[Math.abs(row)] memset(screen, point - spaceLeft + rowShift * row, spaceLeft + spaceRight, colorSource, 0, 1); } - + return this; } } @@ -181,8 +198,9 @@ protected Plotter plotThick(int modThickX, int modThickY) { * Thick, but the direction of drawing is counted in - i.e., for round borders... */ class Deep extends Thick { + protected Direction direction; - + public Deep(V screen, int width, int height) { super(screen, width, height); } @@ -210,7 +228,7 @@ public Plotter shift(int shiftX, int shiftY) { direction = direction.rotation(shiftX, shiftY); return super.shift(shiftX, shiftY); } - + @Override public Plotter plot() { if (xThick <= 1 || yThick <= 1) { @@ -227,8 +245,8 @@ public Plotter plot() { if (!direction.hasLeft && !direction.hasRight) { modThickY >>= 1; } - + return plotThick(modThickX, modThickY); } } -} \ No newline at end of file +} diff --git a/src/v/graphics/Points.java b/src/v/graphics/Points.java index 603f6a79..85c5ea04 100644 --- a/src/v/graphics/Points.java +++ b/src/v/graphics/Points.java @@ -23,14 +23,15 @@ * @author Good Sign */ public interface Points> extends Screens { + default void doRangeCheck(int x, int y, int width, int height) throws BadRangeException { if (x >= 0 && y >= 0) { final int scrWidth = this.getScreenWidth(); final int scrHeight = this.getScreenHeight(); if (x + width > scrWidth || y + height > scrWidth) { throw new BadRangeException(String.format( - "Coordinates overflow screen space: (%d, %d, %d, %d) on screen %dx%d", - x, y, x + width, y + height, scrWidth, scrHeight) + "Coordinates overflow screen space: (%d, %d, %d, %d) on screen %dx%d", + x, y, x + width, y + height, scrWidth, scrHeight) ); } } else { @@ -45,11 +46,11 @@ default void doRangeCheck(int x, int y, patch_t patch) throws BadRangeException default void doRangeCheck(int x, int y, patch_t patch, int dupx, int dupy) throws BadRangeException { doRangeCheck(x, y, patch.width * dupx, patch.height * dupy); } - + default int point(int x, int y) { return y * getScreenWidth() + x; } - + default int point(int x, int y, int width) { return y * width + x; } diff --git a/src/v/graphics/Rectangles.java b/src/v/graphics/Rectangles.java index ef8b6585..dd0d9fa7 100644 --- a/src/v/graphics/Rectangles.java +++ b/src/v/graphics/Rectangles.java @@ -26,6 +26,7 @@ * @author Good Sign */ public interface Rectangles> extends Blocks, Points { + /** * Computes a Horizontal with a row from the Rectangle at heightIndex * @param rect @@ -36,14 +37,13 @@ default Horizontal GetRectRow(Rectangle rect, int heightIndex) { if (heightIndex < 0 || heightIndex > rect.height) { throw new IndexOutOfBoundsException("Bad row index: " + heightIndex); } - + return new Horizontal(point(rect.x, rect.y) + heightIndex * getScreenWidth(), rect.width); } - + /** * V_CopyRect */ - default void CopyRect(E srcScreenType, Rectangle rectangle, E dstScreenType) { final V srcScreen = getScreen(srcScreenType); final V dstScreen = getScreen(dstScreenType); @@ -54,7 +54,7 @@ default void CopyRect(E srcScreenType, Rectangle rectangle, E dstScreenType) { screenCopy(srcScreen, dstScreen, rel); } } - + default void CopyRect(E srcScreenType, Rectangle rectangle, E dstScreenType, int dstPoint) { final V srcScreen = getScreen(srcScreenType); final V dstScreen = getScreen(dstScreenType); @@ -64,11 +64,10 @@ default void CopyRect(E srcScreenType, Rectangle rectangle, E dstScreenType, int screenCopy(srcScreen, dstScreen, rel); } } - + /** * V_FillRect */ - default void FillRect(E screenType, Rectangle rectangle, V patternSrc, Horizontal pattern) { final V screen = getScreen(screenType); if (rectangle.height > 0) { @@ -90,8 +89,11 @@ default void FillRect(E screenType, Rectangle rectangle, V patternSrc, int point RepeatRow(screen, row, rectangle.height - 1); } } - - default void FillRect(E screenType, Rectangle rectangle, int color) {FillRect(screenType, rectangle, (byte) color);} + + default void FillRect(E screenType, Rectangle rectangle, int color) { + FillRect(screenType, rectangle, (byte) color); + } + default void FillRect(E screenType, Rectangle rectangle, byte color) { final V screen = getScreen(screenType); if (rectangle.height > 0) { diff --git a/src/v/graphics/Relocation.java b/src/v/graphics/Relocation.java index 378f3dc0..2c191aa3 100644 --- a/src/v/graphics/Relocation.java +++ b/src/v/graphics/Relocation.java @@ -23,7 +23,7 @@ * @author Good Sign */ public final class Relocation { - + public int source; public int destination; public int length; @@ -42,7 +42,7 @@ public Relocation shift(int amount) { this.destination += amount; return this; } - + public Relocation retarget(int source, int destination) { this.source = source; this.destination = destination; diff --git a/src/v/graphics/Screens.java b/src/v/graphics/Screens.java index bccc08b3..2a56b722 100644 --- a/src/v/graphics/Screens.java +++ b/src/v/graphics/Screens.java @@ -19,7 +19,8 @@ import f.Wiper; import java.lang.reflect.Array; import m.IRandom; -import static utils.GenericCopy.*; +import static utils.GenericCopy.memcpy; +import static utils.GenericCopy.memset; import v.renderers.DoomScreen; /** @@ -28,19 +29,24 @@ * @author Good Sign */ public interface Screens> { + final int SCREENS_COUNT = DoomScreen.values().length; - + V getScreen(E screenType); + int getScalingX(); + int getScalingY(); + int getScreenWidth(); + int getScreenHeight(); + Wiper createWiper(IRandom random); - + /** * memset-like methods for screen surfaces */ - /** * Will fill destPortion on the screen with color of the specified point on it * The point argument IS NOT a color to fill, only a POINTER to the pixel on the screen @@ -48,7 +54,7 @@ public interface Screens> { default void screenSet(V screen, int point, Horizontal destination) { memset(screen, destination.start, destination.length, screen, point, 1); } - + /** * Will fill destPortion on the dstScreen by scrPortion pattern from srcScreen */ @@ -77,19 +83,25 @@ default void screenSet(V screen, Horizontal pattern, Horizontal destination) { default void screenCopy(V srcScreen, V dstScreen, Relocation relocation) { memcpy(srcScreen, relocation.source, dstScreen, relocation.destination, relocation.length); } - + default void screenCopy(E srcScreen, E dstScreen) { final Object dstScreenObj = getScreen(dstScreen); memcpy(getScreen(srcScreen), 0, dstScreenObj, 0, Array.getLength(dstScreenObj)); } - + default Plotter createPlotter(E screen) { return new Plotter.Thin<>(getScreen(screen), getScreenWidth()); } - + class BadRangeException extends Exception { - private static final long serialVersionUID = 2903441181162189295L; - public BadRangeException(String m) { super(m);} - public BadRangeException() {} + + private static final long serialVersionUID = 2903441181162189295L; + + public BadRangeException(String m) { + super(m); + } + + public BadRangeException() { + } } } diff --git a/src/v/graphics/Wipers.java b/src/v/graphics/Wipers.java index 688b60cd..c5abae38 100644 --- a/src/v/graphics/Wipers.java +++ b/src/v/graphics/Wipers.java @@ -17,7 +17,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v.graphics; import f.Wiper; @@ -30,8 +29,9 @@ * SCREEN WIPE PACKAGE */ public class Wipers implements ColorTransform, Melt { + private static final Wipers instance = new Wipers(); - + /** * They are repeated thrice for a reason - they are overloads with different arguments * - Good Sign 2017/04/06 @@ -42,58 +42,59 @@ public enum WipeFunc { doColorXFormB(instance::colorTransformB, byte[].class), doColorXFormS(instance::colorTransformS, short[].class), doColorXFormI(instance::colorTransformI, int[].class), - initColorXForm(instance::initTransform), doColorXForm(doColorXFormB, doColorXFormS, doColorXFormI), exitColorXForm(w -> false), - initScaledMelt(instance::initMeltScaled), doScaledMelt(instance::doMeltScaled), - initMelt(instance::initMelt), doMelt(instance::doMelt), exitMelt(instance::exitMelt); - + private final Class supportFor; private final WF func; - + WipeFunc(WF func) { this.supportFor = null; this.func = func; } - + WipeFunc(WF func, Class supportFor) { this.supportFor = supportFor; this.func = func; } - + WipeFunc(final WipeFunc... wf) { this.supportFor = null; this.func = wipeChoice(wf); } - + private static WF wipeChoice(final WipeFunc[] wf) { - return (WiperImpl wiper) -> { - for (int i = 0; i < wf.length; ++i) { - if (wiper.bufferType == wf[i].supportFor) { - @SuppressWarnings("unchecked") // checked - final WF supported = (WF) wf[i].func; - return supported.invoke(wiper); - } - } - - throw new UnsupportedOperationException("Do not have support for: " + wiper.bufferType); - }; + return (WiperImpl wiper) -> { + for (int i = 0; i < wf.length; ++i) { + if (wiper.bufferType == wf[i].supportFor) { + @SuppressWarnings("unchecked") // checked + final WF supported = (WF) wf[i].func; + return supported.invoke(wiper); + } + } + + throw new UnsupportedOperationException("Do not have support for: " + wiper.bufferType); + }; + } + + interface WF { + + public boolean invoke(WiperImpl wiper); } - - interface WF { public boolean invoke(WiperImpl wiper); } } - + public static > Wiper createWiper(IRandom rnd, Screens screens, E ws, E we, E ms) { return new WiperImpl<>(rnd, screens, ws, we, ms); } - + protected final static class WiperImpl> implements Wiper { + private final Relocation relocation = new Relocation(0, 0, 1); final IRandom random; final Screens screens; @@ -127,7 +128,7 @@ private WiperImpl(IRandom RND, Screens screens, E wipeStartScreen, E wipeE this.scaled_16 = dupy << 4; this.scaled_8 = dupy << 3; } - + void startToScreen(int source, int destination) { screens.screenCopy(wipeStartScr, wipeScr, relocation.retarget(source, destination)); } @@ -156,10 +157,10 @@ public boolean EndScreen(int x, int y, int width, int height) { GenericCopy.memcpy(wipeStartScr, 0, wipeScr, 0, Array.getLength(wipeScr)); return false; } - + @SuppressWarnings("unchecked") - private boolean invokeCheckedFunc(WipeFunc f) { - return ((WF) f.func).invoke(this); + private boolean invokeCheckedFunc(WipeFunc f) { + return ((WF) f.func).invoke(this); } @Override @@ -168,7 +169,7 @@ public boolean ScreenWipe(WipeType type, int x, int y, int width, int height, in //System.out.println("Ticks do "+ticks); this.ticks = ticks; - + // initial stuff if (!go) { go = true; @@ -190,12 +191,16 @@ public boolean ScreenWipe(WipeType type, int x, int y, int width, int height, in return !go; } } - + public interface WipeType { + WipeFunc getInitFunc(); + WipeFunc getDoFunc(); + WipeFunc getExitFunc(); } - - private Wipers() {} + + private Wipers() { + } } diff --git a/src/v/renderers/BppMode.java b/src/v/renderers/BppMode.java index 9ccc0166..eba1c6bc 100644 --- a/src/v/renderers/BppMode.java +++ b/src/v/renderers/BppMode.java @@ -19,10 +19,10 @@ import doom.CVarManager; import doom.CommandVariable; import doom.DoomMain; -import mochadoom.Engine; import java.awt.Transparency; import java.util.function.Function; import m.Settings; +import mochadoom.Engine; import rr.SceneRenderer; import v.DoomGraphicSystem; @@ -35,7 +35,7 @@ public enum BppMode { HiColor(5, BufferedRenderer16::new, BppMode::SceneGen_16, Transparency.OPAQUE), TrueColor(8, BufferedRenderer32::new, BppMode::SceneGen_32, Transparency.OPAQUE), AlphaTrueColor(8, BufferedRenderer32::new, BppMode::SceneGen_32, Transparency.TRANSLUCENT); - + public final int transparency; public final int lightBits; final RenderGen renderGen; @@ -47,14 +47,14 @@ private BppMode(int lightBits, RenderGen renderGen, ScenerGen this.scenerGen = scenerGen; this.transparency = transparency; } - + @SuppressWarnings("unchecked") - public DoomGraphicSystem graphics(RendererFactory.WithWadLoader rf) { + public DoomGraphicSystem graphics(RendererFactory.WithWadLoader rf) { return ((RenderGen) renderGen).apply(rf); } @SuppressWarnings("unchecked") - public SceneRenderer sceneRenderer(DoomMain DOOM) { + public SceneRenderer sceneRenderer(DoomMain DOOM) { return ((ScenerGen) scenerGen).apply(DOOM); } @@ -71,22 +71,25 @@ public static BppMode chooseBppMode(CVarManager CVM) { return Engine.getConfig().getValue(Settings.color_depth, BppMode.class); } } - + @SuppressWarnings("unchecked") - private static SceneRenderer SceneGen_8(DoomMain DOOM) { + private static SceneRenderer SceneGen_8(DoomMain DOOM) { return (SceneRenderer) SceneRendererMode.getMode().indexedGen.apply((DoomMain) DOOM); } - + @SuppressWarnings("unchecked") private static SceneRenderer SceneGen_16(DoomMain DOOM) { return (SceneRenderer) SceneRendererMode.getMode().hicolorGen.apply((DoomMain) DOOM); } - + @SuppressWarnings("unchecked") private static SceneRenderer SceneGen_32(DoomMain DOOM) { return (SceneRenderer) SceneRendererMode.getMode().truecolorGen.apply((DoomMain) DOOM); } - - interface ScenerGen extends Function, SceneRenderer> {} - interface RenderGen extends Function, SoftwareGraphicsSystem> {} + + interface ScenerGen extends Function, SceneRenderer> { + } + + interface RenderGen extends Function, SoftwareGraphicsSystem> { + } } diff --git a/src/v/renderers/BufferedRenderer.java b/src/v/renderers/BufferedRenderer.java index a0be1e10..6bc4d20e 100644 --- a/src/v/renderers/BufferedRenderer.java +++ b/src/v/renderers/BufferedRenderer.java @@ -14,8 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - - package v.renderers; +package v.renderers; import java.awt.Point; import java.awt.image.BufferedImage; @@ -24,6 +23,7 @@ import java.awt.image.WritableRaster; class BufferedRenderer extends SoftwareIndexedVideoRenderer { + private final WritableRaster[] rasters = new WritableRaster[SCREENS_COUNT]; /** @@ -32,7 +32,7 @@ class BufferedRenderer extends SoftwareIndexedVideoRenderer { */ BufferedRenderer(RendererFactory.WithWadLoader rf) { super(rf); - for (DoomScreen s: DoomScreen.values()) { + for (DoomScreen s : DoomScreen.values()) { final int index = s.ordinal(); // Only create non-visible data, pegged to the raster. Create visible images only on-demand. final DataBufferByte db = (DataBufferByte) newBuffer(s); diff --git a/src/v/renderers/BufferedRenderer16.java b/src/v/renderers/BufferedRenderer16.java index 9de8820d..c776bb94 100644 --- a/src/v/renderers/BufferedRenderer16.java +++ b/src/v/renderers/BufferedRenderer16.java @@ -14,7 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v.renderers; import java.awt.Graphics2D; @@ -24,6 +23,7 @@ import java.awt.image.VolatileImage; import java.util.concurrent.BrokenBarrierException; import java.util.logging.Level; +import java.util.logging.Logger; import mochadoom.Loggers; import v.tables.BlurryTable; import v.tables.ColorTint; @@ -41,15 +41,18 @@ * - Good Sign 2017/04/12 */ class BufferedRenderer16 extends SoftwareParallelVideoRenderer { + + private static final Logger LOGGER = Loggers.getLogger(BufferedRenderer16.class.getName()); + protected final short[] raster; - + // VolatileImage speeds up delivery to VRAM - it is 30-40 fps faster then directly rendering BufferedImage protected VolatileImage screen; - + // indicated whether machine display in the same mode as this renderer protected final boolean compatible = checkConfigurationHicolor(); protected final BlurryTable blurryTable; - + /** * This implementation will "tie" a bufferedimage to the underlying byte raster. * @@ -69,11 +72,11 @@ class BufferedRenderer16 extends SoftwareParallelVideoRenderer } else { currentscreen = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_555_RGB); } - + // extract raster from the created image currentscreen.setAccelerationPriority(1.0f); - raster = ((DataBufferUShort)((BufferedImage) currentscreen).getRaster().getDataBuffer()).getData(); - + raster = ((DataBufferUShort) ((BufferedImage) currentscreen).getRaster().getDataBuffer()).getData(); + blurryTable = new BlurryTable(liteColorMaps); /** @@ -100,20 +103,22 @@ public Image getScreenImage() { doWriteScreen(); if (!compatible) { return currentscreen; - } else do { - if (screen.validate(GRAPHICS_CONF) == VolatileImage.IMAGE_INCOMPATIBLE) { - screen.flush(); - // old vImg doesn't work with new GraphicsConfig; re-create it - screen = GRAPHICS_CONF.createCompatibleVolatileImage(width, height); - } + } else { + do { + if (screen.validate(GRAPHICS_CONF) == VolatileImage.IMAGE_INCOMPATIBLE) { + screen.flush(); + // old vImg doesn't work with new GraphicsConfig; re-create it + screen = GRAPHICS_CONF.createCompatibleVolatileImage(width, height); + } - final Graphics2D g = screen.createGraphics(); - g.drawImage(currentscreen, 0, 0, null); - g.dispose(); - } while (screen.contentsLost()); + final Graphics2D g = screen.createGraphics(); + g.drawImage(currentscreen, 0, 0, null); + g.dispose(); + } while (screen.contentsLost()); + } return screen; } - + @Override void doWriteScreen() { for (int i = 0; i < PARALLELISM; i++) { @@ -122,7 +127,7 @@ void doWriteScreen() { try { updateBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { - Loggers.getLogger(BufferedRenderer32.class.getName()).log(Level.SEVERE, e, null); + LOGGER.log(Level.SEVERE, e, null); } } @@ -141,6 +146,7 @@ public BlurryTable getBlurryTable() { * - Good Sign 2017/04/12 */ private class ShortPaletteThread implements Runnable { + private final short[] FG; private final int start; private final int stop; @@ -182,7 +188,7 @@ public void run() { try { updateBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { - Loggers.getLogger(BufferedRenderer32.class.getName()).log(Level.WARNING, e, null); + LOGGER.log(Level.WARNING, e, null); } } } @@ -210,4 +216,4 @@ public void run() { // // Revision 1.2.2.1 2011/11/14 00:27:11 velktron // A barely functional HiColor branch. Most stuff broken. DO NOT USE -// \ No newline at end of file +// diff --git a/src/v/renderers/BufferedRenderer32.java b/src/v/renderers/BufferedRenderer32.java index a44dfa4c..4eb221cf 100644 --- a/src/v/renderers/BufferedRenderer32.java +++ b/src/v/renderers/BufferedRenderer32.java @@ -13,13 +13,12 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . - */ - + */ package v.renderers; import java.awt.Graphics2D; import java.awt.Image; -import static java.awt.Transparency.*; +import static java.awt.Transparency.TRANSLUCENT; import java.awt.image.BufferedImage; import static java.awt.image.BufferedImage.TYPE_INT_ARGB; import static java.awt.image.BufferedImage.TYPE_INT_RGB; @@ -27,6 +26,7 @@ import java.awt.image.VolatileImage; import java.util.concurrent.BrokenBarrierException; import java.util.logging.Level; +import java.util.logging.Logger; import mochadoom.Loggers; import v.tables.BlurryTable; import v.tables.ColorTint; @@ -43,16 +43,19 @@ * - Good Sign 2017/04/12 */ class BufferedRenderer32 extends SoftwareParallelVideoRenderer { + + private static final Logger LOGGER = Loggers.getLogger(BufferedRenderer32.class.getName()); + protected final int[] raster; - + // VolatileImage speeds up delivery to VRAM - it is 30-40 fps faster then directly rendering BufferedImage protected VolatileImage screen; - + // indicated whether machine display in the same mode as this renderer protected final boolean compatible = checkConfigurationTruecolor(); protected final int transparency; protected final BlurryTable blurryTable; - + /** * This implementation will "tie" a BufferedImage to the underlying byte raster. * @@ -61,7 +64,7 @@ class BufferedRenderer32 extends SoftwareParallelVideoRenderer { */ BufferedRenderer32(RendererFactory.WithWadLoader rf) { super(rf, int[].class); - + /** * Try to create as accelerated Images as possible - these would not lose * more performance from attempt (in contrast to 16-bit ones) @@ -75,15 +78,15 @@ class BufferedRenderer32 extends SoftwareParallelVideoRenderer { * still get accelerated */ currentscreen = compatible - ? GRAPHICS_CONF.createCompatibleImage(width, height, transparency) - : new BufferedImage(width, height, transparency == TRANSLUCENT ? TYPE_INT_ARGB : TYPE_INT_RGB); + ? GRAPHICS_CONF.createCompatibleImage(width, height, transparency) + : new BufferedImage(width, height, transparency == TRANSLUCENT ? TYPE_INT_ARGB : TYPE_INT_RGB); currentscreen.setAccelerationPriority(1.0f); - + // extract raster from the created image - raster = ((DataBufferInt)((BufferedImage) currentscreen).getRaster().getDataBuffer()).getData(); - + raster = ((DataBufferInt) ((BufferedImage) currentscreen).getRaster().getDataBuffer()).getData(); + blurryTable = new BlurryTable(liteColorMaps); - + /** * Create postprocess worker threads * 320 is dividable by 16, so any scale of it would @@ -122,7 +125,7 @@ void doWriteScreen() { try { updateBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { - Loggers.getLogger(BufferedRenderer32.class.getName()).log(Level.SEVERE, e, null); + LOGGER.log(Level.SEVERE, e, null); } final Graphics2D g = screen.createGraphics(); @@ -148,6 +151,7 @@ public BlurryTable getBlurryTable() { * - Good Sign 2017/04/12 */ private class IntPaletteThread implements Runnable { + private final int[] FG; private final int start; private final int stop; @@ -188,7 +192,7 @@ public void run() { try { updateBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { - Loggers.getLogger(BufferedRenderer32.class.getName()).log(Level.WARNING, e, null); + LOGGER.log(Level.WARNING, e, null); } } } @@ -216,4 +220,4 @@ public void run() { // // Revision 1.2.2.1 2011/11/14 00:27:11 velktron // A barely functional HiColor branch. Most stuff broken. DO NOT USE -// \ No newline at end of file +// diff --git a/src/v/renderers/DoomScreen.java b/src/v/renderers/DoomScreen.java index e5f346bf..890fb668 100644 --- a/src/v/renderers/DoomScreen.java +++ b/src/v/renderers/DoomScreen.java @@ -27,12 +27,12 @@ */ public enum DoomScreen { FG, BG, WS, WE, SB; - + @SuppressWarnings("unchecked") static Map mapScreensToBuffers(Class bufferType, int bufferLen) { return Arrays.stream(values()) - .collect(() -> new EnumMap<>(DoomScreen.class), - (map, screen) -> map.put(screen, (V) Array.newInstance(bufferType.getComponentType(), bufferLen)), - EnumMap::putAll); + .collect(() -> new EnumMap<>(DoomScreen.class), + (map, screen) -> map.put(screen, (V) Array.newInstance(bufferType.getComponentType(), bufferLen)), + EnumMap::putAll); } } diff --git a/src/v/renderers/RendererFactory.java b/src/v/renderers/RendererFactory.java index 28100129..a53c6555 100644 --- a/src/v/renderers/RendererFactory.java +++ b/src/v/renderers/RendererFactory.java @@ -29,19 +29,21 @@ * @author Good Sign */ public class RendererFactory { - private RendererFactory() {} - + + private RendererFactory() { + } + public static Clear newBuilder() { return new Builder<>(); } private static class Builder - implements Clear, WithVideoScale, WithBppMode, WithWadLoader - { + implements Clear, WithVideoScale, WithBppMode, WithWadLoader { + private IWadLoader wadLoader; private VideoScale videoScale; private BppMode bppMode; - + @Override public WithVideoScale setVideoScale(VideoScale videoScale) { this.videoScale = Objects.requireNonNull(videoScale); @@ -80,26 +82,36 @@ public IWadLoader getWadLoader() { return wadLoader; } } - + public interface Clear { + WithVideoScale setVideoScale(VideoScale videoScale); } public interface WithVideoScale { + WithBppMode setBppMode(BppMode bppMode); + VideoScale getVideoScale(); } - + public interface WithBppMode { + WithWadLoader setWadLoader(IWadLoader wadLoader); + VideoScale getVideoScale(); + BppMode getBppMode(); } - + public interface WithWadLoader { + DoomGraphicSystem build(); + VideoScale getVideoScale(); + BppMode getBppMode(); + IWadLoader getWadLoader(); } } diff --git a/src/v/renderers/SceneRendererMode.java b/src/v/renderers/SceneRendererMode.java index d75a3081..576c0e8d 100644 --- a/src/v/renderers/SceneRendererMode.java +++ b/src/v/renderers/SceneRendererMode.java @@ -33,16 +33,16 @@ public enum SceneRendererMode { Serial(UnifiedRenderer.Indexed::new, UnifiedRenderer.HiColor::new, UnifiedRenderer.TrueColor::new), Parallel(SceneRendererMode::Parallel_8, SceneRendererMode::Parallel_16, SceneRendererMode::Parallel_32), Parallel2(SceneRendererMode::Parallel2_8, SceneRendererMode::Parallel2_16, SceneRendererMode::Parallel2_32); - + private static final boolean cVarSerial = Engine.getCVM().bool(CommandVariable.SERIALRENDERER); private static final boolean cVarParallel = Engine.getCVM().present(CommandVariable.PARALLELRENDERER); private static final boolean cVarParallel2 = Engine.getCVM().present(CommandVariable.PARALLELRENDERER2); private static final int[] threads = cVarSerial ? null : cVarParallel - ? parseSwitchConfig(CommandVariable.PARALLELRENDERER) - : cVarParallel2 - ? parseSwitchConfig(CommandVariable.PARALLELRENDERER2) - : new int[]{2, 2, 2}; - + ? parseSwitchConfig(CommandVariable.PARALLELRENDERER) + : cVarParallel2 + ? parseSwitchConfig(CommandVariable.PARALLELRENDERER2) + : new int[]{2, 2, 2}; + final SG indexedGen; final SG hicolorGen; final SG truecolorGen; @@ -52,7 +52,7 @@ private SceneRendererMode(SG indexed, SG hi, SG this.hicolorGen = hi; this.truecolorGen = truecolor; } - + static int[] parseSwitchConfig(CommandVariable sw) { // Try parsing walls, or default to 1 final int walls = Engine.getCVM().get(sw, Integer.class, 0).orElse(1); @@ -62,7 +62,7 @@ static int[] parseSwitchConfig(CommandVariable sw) { final int masked = Engine.getCVM().get(sw, Integer.class, 2).orElse(2); return new int[]{walls, floors, masked}; } - + static SceneRendererMode getMode() { if (cVarSerial) { /** @@ -88,30 +88,31 @@ static SceneRendererMode getMode() { */ return Engine.getConfig().getValue(Settings.scene_renderer_mode, SceneRendererMode.class); } - + private static SceneRenderer Parallel_8(DoomMain DOOM) { return new ParallelRenderer.Indexed(DOOM, threads[0], threads[1], threads[2]); } - + private static SceneRenderer Parallel_16(DoomMain DOOM) { return new ParallelRenderer.HiColor(DOOM, threads[0], threads[1], threads[2]); } - + private static SceneRenderer Parallel_32(DoomMain DOOM) { return new ParallelRenderer.TrueColor(DOOM, threads[0], threads[1], threads[2]); } - + private static SceneRenderer Parallel2_8(DoomMain DOOM) { return new ParallelRenderer2.Indexed(DOOM, threads[0], threads[1], threads[2]); } - + private static SceneRenderer Parallel2_16(DoomMain DOOM) { return new ParallelRenderer2.HiColor(DOOM, threads[0], threads[1], threads[2]); } - + private static SceneRenderer Parallel2_32(DoomMain DOOM) { return new ParallelRenderer2.TrueColor(DOOM, threads[0], threads[1], threads[2]); } - - interface SG extends Function, SceneRenderer> {} + + interface SG extends Function, SceneRenderer> { + } } diff --git a/src/v/renderers/SoftwareGraphicsSystem.java b/src/v/renderers/SoftwareGraphicsSystem.java index 86c04df5..378872dc 100644 --- a/src/v/renderers/SoftwareGraphicsSystem.java +++ b/src/v/renderers/SoftwareGraphicsSystem.java @@ -39,7 +39,10 @@ import v.graphics.Rectangles; import v.graphics.Relocation; import v.graphics.Wipers; -import static v.renderers.DoomScreen.*; +import static v.renderers.DoomScreen.FG; +import static v.renderers.DoomScreen.WE; +import static v.renderers.DoomScreen.WS; +import static v.renderers.DoomScreen.mapScreensToBuffers; import v.scale.VideoScale; import v.tables.GammaTables; import v.tables.Playpal; @@ -55,8 +58,8 @@ * @author Good Sign */ abstract class SoftwareGraphicsSystem - implements DoomGraphicSystem, Rectangles, Blocks, Patches, Lines -{ + implements DoomGraphicSystem, Rectangles, Blocks, Patches, Lines { + /** * Each screen is [SCREENWIDTH*SCREENHEIGHT]; This is what the various modules (menu, automap, renderer etc.) get to * manipulate at the pixel level. To go beyond 8 bit displays, these must be extended @@ -103,118 +106,212 @@ abstract class SoftwareGraphicsSystem this.palette = palette(rf); this.liteColorMaps = colormap(rf); } - + @SuppressWarnings("unchecked") private V palette(RendererFactory.WithWadLoader rf) { - /*final byte[] */playpal = - Engine.getCVM().bool(CommandVariable.GREYPAL) + /*final byte[] */ + playpal + = Engine.getCVM().bool(CommandVariable.GREYPAL) ? Playpal.greypal() : Engine.getCVM().bool(CommandVariable.NOPLAYPAL) - ? Playpal.properPlaypal(null) - : rf.getWadLoader().LoadPlaypal(); - + ? Playpal.properPlaypal(null) + : rf.getWadLoader().LoadPlaypal(); + /** * In Indexed mode, read PLAYPAL lump can be used directly */ return bufferType == byte[].class - ? (V) playpal - - /** - * In HiColor or TrueColor translate PLAYPAL to real colors - */ - : bufferType == short[].class - ? (V) paletteHiColor(playpal) - : (V) paletteTrueColor(playpal); - } - + ? (V) playpal + /** + * In HiColor or TrueColor translate PLAYPAL to real colors + */ + : bufferType == short[].class + ? (V) paletteHiColor(playpal) + : (V) paletteTrueColor(playpal); + } + private byte[] playpal; - + @SuppressWarnings("unchecked") private V[] colormap(RendererFactory.WithWadLoader rf) { final boolean colormapEnabled = !Engine.getCVM().bool(CommandVariable.NOCOLORMAP) - && Engine.getConfig().equals(Settings.enable_colormap_lump, Boolean.TRUE); - - return - /** - * In Indexed mode, read COLORMAP lump can be used directly - */ - bufferType == byte[].class - ? colormapEnabled - ? (V[]) rf.getWadLoader().LoadColormap() - : (V[]) BuildLightsI(paletteTrueColor(playpal)) - - /** - * In HiColor or TrueColor generate colormaps with lights - */ - : bufferType == short[].class - ? colormapEnabled // HiColor, check for cfg setting and command line argument -nocolormap - ? (V[]) BuildLights15(paletteTrueColor(playpal), rf.getWadLoader().LoadColormap()) - : (V[]) BuildLights15(paletteTrueColor(playpal)) - : colormapEnabled // TrueColor, check for cfg setting and command line argument -nocolormap - ? (V[]) BuildLights24((int[]) palette, rf.getWadLoader().LoadColormap()) - : (V[]) BuildLights24((int[]) palette); + && Engine.getConfig().equals(Settings.enable_colormap_lump, Boolean.TRUE); + + return /** + * In Indexed mode, read COLORMAP lump can be used directly + */ + bufferType == byte[].class + ? colormapEnabled + ? (V[]) rf.getWadLoader().LoadColormap() + : (V[]) BuildLightsI(paletteTrueColor(playpal)) + /** + * In HiColor or TrueColor generate colormaps with lights + */ + : bufferType == short[].class + ? colormapEnabled // HiColor, check for cfg setting and command line argument -nocolormap + ? (V[]) BuildLights15(paletteTrueColor(playpal), rf.getWadLoader().LoadColormap()) + : (V[]) BuildLights15(paletteTrueColor(playpal)) + : colormapEnabled // TrueColor, check for cfg setting and command line argument -nocolormap + ? (V[]) BuildLights24((int[]) palette, rf.getWadLoader().LoadColormap()) + : (V[]) BuildLights24((int[]) palette); } /** * Getters */ - @Override public final int getUsegamma() { return usegamma; } - @Override public final int getPalette() { return usepalette; } - @Override public final int getScreenHeight() { return this.height; } - @Override public final int getScreenWidth() { return this.width; } - @Override public int getScalingX() { return vs.getScalingX(); } - @Override public int getScalingY() { return vs.getScalingY(); } - @Override public final V getScreen(DoomScreen screenType) { return screens.get(screenType); } - @Override public Image getScreenImage() { return currentscreen; /* may be null */ } + @Override + public final int getUsegamma() { + return usegamma; + } + + @Override + public final int getPalette() { + return usepalette; + } + + @Override + public final int getScreenHeight() { + return this.height; + } + + @Override + public final int getScreenWidth() { + return this.width; + } + + @Override + public int getScalingX() { + return vs.getScalingX(); + } + + @Override + public int getScalingY() { + return vs.getScalingY(); + } + + @Override + public final V getScreen(DoomScreen screenType) { + return screens.get(screenType); + } + + @Override + public Image getScreenImage() { + return currentscreen; + /* may be null */ } /** * API route delegating */ - @Override public void screenCopy(V srcScreen, V dstScreen, Relocation relocation) - {Rectangles.super.screenCopy(srcScreen, dstScreen, relocation);} - @Override public void screenCopy(DoomScreen srcScreen, DoomScreen dstScreen) - {Rectangles.super.screenCopy(srcScreen, dstScreen);} - @Override public int getBaseColor(int color) - {return Rectangles.super.getBaseColor(color);} - @Override public int point(int x, int y) - {return Rectangles.super.point(x, y);} - @Override public int point(int x, int y, int width) - {return Rectangles.super.point(x, y, width);} - @Override public void drawLine(Plotter plotter, int x1, int x2) - {Lines.super.drawLine(plotter, x1, x2);} - @Override public void DrawPatch(DoomScreen screen, patch_t patch, int x, int y, int... flags) - {Patches.super.DrawPatch(screen, patch, x, y, flags);} - @Override public void DrawPatchCentered(DoomScreen screen, patch_t patch, int y, int... flags) - {Patches.super.DrawPatchCentered(screen, patch, y, flags);} - @Override public void DrawPatchCenteredScaled(DoomScreen screen, patch_t patch, VideoScale vs, int y, int... flags) - {Patches.super.DrawPatchCenteredScaled(screen, patch, vs, y, flags);} - @Override public void DrawPatchScaled(DoomScreen screen, patch_t patch, VideoScale vs, int x, int y, int... flags) - {Patches.super.DrawPatchScaled(screen, patch, vs, x, y, flags);} - @Override public void DrawPatchColScaled(DoomScreen screen, patch_t patch, VideoScale vs, int x, int col) - {Patches.super.DrawPatchColScaled(screen, patch, vs, x, col);} - @Override public void CopyRect(DoomScreen srcScreenType, Rectangle rectangle, DoomScreen dstScreenType) - {Rectangles.super.CopyRect(srcScreenType, rectangle, dstScreenType);} - @Override public void CopyRect(DoomScreen srcScreenType, Rectangle rectangle, DoomScreen dstScreenType, int dstPoint) - {Rectangles.super.CopyRect(srcScreenType, rectangle, dstScreenType, dstPoint);} - @Override public void FillRect(DoomScreen screenType, Rectangle rectangle, V patternSrc, Horizontal pattern) - {Rectangles.super.FillRect(screenType, rectangle, patternSrc, pattern);} - @Override public void FillRect(DoomScreen screenType, Rectangle rectangle, V patternSrc, int point) - {Rectangles.super.FillRect(screenType, rectangle, patternSrc, point);} - @Override public void FillRect(DoomScreen screenType, Rectangle rectangle, int color) - {Rectangles.super.FillRect(screenType, rectangle, color);} - @Override public void FillRect(DoomScreen screenType, Rectangle rectangle, byte color) - {Rectangles.super.FillRect(screenType, rectangle, color);} - @Override public V ScaleBlock(V block, VideoScale vs, int width, int height) - {return Rectangles.super.ScaleBlock(block, vs, width, height);} - @Override public void TileScreen(DoomScreen dstScreen, V block, Rectangle blockArea) - {Rectangles.super.TileScreen(dstScreen, block, blockArea);} - @Override public void TileScreenArea(DoomScreen dstScreen, Rectangle screenArea, V block, Rectangle blockArea) - {Rectangles.super.TileScreenArea(dstScreen, screenArea, block, blockArea);} - @Override public void DrawBlock(DoomScreen dstScreen, V block, Rectangle sourceArea, int destinationPoint) - {Rectangles.super.DrawBlock(dstScreen, block, sourceArea, destinationPoint);} - @Override public Plotter createPlotter(DoomScreen screen) - {return DoomGraphicSystem.super.createPlotter(screen);} - + @Override + public void screenCopy(V srcScreen, V dstScreen, Relocation relocation) { + Rectangles.super.screenCopy(srcScreen, dstScreen, relocation); + } + + @Override + public void screenCopy(DoomScreen srcScreen, DoomScreen dstScreen) { + Rectangles.super.screenCopy(srcScreen, dstScreen); + } + + @Override + public int getBaseColor(int color) { + return Rectangles.super.getBaseColor(color); + } + + @Override + public int point(int x, int y) { + return Rectangles.super.point(x, y); + } + + @Override + public int point(int x, int y, int width) { + return Rectangles.super.point(x, y, width); + } + + @Override + public void drawLine(Plotter plotter, int x1, int x2) { + Lines.super.drawLine(plotter, x1, x2); + } + + @Override + public void DrawPatch(DoomScreen screen, patch_t patch, int x, int y, int... flags) { + Patches.super.DrawPatch(screen, patch, x, y, flags); + } + + @Override + public void DrawPatchCentered(DoomScreen screen, patch_t patch, int y, int... flags) { + Patches.super.DrawPatchCentered(screen, patch, y, flags); + } + + @Override + public void DrawPatchCenteredScaled(DoomScreen screen, patch_t patch, VideoScale vs, int y, int... flags) { + Patches.super.DrawPatchCenteredScaled(screen, patch, vs, y, flags); + } + + @Override + public void DrawPatchScaled(DoomScreen screen, patch_t patch, VideoScale vs, int x, int y, int... flags) { + Patches.super.DrawPatchScaled(screen, patch, vs, x, y, flags); + } + + @Override + public void DrawPatchColScaled(DoomScreen screen, patch_t patch, VideoScale vs, int x, int col) { + Patches.super.DrawPatchColScaled(screen, patch, vs, x, col); + } + + @Override + public void CopyRect(DoomScreen srcScreenType, Rectangle rectangle, DoomScreen dstScreenType) { + Rectangles.super.CopyRect(srcScreenType, rectangle, dstScreenType); + } + + @Override + public void CopyRect(DoomScreen srcScreenType, Rectangle rectangle, DoomScreen dstScreenType, int dstPoint) { + Rectangles.super.CopyRect(srcScreenType, rectangle, dstScreenType, dstPoint); + } + + @Override + public void FillRect(DoomScreen screenType, Rectangle rectangle, V patternSrc, Horizontal pattern) { + Rectangles.super.FillRect(screenType, rectangle, patternSrc, pattern); + } + + @Override + public void FillRect(DoomScreen screenType, Rectangle rectangle, V patternSrc, int point) { + Rectangles.super.FillRect(screenType, rectangle, patternSrc, point); + } + + @Override + public void FillRect(DoomScreen screenType, Rectangle rectangle, int color) { + Rectangles.super.FillRect(screenType, rectangle, color); + } + + @Override + public void FillRect(DoomScreen screenType, Rectangle rectangle, byte color) { + Rectangles.super.FillRect(screenType, rectangle, color); + } + + @Override + public V ScaleBlock(V block, VideoScale vs, int width, int height) { + return Rectangles.super.ScaleBlock(block, vs, width, height); + } + + @Override + public void TileScreen(DoomScreen dstScreen, V block, Rectangle blockArea) { + Rectangles.super.TileScreen(dstScreen, block, blockArea); + } + + @Override + public void TileScreenArea(DoomScreen dstScreen, Rectangle screenArea, V block, Rectangle blockArea) { + Rectangles.super.TileScreenArea(dstScreen, screenArea, block, blockArea); + } + + @Override + public void DrawBlock(DoomScreen dstScreen, V block, Rectangle sourceArea, int destinationPoint) { + Rectangles.super.DrawBlock(dstScreen, block, sourceArea, destinationPoint); + } + + @Override + public Plotter createPlotter(DoomScreen screen) { + return DoomGraphicSystem.super.createPlotter(screen); + } + /** * I_SetPalette * @@ -232,11 +329,11 @@ public void setPalette(int palette) { this.usepalette = palette % Palettes.NUM_PALETTES; this.forcePalette(); } - + @Override public void setUsegamma(int gamma) { this.usegamma = gamma % GammaTables.LUT.length; - + /** * Because of switching gamma stops powerup palette except for invlunerablity * Settings.fixgammapalette handles the fix @@ -244,7 +341,7 @@ public void setUsegamma(int gamma) { if (Engine.getConfig().equals(Settings.fix_gamma_palette, Boolean.FALSE)) { this.usepalette = 0; } - + this.forcePalette(); } @@ -252,7 +349,7 @@ public void setUsegamma(int gamma) { public V[] getColorMap() { return this.liteColorMaps; } - + public DataBuffer newBuffer(DoomScreen screen) { final V buffer = screens.get(screen); if (buffer.getClass() == int[].class) { @@ -262,7 +359,7 @@ public DataBuffer newBuffer(DoomScreen screen) { } else if (buffer.getClass() == byte[].class) { return new DataBufferByte((byte[]) buffer, ((byte[]) buffer).length); } - + throw new UnsupportedOperationException(String.format("SoftwareVideoRenderer does not support %s buffers", buffer.getClass())); } diff --git a/src/v/renderers/SoftwareIndexedVideoRenderer.java b/src/v/renderers/SoftwareIndexedVideoRenderer.java index b47e8c0f..4199546e 100644 --- a/src/v/renderers/SoftwareIndexedVideoRenderer.java +++ b/src/v/renderers/SoftwareIndexedVideoRenderer.java @@ -14,7 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v.renderers; import java.awt.image.IndexColorModel; @@ -37,7 +36,7 @@ abstract class SoftwareIndexedVideoRenderer extends SoftwareGraphicsSystem rf) { super(rf, byte[].class); - + /** * create gamma levels * Now we can reuse existing array of cmaps, not allocating more memory @@ -47,8 +46,15 @@ abstract class SoftwareIndexedVideoRenderer extends SoftwareGraphicsSystem. */ - package v.renderers; import doom.CommandVariable; -import mochadoom.Engine; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.image.ColorModel; @@ -29,6 +27,7 @@ import java.util.concurrent.Executors; import m.MenuMisc; import m.Settings; +import mochadoom.Engine; /** * Base for HiColor and TrueColor parallel renderers @@ -37,13 +36,14 @@ * @author velktron */ abstract class SoftwareParallelVideoRenderer extends SoftwareGraphicsSystem { + // How many threads it will use, but default it uses all avalable cores private static final int[] EMPTY_INT_PALETTED_BLOCK = new int[0]; private static final short[] EMPTY_SHORT_PALETTED_BLOCK = new short[0]; protected static final int PARALLELISM = Engine.getConfig().getValue(Settings.parallelism_realcolor_tint, Integer.class); protected static final GraphicsConfiguration GRAPHICS_CONF = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice().getDefaultConfiguration(); - + protected final boolean GRAYPAL_SET = Engine.getCVM().bool(CommandVariable.GREYPAL); /** @@ -65,7 +65,7 @@ static boolean checkConfigurationTruecolor() { final int cps = cm.getNumComponents(); return cps == 3 && cm.getComponentSize(0) == 8 && cm.getComponentSize(1) == 8 && cm.getComponentSize(2) == 8; } - + /** * We do not need to clear caches anymore - pallettes are applied on post-process * - Good Sign 2017/04/12 diff --git a/src/v/scale/VideoScale.java b/src/v/scale/VideoScale.java index 7b7fbbfb..7341367a 100644 --- a/src/v/scale/VideoScale.java +++ b/src/v/scale/VideoScale.java @@ -14,7 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v.scale; /** @@ -40,8 +39,11 @@ public interface VideoScale { public static final int BASE_HEIGHT = (int) (INV_ASPECT_RATIO * 320); // 200 int getScreenWidth(); + int getScreenHeight(); + int getScalingX(); + int getScalingY(); /** diff --git a/src/v/scale/VideoScaleInfo.java b/src/v/scale/VideoScaleInfo.java index 3920b85f..ea217def 100644 --- a/src/v/scale/VideoScaleInfo.java +++ b/src/v/scale/VideoScaleInfo.java @@ -14,26 +14,24 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v.scale; class VideoScaleInfo implements VideoScale { - - protected float scale; - protected int width; - protected int height; - protected int bestScaleX; - protected int bestScaleY; - protected int bestSafeScale; - - /** Scale is intended as a multiple of the base resolution, 320 x 200. - * If changing the ratio is also desired, then keep in mind that - * the base width is always considered fixed, while the base height - * is not. - * - * @param scale - */ - + + protected float scale; + protected int width; + protected int height; + protected int bestScaleX; + protected int bestScaleY; + protected int bestSafeScale; + + /** Scale is intended as a multiple of the base resolution, 320 x 200. + * If changing the ratio is also desired, then keep in mind that + * the base width is always considered fixed, while the base height + * is not. + * + * @param scale + */ public VideoScaleInfo(float scale) { this.scale = scale; width = (int) (BASE_WIDTH * scale); @@ -42,35 +40,34 @@ public VideoScaleInfo(float scale) { bestScaleY = (int) Math.floor((float) height / (float) BASE_HEIGHT); bestSafeScale = Math.min(bestScaleX, bestScaleY); } - - /** It's possible to specify other aspect ratios, too, keeping in mind - * that there are maximum width and height limits to take into account, - * and that scaling of graphics etc. will be rather problematic. Default - * ratio is 0.625, 0.75 will give a nice 4:3 ratio. - * - * TODO: pretty lame... - * - * @param scale - * @param ratio - */ - - public VideoScaleInfo(float scale, float ratio){ - this.scale=scale; - width=(int) (BASE_WIDTH*scale); - height=(int) (scale*BASE_WIDTH*ratio); - bestScaleX= (int) Math.floor((float)width/(float)BASE_WIDTH); - bestScaleY= (int) Math.floor((float)height/(float)BASE_HEIGHT); - bestSafeScale= Math.min(bestScaleX, bestScaleY); - - } - + + /** It's possible to specify other aspect ratios, too, keeping in mind + * that there are maximum width and height limits to take into account, + * and that scaling of graphics etc. will be rather problematic. Default + * ratio is 0.625, 0.75 will give a nice 4:3 ratio. + * + * TODO: pretty lame... + * + * @param scale + * @param ratio + */ + public VideoScaleInfo(float scale, float ratio) { + this.scale = scale; + width = (int) (BASE_WIDTH * scale); + height = (int) (scale * BASE_WIDTH * ratio); + bestScaleX = (int) Math.floor((float) width / (float) BASE_WIDTH); + bestScaleY = (int) Math.floor((float) height / (float) BASE_HEIGHT); + bestSafeScale = Math.min(bestScaleX, bestScaleY); + + } + @Override public int getScreenWidth() { return width; } @Override - public int getScreenHeight() { + public int getScreenHeight() { return height; } @@ -95,7 +92,7 @@ public boolean changed() { } @Override - public float getScreenMul() { + public float getScreenMul() { return scale; } diff --git a/src/v/scale/VisualSettings.java b/src/v/scale/VisualSettings.java index 368ff476..19aff5b8 100644 --- a/src/v/scale/VisualSettings.java +++ b/src/v/scale/VisualSettings.java @@ -14,7 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v.scale; import doom.CVarManager; @@ -27,16 +26,15 @@ public class VisualSettings { public final static VideoScale double_vanilla = new VideoScaleInfo(2.0f); public final static VideoScale triple_vanilla = new VideoScaleInfo(3.0f); public final static VideoScale default_scale = triple_vanilla; - + /** Parses the command line for resolution-specific commands, and creates * an appropriate IVideoScale object. * * @param CM * @return */ - - public final static VideoScale parse(CVarManager CVM){ - + public final static VideoScale parse(CVarManager CVM) { + { // check multiply // -multiply parameter defined from linux doom. // It gets priority over all others, if present. @@ -48,10 +46,10 @@ public final static VideoScale parse(CVarManager CVM){ return new VideoScaleInfo(multiply); } } // forget multiply - + // At least one of them is not a dud. final int mulx, muly, mulf; - + // check width & height final int width = CVM.get(CommandVariable.WIDTH, Integer.class, 0).orElse(-1); final int height = CVM.get(CommandVariable.HEIGHT, Integer.class, 0).orElse(-1); @@ -64,7 +62,7 @@ public final static VideoScale parse(CVarManager CVM){ // Break them down to the nearest multiple of the base width or height. mulx = Math.round((float) width / VideoScale.BASE_WIDTH); muly = Math.round((float) height / VideoScale.BASE_HEIGHT); - + // Do not accept zero or sub-vanilla resolutions if (mulx > 0 || muly > 0) { // Use the maximum multiplier. We don't support skewed @@ -74,7 +72,7 @@ public final static VideoScale parse(CVarManager CVM){ return new VideoScaleInfo(mulf); } } - + // In all other cases... return default_scale; } diff --git a/src/v/tables/BlurryTable.java b/src/v/tables/BlurryTable.java index 536db7d1..d32d39c3 100644 --- a/src/v/tables/BlurryTable.java +++ b/src/v/tables/BlurryTable.java @@ -22,7 +22,7 @@ import v.graphics.Colors; import static v.graphics.Lights.COLORMAP_BLURRY; import static v.graphics.Lights.COLORMAP_FIXED; -import static v.graphics.Palettes.*; +import static v.graphics.Palettes.PAL_NUM_COLORS; /** * Colormap-friendly vanilla-like BlurryMap for HiColor && TrueColor modes @@ -38,6 +38,7 @@ * @author Good Sign */ public class BlurryTable implements FuzzMix, Colors { + /** * Indexed LUT, e.g. classic "BLURRYMAP" (unaffected) */ @@ -51,10 +52,10 @@ public class BlurryTable implements FuzzMix, Colors { private final byte[] LUT_r5; private final byte[] LUT_g5; private final byte[] LUT_b5; - + private final boolean semiTranslucent = Engine.getConfig().equals(Settings.semi_translucent_fuzz, Boolean.TRUE); private final boolean fuzzMix = Engine.getConfig().equals(Settings.fuzz_mix, Boolean.TRUE); - + /** * Only support indexed "BLURRYMAP" with indexed colorMap * @param colorMap @@ -88,7 +89,7 @@ public BlurryTable(short[][] liteColorMaps) { * Prepare to sort colors - we will be using the ratio that is next close to apply for current color */ final TreeMap sortedRatios = new TreeMap<>(this::CompareColors555); - + for (int i = 0; i < PAL_NUM_COLORS; ++i) { // first get "BLURRYMAP" color components final int[] blurryColor = getRGB555(liteColorMaps[COLORMAP_BLURRY][i], new int[3]); @@ -100,29 +101,29 @@ public BlurryTable(short[][] liteColorMaps) { // get grayscale color components final int[] blurryAvg = getRGB555(avgColor, new int[3]); final int[] fixedAvg = getRGB555(avgOrig, new int[3]); - + // now, calculate the ratios final float ratioR = fixedAvg[0] > 0 ? blurryAvg[0] / (float) fixedAvg[0] : 0.0f, - ratioG = fixedAvg[1] > 0 ? blurryAvg[1] / (float) fixedAvg[1] : 0.0f, - ratioB = fixedAvg[2] > 0 ? blurryAvg[2] / (float) fixedAvg[2] : 0.0f; - + ratioG = fixedAvg[1] > 0 ? blurryAvg[1] / (float) fixedAvg[1] : 0.0f, + ratioB = fixedAvg[2] > 0 ? blurryAvg[2] / (float) fixedAvg[2] : 0.0f; + // best ratio is weighted towards red and blue, but should not be multiplied or it will be too dark final float bestRatio = GreyscaleFilter.component(ratioR, ratioG, ratioB);//ratioR * ratioR * ratioG * ratioB * ratioB; - + // associate normal color from colormaps avegrage with this ratio sortedRatios.put(avgOrig, bestRatio); } - + // now we have built our sorted maps, time to calculate color component mappings for (int i = 0; i <= 0x1F; ++i) { final short rgb555 = toRGB555(i, i, i); // now the best part - approximation. we just pick the closest grayscale color ratio final float ratio = sortedRatios.floorEntry(rgb555).getValue(); - LUT_r5[i] = LUT_g5[i] = LUT_b5[i] = (byte) ((int)(i * ratio) & 0x1F); + LUT_r5[i] = LUT_g5[i] = LUT_b5[i] = (byte) ((int) (i * ratio) & 0x1F); } // all done } - + /** * TrueColor BlurryTable will only support int[][] colormap * @param liteColorMaps @@ -136,12 +137,12 @@ public BlurryTable(int[][] liteColorMaps) { this.LUT_g8 = new byte[256]; this.LUT_r8 = new byte[256]; this.LUT_idx = null; - + /** * Prepare to sort colors - we will be using the ratio that is next close to apply for current color */ final TreeMap sortedRatios = new TreeMap<>(this::CompareColors888); - + for (int i = 0; i < PAL_NUM_COLORS; ++i) { // first get "BLURRYMAP" color components. 24 bit lighting is richer (256 vs 32) so we need to multiply final int[] blurryColor = getRGB888(liteColorMaps[COLORMAP_BLURRY << 3][i], new int[3]); @@ -153,31 +154,31 @@ public BlurryTable(int[][] liteColorMaps) { // get grayscale color components final int[] blurryAvg = getRGB888(avgColor, new int[3]); final int[] fixedAvg = getRGB888(avgOrig, new int[3]); - + // now, calculate the ratios final float ratioR = fixedAvg[0] > 0 ? blurryAvg[0] / (float) fixedAvg[0] : 0.0f, - ratioG = fixedAvg[1] > 0 ? blurryAvg[1] / (float) fixedAvg[1] : 0.0f, - ratioB = fixedAvg[2] > 0 ? blurryAvg[2] / (float) fixedAvg[2] : 0.0f; - + ratioG = fixedAvg[1] > 0 ? blurryAvg[1] / (float) fixedAvg[1] : 0.0f, + ratioB = fixedAvg[2] > 0 ? blurryAvg[2] / (float) fixedAvg[2] : 0.0f; + // weight ratio towards red and blue and multiply to make darker final float bestRatio = GreyscaleFilter.component(ratioR, ratioG, ratioB);//ratioR * ratioR * ratioG * ratioB * ratioB; - + // associate normal color from colormaps avegrage with this ratio sortedRatios.put(avgOrig, bestRatio); } - + // now we have built our sorted maps, time to calculate color component mappings for (int i = 0; i <= 0xFF; ++i) { final int rgb = toRGB888(i, i, i); // now the best part - approximation. we just pick the closest grayscale color ratio final float ratio = sortedRatios.floorEntry(rgb).getValue(); - LUT_r8[i] = LUT_g8[i] = LUT_b8[i] = (byte) ((int)(i * ratio) & 0xFF); + LUT_r8[i] = LUT_g8[i] = LUT_b8[i] = (byte) ((int) (i * ratio) & 0xFF); // for alpha it is different: we use the same ratio as for greyscale color, but the base alpha is min 50% LUT_a8[i] = (byte) (ratio * (Math.max(i, 0x7F) / (float) 0xFF) * 0xFF); } // all done } - + /** * For indexes */ @@ -195,7 +196,7 @@ public short computePixel(short pixel) { final int rgb[] = getRGB555(pixel, new int[4]); return toRGB555(LUT_r5[rgb[0]], LUT_g5[rgb[1]], LUT_b5[rgb[2]]); } - + /** * In high detail mode in AlphaTrueColor color mode will compute special greyscale-to-ratio translucency */ @@ -203,7 +204,7 @@ public int computePixel(int pixel) { if (fuzzMix) { // if blurry feature enabled, everything else does not apply return fuzzMixTrue(pixel); } - + if (!semiTranslucent) { return computePixelFast(pixel); } @@ -212,7 +213,7 @@ public int computePixel(int pixel) { argb[0] = Math.min(argb[0], GreyscaleFilter.component(argb[1], argb[2], argb[3])); return toARGB8888(LUT_a8[argb[0]], LUT_r8[argb[1]], LUT_g8[argb[2]], LUT_b8[argb[3]]); } - + /** * For low detail mode, do not compute translucency */ @@ -220,7 +221,7 @@ public int computePixelFast(int pixel) { if (fuzzMix) { // if blurry feature enabled, everything else does not apply return fuzzMixTrueLow(pixel); } - + final int rgb[] = getRGB888(pixel, new int[3]); return 0xFF000000 + (toRGB888(LUT_r8[rgb[0]], LUT_g8[rgb[1]], LUT_b8[rgb[2]]) & 0xFFFFFF); } diff --git a/src/v/tables/ColorTint.java b/src/v/tables/ColorTint.java index c34f9eec..3744c0ea 100644 --- a/src/v/tables/ColorTint.java +++ b/src/v/tables/ColorTint.java @@ -14,7 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v.tables; import java.util.Arrays; @@ -32,52 +31,50 @@ * - Good Sign */ public class ColorTint { - public final static ColorTint - NORMAL = new ColorTint(0, 0, 0, .0f), - RED_11 = new ColorTint(255, 2, 3, 0.11f), - RED_22 = new ColorTint(255, 0, 0, 0.22f), - RED_33 = new ColorTint(255, 0, 0, 0.33f), - RED_44 = new ColorTint(255, 0, 0, 0.44f), - RED_55 = new ColorTint(255, 0, 0, 0.55f), - RED_66 = new ColorTint(255, 0, 0, 0.66f), - RED_77 = new ColorTint(255, 0, 0, 0.77f), - RED_88 = new ColorTint(255, 0, 0, 0.88f), - BERSERK_SLIGHT = new ColorTint(215, 185, 68, 0.12f), - BERSERK_SOMEWHAT = new ColorTint(215, 185, 68, 0.25f), - BERSERK_NOTICABLE = new ColorTint(215, 185, 68, 0.375f), - BERSERK_HEAVY = new ColorTint(215, 185, 68, 0.50f), - RADSUIT = new ColorTint(3, 253, 3, 0.125f), - - GREY_NORMAL = new ColorTint(NORMAL.mid(), NORMAL.mid5(), NORMAL.purepart), - GREY_RED_11 = new ColorTint(RED_11.mid(), RED_11.mid5(), RED_11.purepart), - GREY_RED_22 = new ColorTint(RED_22.mid(), RED_22.mid5(), RED_22.purepart), - GREY_RED_33 = new ColorTint(RED_33.mid(), RED_33.mid5(), RED_33.purepart), - GREY_RED_44 = new ColorTint(RED_44.mid(), RED_44.mid5(), RED_44.purepart), - GREY_RED_55 = new ColorTint(RED_55.mid(), RED_55.mid5(), RED_55.purepart), - GREY_RED_66 = new ColorTint(RED_66.mid(), RED_66.mid5(), RED_66.purepart), - GREY_RED_77 = new ColorTint(RED_77.mid(), RED_77.mid5(), RED_77.purepart), - GREY_RED_88 = new ColorTint(RED_88.mid(), RED_88.mid5(), RED_88.purepart), - GREY_BERSERK_SLIGHT = new ColorTint(BERSERK_SLIGHT.mid(), BERSERK_SLIGHT.mid5(), BERSERK_SLIGHT.purepart), - GREY_BERSERK_SOMEWHAT = new ColorTint(BERSERK_SOMEWHAT.mid(), BERSERK_SOMEWHAT.mid5(), BERSERK_SOMEWHAT.purepart), - GREY_BERSERK_NOTICABLE = new ColorTint(BERSERK_NOTICABLE.mid(), BERSERK_NOTICABLE.mid5(), BERSERK_NOTICABLE.purepart), - GREY_BERSERK_HEAVY = new ColorTint(BERSERK_HEAVY.mid(), BERSERK_HEAVY.mid5(), BERSERK_HEAVY.purepart), - GREY_RADSUIT = new ColorTint(RADSUIT.mid(), RADSUIT.mid5(), RADSUIT.purepart); - + + public final static ColorTint NORMAL = new ColorTint(0, 0, 0, .0f), + RED_11 = new ColorTint(255, 2, 3, 0.11f), + RED_22 = new ColorTint(255, 0, 0, 0.22f), + RED_33 = new ColorTint(255, 0, 0, 0.33f), + RED_44 = new ColorTint(255, 0, 0, 0.44f), + RED_55 = new ColorTint(255, 0, 0, 0.55f), + RED_66 = new ColorTint(255, 0, 0, 0.66f), + RED_77 = new ColorTint(255, 0, 0, 0.77f), + RED_88 = new ColorTint(255, 0, 0, 0.88f), + BERSERK_SLIGHT = new ColorTint(215, 185, 68, 0.12f), + BERSERK_SOMEWHAT = new ColorTint(215, 185, 68, 0.25f), + BERSERK_NOTICABLE = new ColorTint(215, 185, 68, 0.375f), + BERSERK_HEAVY = new ColorTint(215, 185, 68, 0.50f), + RADSUIT = new ColorTint(3, 253, 3, 0.125f), + GREY_NORMAL = new ColorTint(NORMAL.mid(), NORMAL.mid5(), NORMAL.purepart), + GREY_RED_11 = new ColorTint(RED_11.mid(), RED_11.mid5(), RED_11.purepart), + GREY_RED_22 = new ColorTint(RED_22.mid(), RED_22.mid5(), RED_22.purepart), + GREY_RED_33 = new ColorTint(RED_33.mid(), RED_33.mid5(), RED_33.purepart), + GREY_RED_44 = new ColorTint(RED_44.mid(), RED_44.mid5(), RED_44.purepart), + GREY_RED_55 = new ColorTint(RED_55.mid(), RED_55.mid5(), RED_55.purepart), + GREY_RED_66 = new ColorTint(RED_66.mid(), RED_66.mid5(), RED_66.purepart), + GREY_RED_77 = new ColorTint(RED_77.mid(), RED_77.mid5(), RED_77.purepart), + GREY_RED_88 = new ColorTint(RED_88.mid(), RED_88.mid5(), RED_88.purepart), + GREY_BERSERK_SLIGHT = new ColorTint(BERSERK_SLIGHT.mid(), BERSERK_SLIGHT.mid5(), BERSERK_SLIGHT.purepart), + GREY_BERSERK_SOMEWHAT = new ColorTint(BERSERK_SOMEWHAT.mid(), BERSERK_SOMEWHAT.mid5(), BERSERK_SOMEWHAT.purepart), + GREY_BERSERK_NOTICABLE = new ColorTint(BERSERK_NOTICABLE.mid(), BERSERK_NOTICABLE.mid5(), BERSERK_NOTICABLE.purepart), + GREY_BERSERK_HEAVY = new ColorTint(BERSERK_HEAVY.mid(), BERSERK_HEAVY.mid5(), BERSERK_HEAVY.purepart), + GREY_RADSUIT = new ColorTint(RADSUIT.mid(), RADSUIT.mid5(), RADSUIT.purepart); + public static final List NORMAL_TINTS = Collections.unmodifiableList(Arrays.asList( - NORMAL, - RED_11, RED_22, RED_33, RED_44, RED_55, RED_66, RED_77, RED_88, - BERSERK_SLIGHT, BERSERK_SOMEWHAT, BERSERK_NOTICABLE, BERSERK_HEAVY, RADSUIT + NORMAL, + RED_11, RED_22, RED_33, RED_44, RED_55, RED_66, RED_77, RED_88, + BERSERK_SLIGHT, BERSERK_SOMEWHAT, BERSERK_NOTICABLE, BERSERK_HEAVY, RADSUIT )); - + public static final List GREY_TINTS = Collections.unmodifiableList(Arrays.asList( - GREY_NORMAL, - GREY_RED_11, GREY_RED_22, GREY_RED_33, GREY_RED_44, GREY_RED_55, GREY_RED_66, GREY_RED_77, GREY_RED_88, - GREY_BERSERK_SLIGHT, GREY_BERSERK_SOMEWHAT, GREY_BERSERK_NOTICABLE, GREY_BERSERK_HEAVY, GREY_RADSUIT + GREY_NORMAL, + GREY_RED_11, GREY_RED_22, GREY_RED_33, GREY_RED_44, GREY_RED_55, GREY_RED_66, GREY_RED_77, GREY_RED_88, + GREY_BERSERK_SLIGHT, GREY_BERSERK_SOMEWHAT, GREY_BERSERK_NOTICABLE, GREY_BERSERK_HEAVY, GREY_RADSUIT )); - + /*public static List generateTints(byte cmaps[][]) { }*/ - ColorTint(int r, int g, int b, float tint) { this(r * tint, (r >> 3) * tint, g * tint, (g >> 3) * tint, b * tint, (b >> 3) * tint, 1 - tint); } @@ -85,7 +82,7 @@ public class ColorTint { ColorTint(float mid8, float mid5, float purepart) { this(mid8, mid5, mid8, mid5, mid8, mid5, purepart); } - + ColorTint(float r, float r5, float g, float g5, float b, float b5, float purepart) { this.r = r; this.r5 = r5; @@ -117,7 +114,7 @@ public class ColorTint { public final byte[][] LUT_r5 = new byte[5][0x20]; public final byte[][] LUT_g5 = new byte[5][0x20]; public final byte[][] LUT_b5 = new byte[5][0x20]; - + public float mid() { return (r + g + b) / 3; } @@ -149,4 +146,4 @@ public final int tintRed8(int red8) { public final int tintRed5(int red5) { return Math.min((int) (red5 * purepart + r5), 0x1F); } -} \ No newline at end of file +} diff --git a/src/v/tables/FuzzMix.java b/src/v/tables/FuzzMix.java index d0c30ead..5c6d5b4f 100644 --- a/src/v/tables/FuzzMix.java +++ b/src/v/tables/FuzzMix.java @@ -28,8 +28,9 @@ * - Good Sign 2017/04/16 * * @author velktron -*/ + */ public interface FuzzMix { + /** * Was used by: * R_DrawFuzzColumn.HiColor @@ -38,7 +39,7 @@ public interface FuzzMix { * Now used by BlurryTable::computePixel * only if the option fuzz_mix enabled */ - default short fuzzMixHi(short rgb){ + default short fuzzMixHi(short rgb) { // super-fast half-brite trick // 3DEF and >> 1: ok hue, but too dark // 7BDE, no shift: good compromise @@ -55,7 +56,7 @@ default short fuzzMixHi(short rgb){ * * AX: This is what makes it blurry */ - default int fuzzMixTrue(int rgb){ + default int fuzzMixTrue(int rgb) { // Proper half-brite alpha! return rgb & 0x10FFFFFF; } diff --git a/src/v/tables/GammaTables.java b/src/v/tables/GammaTables.java index 7358be67..6f74df73 100644 --- a/src/v/tables/GammaTables.java +++ b/src/v/tables/GammaTables.java @@ -18,103 +18,101 @@ // // from v_video.c // - package v.tables; import m.Settings; import mochadoom.Engine; public class GammaTables { - // Now where did these came from? - public final static int[][] LUT = - { - {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, - 17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32, - 33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48, - 49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64, - 65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80, - 81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96, - 97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112, - 113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128, - 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, - 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, - 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175, - 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, - 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207, - 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, - 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239, - 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255}, - - {2,4,5,7,8,10,11,12,14,15,16,18,19,20,21,23,24,25,26,27,29,30,31, - 32,33,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,54,55, - 56,57,58,59,60,61,62,63,64,65,66,67,69,70,71,72,73,74,75,76,77, - 78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98, - 99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114, - 115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,129, - 130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145, - 146,147,148,148,149,150,151,152,153,154,155,156,157,158,159,160, - 161,162,163,163,164,165,166,167,168,169,170,171,172,173,174,175, - 175,176,177,178,179,180,181,182,183,184,185,186,186,187,188,189, - 190,191,192,193,194,195,196,196,197,198,199,200,201,202,203,204, - 205,205,206,207,208,209,210,211,212,213,214,214,215,216,217,218, - 219,220,221,222,222,223,224,225,226,227,228,229,230,230,231,232, - 233,234,235,236,237,237,238,239,240,241,242,243,244,245,245,246, - 247,248,249,250,251,252,252,253,254,255}, - - {4,7,9,11,13,15,17,19,21,22,24,26,27,29,30,32,33,35,36,38,39,40,42, - 43,45,46,47,48,50,51,52,54,55,56,57,59,60,61,62,63,65,66,67,68,69, - 70,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,92,93, - 94,95,96,97,98,100,101,102,103,104,105,106,107,108,109,110,111,112, - 113,114,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128, - 129,130,131,132,133,133,134,135,136,137,138,139,140,141,142,143,144, - 144,145,146,147,148,149,150,151,152,153,153,154,155,156,157,158,159, - 160,160,161,162,163,164,165,166,166,167,168,169,170,171,172,172,173, - 174,175,176,177,178,178,179,180,181,182,183,183,184,185,186,187,188, - 188,189,190,191,192,193,193,194,195,196,197,197,198,199,200,201,201, - 202,203,204,205,206,206,207,208,209,210,210,211,212,213,213,214,215, - 216,217,217,218,219,220,221,221,222,223,224,224,225,226,227,228,228, - 229,230,231,231,232,233,234,235,235,236,237,238,238,239,240,241,241, - 242,243,244,244,245,246,247,247,248,249,250,251,251,252,253,254,254, - 255}, - {8,12,16,19,22,24,27,29,31,34,36,38,40,41,43,45,47,49,50,52,53,55, - 57,58,60,61,63,64,65,67,68,70,71,72,74,75,76,77,79,80,81,82,84,85, - 86,87,88,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,107, - 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124, - 125,126,127,128,129,130,131,132,133,134,135,135,136,137,138,139,140, - 141,142,143,143,144,145,146,147,148,149,150,150,151,152,153,154,155, - 155,156,157,158,159,160,160,161,162,163,164,165,165,166,167,168,169, - 169,170,171,172,173,173,174,175,176,176,177,178,179,180,180,181,182, - 183,183,184,185,186,186,187,188,189,189,190,191,192,192,193,194,195, - 195,196,197,197,198,199,200,200,201,202,202,203,204,205,205,206,207, - 207,208,209,210,210,211,212,212,213,214,214,215,216,216,217,218,219, - 219,220,221,221,222,223,223,224,225,225,226,227,227,228,229,229,230, - 231,231,232,233,233,234,235,235,236,237,237,238,238,239,240,240,241, - 242,242,243,244,244,245,246,246,247,247,248,249,249,250,251,251,252, - 253,253,254,254,255}, + // Now where did these came from? + public final static int[][] LUT + = { + {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, + 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, + 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, + 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, + 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, + 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255}, + {2, 4, 5, 7, 8, 10, 11, 12, 14, 15, 16, 18, 19, 20, 21, 23, 24, 25, 26, 27, 29, 30, 31, + 32, 33, 34, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 69, 70, 71, 72, 73, 74, 75, 76, 77, + 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, + 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, + 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 129, + 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, + 146, 147, 148, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, + 161, 162, 163, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, + 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 186, 187, 188, 189, + 190, 191, 192, 193, 194, 195, 196, 196, 197, 198, 199, 200, 201, 202, 203, 204, + 205, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 214, 215, 216, 217, 218, + 219, 220, 221, 222, 222, 223, 224, 225, 226, 227, 228, 229, 230, 230, 231, 232, + 233, 234, 235, 236, 237, 237, 238, 239, 240, 241, 242, 243, 244, 245, 245, 246, + 247, 248, 249, 250, 251, 252, 252, 253, 254, 255}, + {4, 7, 9, 11, 13, 15, 17, 19, 21, 22, 24, 26, 27, 29, 30, 32, 33, 35, 36, 38, 39, 40, 42, + 43, 45, 46, 47, 48, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, + 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, + 113, 114, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, + 129, 130, 131, 132, 133, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, + 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 153, 154, 155, 156, 157, 158, 159, + 160, 160, 161, 162, 163, 164, 165, 166, 166, 167, 168, 169, 170, 171, 172, 172, 173, + 174, 175, 176, 177, 178, 178, 179, 180, 181, 182, 183, 183, 184, 185, 186, 187, 188, + 188, 189, 190, 191, 192, 193, 193, 194, 195, 196, 197, 197, 198, 199, 200, 201, 201, + 202, 203, 204, 205, 206, 206, 207, 208, 209, 210, 210, 211, 212, 213, 213, 214, 215, + 216, 217, 217, 218, 219, 220, 221, 221, 222, 223, 224, 224, 225, 226, 227, 228, 228, + 229, 230, 231, 231, 232, 233, 234, 235, 235, 236, 237, 238, 238, 239, 240, 241, 241, + 242, 243, 244, 244, 245, 246, 247, 247, 248, 249, 250, 251, 251, 252, 253, 254, 254, + 255}, + {8, 12, 16, 19, 22, 24, 27, 29, 31, 34, 36, 38, 40, 41, 43, 45, 47, 49, 50, 52, 53, 55, + 57, 58, 60, 61, 63, 64, 65, 67, 68, 70, 71, 72, 74, 75, 76, 77, 79, 80, 81, 82, 84, 85, + 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, + 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, + 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 135, 136, 137, 138, 139, 140, + 141, 142, 143, 143, 144, 145, 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, + 155, 156, 157, 158, 159, 160, 160, 161, 162, 163, 164, 165, 165, 166, 167, 168, 169, + 169, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 179, 180, 180, 181, 182, + 183, 183, 184, 185, 186, 186, 187, 188, 189, 189, 190, 191, 192, 192, 193, 194, 195, + 195, 196, 197, 197, 198, 199, 200, 200, 201, 202, 202, 203, 204, 205, 205, 206, 207, + 207, 208, 209, 210, 210, 211, 212, 212, 213, 214, 214, 215, 216, 216, 217, 218, 219, + 219, 220, 221, 221, 222, 223, 223, 224, 225, 225, 226, 227, 227, 228, 229, 229, 230, + 231, 231, 232, 233, 233, 234, 235, 235, 236, 237, 237, 238, 238, 239, 240, 240, 241, + 242, 242, 243, 244, 244, 245, 246, 246, 247, 247, 248, 249, 249, 250, 251, 251, 252, + 253, 253, 254, 254, 255}, + {16, 23, 28, 32, 36, 39, 42, 45, 48, 50, 53, 55, 57, 60, 62, 64, 66, 68, 69, 71, 73, 75, 76, + 78, 80, 81, 83, 84, 86, 87, 89, 90, 92, 93, 94, 96, 97, 98, 100, 101, 102, 103, 105, 106, + 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, + 125, 126, 128, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, + 142, 143, 143, 144, 145, 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155, + 156, 157, 158, 159, 159, 160, 161, 162, 163, 163, 164, 165, 166, 166, 167, 168, 169, + 169, 170, 171, 172, 172, 173, 174, 175, 175, 176, 177, 177, 178, 179, 180, 180, 181, + 182, 182, 183, 184, 184, 185, 186, 187, 187, 188, 189, 189, 190, 191, 191, 192, 193, + 193, 194, 195, 195, 196, 196, 197, 198, 198, 199, 200, 200, 201, 202, 202, 203, 203, + 204, 205, 205, 206, 207, 207, 208, 208, 209, 210, 210, 211, 211, 212, 213, 213, 214, + 214, 215, 216, 216, 217, 217, 218, 219, 219, 220, 220, 221, 221, 222, 223, 223, 224, + 224, 225, 225, 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 232, 232, 233, 233, + 234, 234, 235, 235, 236, 236, 237, 237, 238, 239, 239, 240, 240, 241, 241, 242, 242, + 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 248, 248, 249, 249, 250, 250, 251, + 251, 252, 252, 253, 254, 254, 255, 255} + }; - {16,23,28,32,36,39,42,45,48,50,53,55,57,60,62,64,66,68,69,71,73,75,76, - 78,80,81,83,84,86,87,89,90,92,93,94,96,97,98,100,101,102,103,105,106, - 107,108,109,110,112,113,114,115,116,117,118,119,120,121,122,123,124, - 125,126,128,128,129,130,131,132,133,134,135,136,137,138,139,140,141, - 142,143,143,144,145,146,147,148,149,150,150,151,152,153,154,155,155, - 156,157,158,159,159,160,161,162,163,163,164,165,166,166,167,168,169, - 169,170,171,172,172,173,174,175,175,176,177,177,178,179,180,180,181, - 182,182,183,184,184,185,186,187,187,188,189,189,190,191,191,192,193, - 193,194,195,195,196,196,197,198,198,199,200,200,201,202,202,203,203, - 204,205,205,206,207,207,208,208,209,210,210,211,211,212,213,213,214, - 214,215,216,216,217,217,218,219,219,220,220,221,221,222,223,223,224, - 224,225,225,226,227,227,228,228,229,229,230,230,231,232,232,233,233, - 234,234,235,235,236,236,237,237,238,239,239,240,240,241,241,242,242, - 243,243,244,244,245,245,246,246,247,247,248,248,249,249,250,250,251, - 251,252,252,253,254,254,255,255} - }; - static { if (Engine.getConfig().equals(Settings.fix_gamma_ramp, Boolean.TRUE)) { - for (int i = 0; i < 128; --LUT[0][i++]) {} + for (int i = 0; i < 128; --LUT[0][i++]) { + } } } - - private GammaTables() {} + + private GammaTables() { + } } diff --git a/src/v/tables/GreyscaleFilter.java b/src/v/tables/GreyscaleFilter.java index 77427405..f0caf2c7 100644 --- a/src/v/tables/GreyscaleFilter.java +++ b/src/v/tables/GreyscaleFilter.java @@ -28,23 +28,23 @@ public enum GreyscaleFilter { Average, Luminance, // this one is the default for invulnerability map Luminosity; - + private static GreyscaleFilter FILTER; - + public static int component(int r, int g, int b) { if (FILTER == null) { readSetting(); } return FILTER.getComponent(r, g, b); } - + public static float component(float r, float g, float b) { if (FILTER == null) { readSetting(); } return FILTER.getComponent(r, g, b); } - + public static int grey888(int rgb888) { if (FILTER == null) { readSetting(); @@ -76,9 +76,9 @@ public static short grey555(short rgb555) { private static void readSetting() { FILTER = Engine.getConfig().getValue(Settings.greyscale_filter, GreyscaleFilter.class); } - + public int getComponent(int r, int g, int b) { - switch(this) { + switch (this) { case Lightness: return (Math.max(Math.max(r, g), b) + Math.min(Math.min(r, g), b)) / 2; case Average: @@ -88,13 +88,13 @@ public int getComponent(int r, int g, int b) { case Luminosity: return (int) (0.2126f * r + 0.7152f * g + 0.0722f * b); } - + // should not happen return 0; } - + public float getComponent(float r, float g, float b) { - switch(this) { + switch (this) { case Lightness: return (Math.max(Math.max(r, g), b) + Math.min(Math.min(r, g), b)) / 2; case Average: @@ -104,25 +104,25 @@ public float getComponent(float r, float g, float b) { case Luminosity: return 0.2126f * r + 0.7152f * g + 0.0722f * b; } - + // should not happen return 0.0f; } - + public int getGrey888(int r8, int g8, int b8) { final int component = getComponent(r8, g8, b8) & 0xFF; return 0xFF000000 + (component << 16) + (component << 8) + component; } - - public short getGrey555(int r5, int g5, int b5){ + + public short getGrey555(int r5, int g5, int b5) { final int component = getComponent(r5, g5, b5) & 0x1F; return (short) ((component << 10) + (component << 5) + component); } - + public int getGrey888(int rgb888) { return getGrey888((rgb888 >> 16) & 0xFF, (rgb888 >> 8) & 0xFF, rgb888 & 0xFF); } - + public short getGrey555(short rgb555) { return getGrey555((rgb555 >> 10) & 0x1F, (rgb555 >> 5) & 0x1F, rgb555 & 0x1F); } diff --git a/src/v/tables/LightsAndColors.java b/src/v/tables/LightsAndColors.java index 08a1c4d4..fb71ed6f 100644 --- a/src/v/tables/LightsAndColors.java +++ b/src/v/tables/LightsAndColors.java @@ -14,7 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v.tables; import doom.DoomMain; @@ -32,16 +31,14 @@ * * @param The data type of the SCREEN */ - public class LightsAndColors { - + private final LCData LC_DATA; - + /** For HiColor, these are, effectively, a bunch of 555 RGB palettes, * for TrueColor they are a bunch of 32-bit ARGB palettes etc. * Only for indexed they represent index remappings. */ - /** "peg" this to the one from RendererData */ public V[] colormaps; @@ -50,12 +47,12 @@ public class LightsAndColors { /** Use in conjunction with player.fixedcolormap */ public V fixedcolormap; - - /** - * Color tables for different players, translate a limited part to another - * (color ramps used for suit colors). - */ - public byte[][] translationtables; + + /** + * Color tables for different players, translate a limited part to another + * (color ramps used for suit colors). + */ + public byte[][] translationtables; // bumped light from gun blasts public int extralight; @@ -104,7 +101,7 @@ public int maxLightZ() { public int numColorMaps() { return LC_DATA.NUMCOLORMAPS; } - + /** * player_t.fixedcolormap have a range of 0..31 in vanilla. * We must respect it. However, we can have more lightlevels then vanilla. @@ -117,7 +114,7 @@ public V getFixedColormap(player_t player) { if (LC_DATA.bpp.lightBits > 5) { return colormaps[player.fixedcolormap << (LC_DATA.bpp.lightBits - 5)]; } - + return colormaps[player.fixedcolormap]; } @@ -126,8 +123,9 @@ public final byte[] getTranslationTable(long mobjflags) { } private static class LCData { + final BppMode bpp; - + /** * These two are tied by an inverse relationship. E.g. 256 levels, 0 shift * 128 levels, 1 shift ...etc... 16 levels, 4 shift (default). Or even less, @@ -138,28 +136,21 @@ private static class LCData { * levels, you also put more memory pressure, and due to their being only * 256 colors to begin with, visually, there won't be many differences. */ - - final int LIGHTLEVELS; final int LIGHTSEGSHIFT; - /** Number of diminishing brightness levels. There a 0-31, i.e. 32 LUT in the COLORMAP lump. TODO: how can those be distinct from the light levels??? - */ - + */ final int NUMCOLORMAPS; - // These are a bit more tricky to figure out though. - /** Maximum index used for light levels of sprites. In practice, * it's capped by the number of light levels??? * * Normally set to 48 (32 +16???) */ - final int MAXLIGHTSCALE; /** Used to scale brightness of walls and sprites. Their "scale" is shifted by @@ -172,7 +163,6 @@ private static class LCData { /** This one seems arbitrary. Will auto-fit to 128 possible levels? */ final int MAXLIGHTZ; - final int LIGHTBRIGHT; /** Normally 20 for 32 colormaps, applied to distance. @@ -193,4 +183,4 @@ private static class LCData { LIGHTZSHIFT = 25 - bpp.lightBits; } } -} \ No newline at end of file +} diff --git a/src/v/tables/Playpal.java b/src/v/tables/Playpal.java index 9ea2c975..799bd5b4 100644 --- a/src/v/tables/Playpal.java +++ b/src/v/tables/Playpal.java @@ -14,13 +14,13 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package v.tables; import java.util.stream.IntStream; import v.graphics.Palettes; -import static v.graphics.Palettes.*; -import static v.tables.ColorTint.*; +import static v.graphics.Palettes.NUM_PALETTES; +import static v.graphics.Palettes.PAL_NUM_COLORS; +import static v.tables.ColorTint.NORMAL_TINTS; /** * Palette generation failsafe. Uses only data from the first palette, and @@ -28,78 +28,79 @@ * from: http://doom.wikia.com/wiki/PLAYPAL */ public class Playpal { - private final static int playpal[] = { 0x00, 0x00, 0x00, 0x1F, 0x17, 0x0B, - 0x17, 0x0F, 0x07, 0x4B, 0x4B, 0x4B, 0xFF, 0xFF, 0xFF, 0x1B, 0x1B, - 0x1B, 0x13, 0x13, 0x13, 0x0B, 0x0B, 0x0B, 0x07, 0x07, 0x07, 0x2F, - 0x37, 0x1F, 0x23, 0x2B, 0x0F, 0x17, 0x1F, 0x07, 0x0F, 0x17, 0x00, - 0x4F, 0x3B, 0x2B, 0x47, 0x33, 0x23, 0x3F, 0x2B, 0x1B, 0xFF, 0xB7, - 0xB7, 0xF7, 0xAB, 0xAB, 0xF3, 0xA3, 0xA3, 0xEB, 0x97, 0x97, 0xE7, - 0x8F, 0x8F, 0xDF, 0x87, 0x87, 0xDB, 0x7B, 0x7B, 0xD3, 0x73, 0x73, - 0xCB, 0x6B, 0x6B, 0xC7, 0x63, 0x63, 0xBF, 0x5B, 0x5B, 0xBB, 0x57, - 0x57, 0xB3, 0x4F, 0x4F, 0xAF, 0x47, 0x47, 0xA7, 0x3F, 0x3F, 0xA3, - 0x3B, 0x3B, 0x9B, 0x33, 0x33, 0x97, 0x2F, 0x2F, 0x8F, 0x2B, 0x2B, - 0x8B, 0x23, 0x23, 0x83, 0x1F, 0x1F, 0x7F, 0x1B, 0x1B, 0x77, 0x17, - 0x17, 0x73, 0x13, 0x13, 0x6B, 0x0F, 0x0F, 0x67, 0x0B, 0x0B, 0x5F, - 0x07, 0x07, 0x5B, 0x07, 0x07, 0x53, 0x07, 0x07, 0x4F, 0x00, 0x00, - 0x47, 0x00, 0x00, 0x43, 0x00, 0x00, 0xFF, 0xEB, 0xDF, 0xFF, 0xE3, - 0xD3, 0xFF, 0xDB, 0xC7, 0xFF, 0xD3, 0xBB, 0xFF, 0xCF, 0xB3, 0xFF, - 0xC7, 0xA7, 0xFF, 0xBF, 0x9B, 0xFF, 0xBB, 0x93, 0xFF, 0xB3, 0x83, - 0xF7, 0xAB, 0x7B, 0xEF, 0xA3, 0x73, 0xE7, 0x9B, 0x6B, 0xDF, 0x93, - 0x63, 0xD7, 0x8B, 0x5B, 0xCF, 0x83, 0x53, 0xCB, 0x7F, 0x4F, 0xBF, - 0x7B, 0x4B, 0xB3, 0x73, 0x47, 0xAB, 0x6F, 0x43, 0xA3, 0x6B, 0x3F, - 0x9B, 0x63, 0x3B, 0x8F, 0x5F, 0x37, 0x87, 0x57, 0x33, 0x7F, 0x53, - 0x2F, 0x77, 0x4F, 0x2B, 0x6B, 0x47, 0x27, 0x5F, 0x43, 0x23, 0x53, - 0x3F, 0x1F, 0x4B, 0x37, 0x1B, 0x3F, 0x2F, 0x17, 0x33, 0x2B, 0x13, - 0x2B, 0x23, 0x0F, 0xEF, 0xEF, 0xEF, 0xE7, 0xE7, 0xE7, 0xDF, 0xDF, - 0xDF, 0xDB, 0xDB, 0xDB, 0xD3, 0xD3, 0xD3, 0xCB, 0xCB, 0xCB, 0xC7, - 0xC7, 0xC7, 0xBF, 0xBF, 0xBF, 0xB7, 0xB7, 0xB7, 0xB3, 0xB3, 0xB3, - 0xAB, 0xAB, 0xAB, 0xA7, 0xA7, 0xA7, 0x9F, 0x9F, 0x9F, 0x97, 0x97, - 0x97, 0x93, 0x93, 0x93, 0x8B, 0x8B, 0x8B, 0x83, 0x83, 0x83, 0x7F, - 0x7F, 0x7F, 0x77, 0x77, 0x77, 0x6F, 0x6F, 0x6F, 0x6B, 0x6B, 0x6B, - 0x63, 0x63, 0x63, 0x5B, 0x5B, 0x5B, 0x57, 0x57, 0x57, 0x4F, 0x4F, - 0x4F, 0x47, 0x47, 0x47, 0x43, 0x43, 0x43, 0x3B, 0x3B, 0x3B, 0x37, - 0x37, 0x37, 0x2F, 0x2F, 0x2F, 0x27, 0x27, 0x27, 0x23, 0x23, 0x23, - 0x77, 0xFF, 0x6F, 0x6F, 0xEF, 0x67, 0x67, 0xDF, 0x5F, 0x5F, 0xCF, - 0x57, 0x5B, 0xBF, 0x4F, 0x53, 0xAF, 0x47, 0x4B, 0x9F, 0x3F, 0x43, - 0x93, 0x37, 0x3F, 0x83, 0x2F, 0x37, 0x73, 0x2B, 0x2F, 0x63, 0x23, - 0x27, 0x53, 0x1B, 0x1F, 0x43, 0x17, 0x17, 0x33, 0x0F, 0x13, 0x23, - 0x0B, 0x0B, 0x17, 0x07, 0xBF, 0xA7, 0x8F, 0xB7, 0x9F, 0x87, 0xAF, - 0x97, 0x7F, 0xA7, 0x8F, 0x77, 0x9F, 0x87, 0x6F, 0x9B, 0x7F, 0x6B, - 0x93, 0x7B, 0x63, 0x8B, 0x73, 0x5B, 0x83, 0x6B, 0x57, 0x7B, 0x63, - 0x4F, 0x77, 0x5F, 0x4B, 0x6F, 0x57, 0x43, 0x67, 0x53, 0x3F, 0x5F, - 0x4B, 0x37, 0x57, 0x43, 0x33, 0x53, 0x3F, 0x2F, 0x9F, 0x83, 0x63, - 0x8F, 0x77, 0x53, 0x83, 0x6B, 0x4B, 0x77, 0x5F, 0x3F, 0x67, 0x53, - 0x33, 0x5B, 0x47, 0x2B, 0x4F, 0x3B, 0x23, 0x43, 0x33, 0x1B, 0x7B, - 0x7F, 0x63, 0x6F, 0x73, 0x57, 0x67, 0x6B, 0x4F, 0x5B, 0x63, 0x47, - 0x53, 0x57, 0x3B, 0x47, 0x4F, 0x33, 0x3F, 0x47, 0x2B, 0x37, 0x3F, - 0x27, 0xFF, 0xFF, 0x73, 0xEB, 0xDB, 0x57, 0xD7, 0xBB, 0x43, 0xC3, - 0x9B, 0x2F, 0xAF, 0x7B, 0x1F, 0x9B, 0x5B, 0x13, 0x87, 0x43, 0x07, - 0x73, 0x2B, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xDB, 0xDB, 0xFF, 0xBB, - 0xBB, 0xFF, 0x9B, 0x9B, 0xFF, 0x7B, 0x7B, 0xFF, 0x5F, 0x5F, 0xFF, - 0x3F, 0x3F, 0xFF, 0x1F, 0x1F, 0xFF, 0x00, 0x00, 0xEF, 0x00, 0x00, - 0xE3, 0x00, 0x00, 0xD7, 0x00, 0x00, 0xCB, 0x00, 0x00, 0xBF, 0x00, - 0x00, 0xB3, 0x00, 0x00, 0xA7, 0x00, 0x00, 0x9B, 0x00, 0x00, 0x8B, - 0x00, 0x00, 0x7F, 0x00, 0x00, 0x73, 0x00, 0x00, 0x67, 0x00, 0x00, - 0x5B, 0x00, 0x00, 0x4F, 0x00, 0x00, 0x43, 0x00, 0x00, 0xE7, 0xE7, - 0xFF, 0xC7, 0xC7, 0xFF, 0xAB, 0xAB, 0xFF, 0x8F, 0x8F, 0xFF, 0x73, - 0x73, 0xFF, 0x53, 0x53, 0xFF, 0x37, 0x37, 0xFF, 0x1B, 0x1B, 0xFF, - 0x00, 0x00, 0xFF, 0x00, 0x00, 0xE3, 0x00, 0x00, 0xCB, 0x00, 0x00, - 0xB3, 0x00, 0x00, 0x9B, 0x00, 0x00, 0x83, 0x00, 0x00, 0x6B, 0x00, - 0x00, 0x53, 0xFF, 0xFF, 0xFF, 0xFF, 0xEB, 0xDB, 0xFF, 0xD7, 0xBB, - 0xFF, 0xC7, 0x9B, 0xFF, 0xB3, 0x7B, 0xFF, 0xA3, 0x5B, 0xFF, 0x8F, - 0x3B, 0xFF, 0x7F, 0x1B, 0xF3, 0x73, 0x17, 0xEB, 0x6F, 0x0F, 0xDF, - 0x67, 0x0F, 0xD7, 0x5F, 0x0B, 0xCB, 0x57, 0x07, 0xC3, 0x4F, 0x00, - 0xB7, 0x47, 0x00, 0xAF, 0x43, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xD7, 0xFF, 0xFF, 0xB3, 0xFF, 0xFF, 0x8F, 0xFF, 0xFF, 0x6B, 0xFF, - 0xFF, 0x47, 0xFF, 0xFF, 0x23, 0xFF, 0xFF, 0x00, 0xA7, 0x3F, 0x00, - 0x9F, 0x37, 0x00, 0x93, 0x2F, 0x00, 0x87, 0x23, 0x00, 0x4F, 0x3B, - 0x27, 0x43, 0x2F, 0x1B, 0x37, 0x23, 0x13, 0x2F, 0x1B, 0x0B, 0x00, - 0x00, 0x53, 0x00, 0x00, 0x47, 0x00, 0x00, 0x3B, 0x00, 0x00, 0x2F, - 0x00, 0x00, 0x23, 0x00, 0x00, 0x17, 0x00, 0x00, 0x0B, 0x00, 0x00, - 0x00, 0xFF, 0x9F, 0x43, 0xFF, 0xE7, 0x4B, 0xFF, 0x7B, 0xFF, 0xFF, - 0x00, 0xFF, 0xCF, 0x00, 0xCF, 0x9F, 0x00, 0x9B, 0x6F, 0x00, 0x6B, - 0xA7, 0x6B, 0x6B }; - + + private final static int playpal[] = {0x00, 0x00, 0x00, 0x1F, 0x17, 0x0B, + 0x17, 0x0F, 0x07, 0x4B, 0x4B, 0x4B, 0xFF, 0xFF, 0xFF, 0x1B, 0x1B, + 0x1B, 0x13, 0x13, 0x13, 0x0B, 0x0B, 0x0B, 0x07, 0x07, 0x07, 0x2F, + 0x37, 0x1F, 0x23, 0x2B, 0x0F, 0x17, 0x1F, 0x07, 0x0F, 0x17, 0x00, + 0x4F, 0x3B, 0x2B, 0x47, 0x33, 0x23, 0x3F, 0x2B, 0x1B, 0xFF, 0xB7, + 0xB7, 0xF7, 0xAB, 0xAB, 0xF3, 0xA3, 0xA3, 0xEB, 0x97, 0x97, 0xE7, + 0x8F, 0x8F, 0xDF, 0x87, 0x87, 0xDB, 0x7B, 0x7B, 0xD3, 0x73, 0x73, + 0xCB, 0x6B, 0x6B, 0xC7, 0x63, 0x63, 0xBF, 0x5B, 0x5B, 0xBB, 0x57, + 0x57, 0xB3, 0x4F, 0x4F, 0xAF, 0x47, 0x47, 0xA7, 0x3F, 0x3F, 0xA3, + 0x3B, 0x3B, 0x9B, 0x33, 0x33, 0x97, 0x2F, 0x2F, 0x8F, 0x2B, 0x2B, + 0x8B, 0x23, 0x23, 0x83, 0x1F, 0x1F, 0x7F, 0x1B, 0x1B, 0x77, 0x17, + 0x17, 0x73, 0x13, 0x13, 0x6B, 0x0F, 0x0F, 0x67, 0x0B, 0x0B, 0x5F, + 0x07, 0x07, 0x5B, 0x07, 0x07, 0x53, 0x07, 0x07, 0x4F, 0x00, 0x00, + 0x47, 0x00, 0x00, 0x43, 0x00, 0x00, 0xFF, 0xEB, 0xDF, 0xFF, 0xE3, + 0xD3, 0xFF, 0xDB, 0xC7, 0xFF, 0xD3, 0xBB, 0xFF, 0xCF, 0xB3, 0xFF, + 0xC7, 0xA7, 0xFF, 0xBF, 0x9B, 0xFF, 0xBB, 0x93, 0xFF, 0xB3, 0x83, + 0xF7, 0xAB, 0x7B, 0xEF, 0xA3, 0x73, 0xE7, 0x9B, 0x6B, 0xDF, 0x93, + 0x63, 0xD7, 0x8B, 0x5B, 0xCF, 0x83, 0x53, 0xCB, 0x7F, 0x4F, 0xBF, + 0x7B, 0x4B, 0xB3, 0x73, 0x47, 0xAB, 0x6F, 0x43, 0xA3, 0x6B, 0x3F, + 0x9B, 0x63, 0x3B, 0x8F, 0x5F, 0x37, 0x87, 0x57, 0x33, 0x7F, 0x53, + 0x2F, 0x77, 0x4F, 0x2B, 0x6B, 0x47, 0x27, 0x5F, 0x43, 0x23, 0x53, + 0x3F, 0x1F, 0x4B, 0x37, 0x1B, 0x3F, 0x2F, 0x17, 0x33, 0x2B, 0x13, + 0x2B, 0x23, 0x0F, 0xEF, 0xEF, 0xEF, 0xE7, 0xE7, 0xE7, 0xDF, 0xDF, + 0xDF, 0xDB, 0xDB, 0xDB, 0xD3, 0xD3, 0xD3, 0xCB, 0xCB, 0xCB, 0xC7, + 0xC7, 0xC7, 0xBF, 0xBF, 0xBF, 0xB7, 0xB7, 0xB7, 0xB3, 0xB3, 0xB3, + 0xAB, 0xAB, 0xAB, 0xA7, 0xA7, 0xA7, 0x9F, 0x9F, 0x9F, 0x97, 0x97, + 0x97, 0x93, 0x93, 0x93, 0x8B, 0x8B, 0x8B, 0x83, 0x83, 0x83, 0x7F, + 0x7F, 0x7F, 0x77, 0x77, 0x77, 0x6F, 0x6F, 0x6F, 0x6B, 0x6B, 0x6B, + 0x63, 0x63, 0x63, 0x5B, 0x5B, 0x5B, 0x57, 0x57, 0x57, 0x4F, 0x4F, + 0x4F, 0x47, 0x47, 0x47, 0x43, 0x43, 0x43, 0x3B, 0x3B, 0x3B, 0x37, + 0x37, 0x37, 0x2F, 0x2F, 0x2F, 0x27, 0x27, 0x27, 0x23, 0x23, 0x23, + 0x77, 0xFF, 0x6F, 0x6F, 0xEF, 0x67, 0x67, 0xDF, 0x5F, 0x5F, 0xCF, + 0x57, 0x5B, 0xBF, 0x4F, 0x53, 0xAF, 0x47, 0x4B, 0x9F, 0x3F, 0x43, + 0x93, 0x37, 0x3F, 0x83, 0x2F, 0x37, 0x73, 0x2B, 0x2F, 0x63, 0x23, + 0x27, 0x53, 0x1B, 0x1F, 0x43, 0x17, 0x17, 0x33, 0x0F, 0x13, 0x23, + 0x0B, 0x0B, 0x17, 0x07, 0xBF, 0xA7, 0x8F, 0xB7, 0x9F, 0x87, 0xAF, + 0x97, 0x7F, 0xA7, 0x8F, 0x77, 0x9F, 0x87, 0x6F, 0x9B, 0x7F, 0x6B, + 0x93, 0x7B, 0x63, 0x8B, 0x73, 0x5B, 0x83, 0x6B, 0x57, 0x7B, 0x63, + 0x4F, 0x77, 0x5F, 0x4B, 0x6F, 0x57, 0x43, 0x67, 0x53, 0x3F, 0x5F, + 0x4B, 0x37, 0x57, 0x43, 0x33, 0x53, 0x3F, 0x2F, 0x9F, 0x83, 0x63, + 0x8F, 0x77, 0x53, 0x83, 0x6B, 0x4B, 0x77, 0x5F, 0x3F, 0x67, 0x53, + 0x33, 0x5B, 0x47, 0x2B, 0x4F, 0x3B, 0x23, 0x43, 0x33, 0x1B, 0x7B, + 0x7F, 0x63, 0x6F, 0x73, 0x57, 0x67, 0x6B, 0x4F, 0x5B, 0x63, 0x47, + 0x53, 0x57, 0x3B, 0x47, 0x4F, 0x33, 0x3F, 0x47, 0x2B, 0x37, 0x3F, + 0x27, 0xFF, 0xFF, 0x73, 0xEB, 0xDB, 0x57, 0xD7, 0xBB, 0x43, 0xC3, + 0x9B, 0x2F, 0xAF, 0x7B, 0x1F, 0x9B, 0x5B, 0x13, 0x87, 0x43, 0x07, + 0x73, 0x2B, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xDB, 0xDB, 0xFF, 0xBB, + 0xBB, 0xFF, 0x9B, 0x9B, 0xFF, 0x7B, 0x7B, 0xFF, 0x5F, 0x5F, 0xFF, + 0x3F, 0x3F, 0xFF, 0x1F, 0x1F, 0xFF, 0x00, 0x00, 0xEF, 0x00, 0x00, + 0xE3, 0x00, 0x00, 0xD7, 0x00, 0x00, 0xCB, 0x00, 0x00, 0xBF, 0x00, + 0x00, 0xB3, 0x00, 0x00, 0xA7, 0x00, 0x00, 0x9B, 0x00, 0x00, 0x8B, + 0x00, 0x00, 0x7F, 0x00, 0x00, 0x73, 0x00, 0x00, 0x67, 0x00, 0x00, + 0x5B, 0x00, 0x00, 0x4F, 0x00, 0x00, 0x43, 0x00, 0x00, 0xE7, 0xE7, + 0xFF, 0xC7, 0xC7, 0xFF, 0xAB, 0xAB, 0xFF, 0x8F, 0x8F, 0xFF, 0x73, + 0x73, 0xFF, 0x53, 0x53, 0xFF, 0x37, 0x37, 0xFF, 0x1B, 0x1B, 0xFF, + 0x00, 0x00, 0xFF, 0x00, 0x00, 0xE3, 0x00, 0x00, 0xCB, 0x00, 0x00, + 0xB3, 0x00, 0x00, 0x9B, 0x00, 0x00, 0x83, 0x00, 0x00, 0x6B, 0x00, + 0x00, 0x53, 0xFF, 0xFF, 0xFF, 0xFF, 0xEB, 0xDB, 0xFF, 0xD7, 0xBB, + 0xFF, 0xC7, 0x9B, 0xFF, 0xB3, 0x7B, 0xFF, 0xA3, 0x5B, 0xFF, 0x8F, + 0x3B, 0xFF, 0x7F, 0x1B, 0xF3, 0x73, 0x17, 0xEB, 0x6F, 0x0F, 0xDF, + 0x67, 0x0F, 0xD7, 0x5F, 0x0B, 0xCB, 0x57, 0x07, 0xC3, 0x4F, 0x00, + 0xB7, 0x47, 0x00, 0xAF, 0x43, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xD7, 0xFF, 0xFF, 0xB3, 0xFF, 0xFF, 0x8F, 0xFF, 0xFF, 0x6B, 0xFF, + 0xFF, 0x47, 0xFF, 0xFF, 0x23, 0xFF, 0xFF, 0x00, 0xA7, 0x3F, 0x00, + 0x9F, 0x37, 0x00, 0x93, 0x2F, 0x00, 0x87, 0x23, 0x00, 0x4F, 0x3B, + 0x27, 0x43, 0x2F, 0x1B, 0x37, 0x23, 0x13, 0x2F, 0x1B, 0x0B, 0x00, + 0x00, 0x53, 0x00, 0x00, 0x47, 0x00, 0x00, 0x3B, 0x00, 0x00, 0x2F, + 0x00, 0x00, 0x23, 0x00, 0x00, 0x17, 0x00, 0x00, 0x0B, 0x00, 0x00, + 0x00, 0xFF, 0x9F, 0x43, 0xFF, 0xE7, 0x4B, 0xFF, 0x7B, 0xFF, 0xFF, + 0x00, 0xFF, 0xCF, 0x00, 0xCF, 0x9F, 0x00, 0x9B, 0x6F, 0x00, 0x6B, + 0xA7, 0x6B, 0x6B}; + /** * Why not restore idea of grayscale palette? * - Good Sign 2017/04/12 @@ -109,9 +110,9 @@ public class Playpal { * } */ private final static int greypal[] = IntStream.range(0, Palettes.PAL_NUM_COLORS) - .flatMap(i -> - IntStream.of(i = GreyscaleFilter.component(playpal[3 * i], playpal[3 * i + 1], playpal[3 * i + 2]), i, i) - ).toArray(); + .flatMap(i + -> IntStream.of(i = GreyscaleFilter.component(playpal[3 * i], playpal[3 * i + 1], playpal[3 * i + 2]), i, i) + ).toArray(); /** * Get grey palette in PLAYPAL bytes format @@ -128,7 +129,7 @@ public static byte[] greypal() { public static byte[] properPlaypal(byte[] lumpData) { return properPlaypal(playpal, lumpData); } - + private static byte[] properPlaypal(int[] data, byte[] lumpData) { final int palstride = PAL_NUM_COLORS * 3; final byte[] palette = new byte[palstride * NUM_PALETTES]; @@ -144,16 +145,18 @@ private static byte[] properPlaypal(int[] data, byte[] lumpData) { palette[palstride * t + 3 * i + 2] = (byte) tint.tintBlue8(rgb[2]); } } - + /** * If we have part or a whole palette, repair it using ours, * otherwise just use ours. Math.min to avoid larger palette to cause exception. */ - if (lumpData != null) + if (lumpData != null) { System.arraycopy(lumpData, 0, palette, 0, Math.min(lumpData.length, palette.length)); - + } + return palette; } - private Playpal() {} + private Playpal() { + } } diff --git a/src/w/AidedReadableDoomObject.java b/src/w/AidedReadableDoomObject.java index 63959aca..3bce46df 100644 --- a/src/w/AidedReadableDoomObject.java +++ b/src/w/AidedReadableDoomObject.java @@ -9,8 +9,7 @@ * @author Maes * */ - public interface AidedReadableDoomObject { - - public void read(DataInputStream f, int len) throws IOException ; + + public void read(DataInputStream f, int len) throws IOException; } diff --git a/src/w/CacheableDoomObject.java b/src/w/CacheableDoomObject.java index 129f575c..f86108d1 100644 --- a/src/w/CacheableDoomObject.java +++ b/src/w/CacheableDoomObject.java @@ -41,8 +41,7 @@ * @author Velktron * */ - public interface CacheableDoomObject { - - public void unpack(ByteBuffer buf) throws IOException ; + + public void unpack(ByteBuffer buf) throws IOException; } diff --git a/src/w/CacheableDoomObjectContainer.java b/src/w/CacheableDoomObjectContainer.java index b76b8e14..49bf29df 100644 --- a/src/w/CacheableDoomObjectContainer.java +++ b/src/w/CacheableDoomObjectContainer.java @@ -13,37 +13,35 @@ * abuse? ;-) * */ - public class CacheableDoomObjectContainer implements CacheableDoomObject { - - private T[] stuff; - - public CacheableDoomObjectContainer(T[] stuff){ - this.stuff=stuff; - } - - public T[] getStuff(){ - return stuff; - } - - @Override - public void unpack(ByteBuffer buf) throws IOException { - for (int i = 0; i < stuff.length; i++) { - stuff[i].unpack(buf); - } - } - - /** Statically usable method - * - * @param buf - * @param stuff - * @throws IOException - */ - - public static void unpack(ByteBuffer buf, CacheableDoomObject[] stuff) throws IOException{ - for (int i = 0; i < stuff.length; i++) { - stuff[i].unpack(buf); - } - } + + private T[] stuff; + + public CacheableDoomObjectContainer(T[] stuff) { + this.stuff = stuff; + } + + public T[] getStuff() { + return stuff; + } + + @Override + public void unpack(ByteBuffer buf) throws IOException { + for (int i = 0; i < stuff.length; i++) { + stuff[i].unpack(buf); + } + } + + /** Statically usable method + * + * @param buf + * @param stuff + * @throws IOException + */ + public static void unpack(ByteBuffer buf, CacheableDoomObject[] stuff) throws IOException { + for (int i = 0; i < stuff.length; i++) { + stuff[i].unpack(buf); + } + } } diff --git a/src/w/DoomBuffer.java b/src/w/DoomBuffer.java index e5f8ad1d..44dabaec 100644 --- a/src/w/DoomBuffer.java +++ b/src/w/DoomBuffer.java @@ -16,20 +16,19 @@ * @author admin * */ +public class DoomBuffer implements CacheableDoomObject { -public class DoomBuffer implements CacheableDoomObject { - - public DoomBuffer(){ + public DoomBuffer() { } - - public DoomBuffer(ByteBuffer b){ - this.buffer=b; + + public DoomBuffer(ByteBuffer b) { + this.buffer = b; } private ByteBuffer buffer; - public static void readObjectArray(ByteBuffer buf,CacheableDoomObject[] s,int len) throws IOException { + public static void readObjectArray(ByteBuffer buf, CacheableDoomObject[] s, int len) throws IOException { if ((s == null) || (len == 0)) { return; } @@ -38,7 +37,7 @@ public static void readObjectArray(ByteBuffer buf,CacheableDoomObject[] s,int le s[i].unpack(buf); } } - + public static void readIntArray(ByteBuffer buf, int[] s, int len) throws IOException { if ((s == null) || (len == 0)) { return; @@ -48,90 +47,105 @@ public static void readIntArray(ByteBuffer buf, int[] s, int len) throws IOExcep s[i] = buf.getInt(); } } - - public static void putIntArray(ByteBuffer buf,int[] s,int len,ByteOrder bo) throws IOException { + + public static void putIntArray(ByteBuffer buf, int[] s, int len, ByteOrder bo) throws IOException { buf.order(bo); - - if ((s==null)||(len==0)) return; - - for (int i=0;i c=s.getClass().getComponentType(); - - for (int i=0;i c) throws Exception { - - if ((s==null)||(len==0)) return; - - for (int i=0;i s,int len) throws IOException { - - if ((s==null)||(len==0)) return; - - for (int i=0;i c = s.getClass().getComponentType(); + + for (int i = 0; i < Math.min(len, s.length); i++) { + if (s[i] == null) { + s[i] = (IReadableDoomObject) c.getDeclaredConstructor().newInstance(); + } + s[i].read(dis); + } + } + + public static void readObjectArray(DataInputStream dis, IReadableDoomObject[] s, int len, Class c) throws Exception { + + if ((s == null) || (len == 0)) { + return; + } + + for (int i = 0; i < Math.min(len, s.length); i++) { + if (s[i] == null) { + s[i] = (IReadableDoomObject) c.getDeclaredConstructor().newInstance(); + } + s[i].read(dis); + } + } + + public static final void readIntArray(DataInputStream dis, int[] s, int len, ByteOrder bo) throws IOException { + + if ((s == null) || (len == 0)) { + return; + } + + for (int i = 0; i < Math.min(len, s.length); i++) { + s[i] = dis.readInt(); + if (bo == ByteOrder.LITTLE_ENDIAN) { + s[i] = Swap.LONG(s[i]); + } + } + } + + public static final void readShortArray(DataInputStream dis, short[] s, int len, ByteOrder bo) throws IOException { + + if ((s == null) || (len == 0)) { + return; + } + + for (int i = 0; i < Math.min(len, s.length); i++) { + s[i] = dis.readShort(); + if (bo == ByteOrder.LITTLE_ENDIAN) { + s[i] = Swap.SHORT(s[i]); + } + } + } + + public static final void readIntArray(DataInputStream dis, int[] s, ByteOrder bo) throws IOException { + readIntArray(dis, s, s.length, bo); + } + + public static final void readShortArray(DataInputStream dis, short[] s, ByteOrder bo) throws IOException { + readShortArray(dis, s, s.length, bo); + } + + public static void readBooleanArray(DataInputStream dis, boolean[] s, int len) throws IOException { + + if ((s == null) || (len == 0)) { + return; + } + + for (int i = 0; i < Math.min(len, s.length); i++) { + s[i] = dis.readBoolean(); + } + } + + /** Reads an array of "int booleans" into an array or + * proper booleans. 4 bytes per boolean are used! + * + * @param s + * @param len + * @throws IOException + */ + public final static void readBooleanIntArray(DataInputStream dis, boolean[] s, int len) throws IOException { + + if ((s == null) || (len == 0)) { + return; + } + + for (int i = 0; i < Math.min(len, s.length); i++) { + s[i] = readIntBoolean(dis); + } + } + + public static final void readBooleanIntArray(DataInputStream dis, boolean[] s) throws IOException { + readBooleanIntArray(dis, s, s.length); + } + + public static final void writeBoolean(DataOutputStream dos, boolean[] s, int len) throws IOException { + + if ((s == null) || (len == 0)) { + return; + } + + for (int i = 0; i < Math.min(len, s.length); i++) { + dos.writeBoolean(s[i]); + } + } + + public static final void writeObjectArray(DataOutputStream dos, IWritableDoomObject[] s, int len) throws IOException { + + if ((s == null) || (len == 0)) { + return; + } + + for (int i = 0; i < Math.min(len, s.length); i++) { + s[i].write(dos); + } + } + + public static final void writeListOfObjects(DataOutputStream dos, List s, int len) throws IOException { + + if ((s == null) || (len == 0)) { + return; + } + + for (int i = 0; i < Math.min(len, s.size()); i++) { + s.get(i).write(dos); + } + } + + public final static void readBooleanArray(DataInputStream dis, boolean[] s) throws IOException { + readBooleanArray(dis, s, s.length); + } + + public final static void readIntBooleanArray(DataInputStream dis, boolean[] s) throws IOException { + readBooleanIntArray(dis, s, s.length); + } + + public static final void writeCharArray(DataOutputStream dos, char[] charr, int len) throws IOException { + + if ((charr == null) || (len == 0)) { + return; + } + + for (int i = 0; i < Math.min(len, charr.length); i++) { + dos.writeChar(charr[i]); + } + } + + /** Will read an array of proper Unicode chars. + * + * @param charr + * @param len + * @throws IOException + */ + public static final void readCharArray(DataInputStream dis, char[] charr, int len) throws IOException { + + if ((charr == null) || (len == 0)) { + return; + } + + for (int i = 0; i < Math.min(len, charr.length); i++) { + charr[i] = dis.readChar(); + } + } + + /** Will read a bunch of non-unicode chars into a char array. + * Useful when dealing with legacy text files. + * + * @param charr + * @param len + * @throws IOException + */ + public static final void readNonUnicodeCharArray(DataInputStream dis, char[] charr, int len) throws IOException { + + if ((charr == null) || (len == 0)) { + return; + } + + for (int i = 0; i < Math.min(len, charr.length); i++) { + charr[i] = (char) dis.readUnsignedByte(); + } + } + + /** Writes an item reference. public void writeItem(gitem_t item) throws IOException { if (item == null) writeInt(-1); else writeInt(item.index); } -*/ - /** Reads the item index and returns the game item. + */ + /** Reads the item index and returns the game item. public gitem_t readItem() throws IOException { int ndx = readInt(); if (ndx == -1) @@ -416,54 +452,50 @@ public gitem_t readItem() throws IOException { else return GameItemList.itemlist[ndx]; } - * @throws IOException -*/ - - public static final long readUnsignedLEInt(DataInputStream dis) throws IOException{ - int tmp=dis.readInt(); - return 0xFFFFFFFFL&Swap.LONG(tmp); - } - - public static final int readLEInt(DataInputStream dis) throws IOException{ - int tmp=dis.readInt(); - return Swap.LONG(tmp); - } - - public static final int readLEInt(InputStream dis) throws IOException{ - int tmp=new DataInputStream(dis).readInt(); - return Swap.LONG(tmp); - } - - public static final void writeLEInt(DataOutputStream dos,int value) throws IOException{ - dos.writeInt(Swap.LONG(value)); - } - -// 2-byte number - public static int SHORT_little_endian_TO_big_endian(int i) - { - return ((i>>8)&0xff)+((i << 8)&0xff00); - } - - // 4-byte number - public static int INT_little_endian_TO_big_endian(int i) - { - return((i&0xff)<<24)+((i&0xff00)<<8)+((i&0xff0000)>>8)+((i>>24)&0xff); - } + * @throws IOException + */ + public static final long readUnsignedLEInt(DataInputStream dis) throws IOException { + int tmp = dis.readInt(); + return 0xFFFFFFFFL & Swap.LONG(tmp); + } + + public static final int readLEInt(DataInputStream dis) throws IOException { + int tmp = dis.readInt(); + return Swap.LONG(tmp); + } + + public static final int readLEInt(InputStream dis) throws IOException { + int tmp = new DataInputStream(dis).readInt(); + return Swap.LONG(tmp); + } + + public static final void writeLEInt(DataOutputStream dos, int value) throws IOException { + dos.writeInt(Swap.LONG(value)); + } -public static final short readLEShort(DataInputStream dis) throws IOException { - short tmp=dis.readShort(); - return Swap.SHORT(tmp); -} - -/** Reads a "big boolean" using 4 bytes. - * - * @return - * @throws IOException - */ -public static final boolean readIntBoolean(DataInputStream dis) throws IOException { - return (dis.readInt()!=0); - -} +// 2-byte number + public static int SHORT_little_endian_TO_big_endian(int i) { + return ((i >> 8) & 0xff) + ((i << 8) & 0xff00); + } + + // 4-byte number + public static int INT_little_endian_TO_big_endian(int i) { + return ((i & 0xff) << 24) + ((i & 0xff00) << 8) + ((i & 0xff0000) >> 8) + ((i >> 24) & 0xff); + } + + public static final short readLEShort(DataInputStream dis) throws IOException { + short tmp = dis.readShort(); + return Swap.SHORT(tmp); + } + + /** Reads a "big boolean" using 4 bytes. + * + * @return + * @throws IOException + */ + public static final boolean readIntBoolean(DataInputStream dis) throws IOException { + return (dis.readInt() != 0); + + } - } diff --git a/src/w/IPackableDoomObject.java b/src/w/IPackableDoomObject.java index 4916732e..d700ecd8 100644 --- a/src/w/IPackableDoomObject.java +++ b/src/w/IPackableDoomObject.java @@ -4,5 +4,6 @@ import java.nio.ByteBuffer; public interface IPackableDoomObject { - public void pack(ByteBuffer buf) throws IOException ; + + public void pack(ByteBuffer buf) throws IOException; } diff --git a/src/w/IReadWriteDoomObject.java b/src/w/IReadWriteDoomObject.java index 9c2fa1b9..cab97d97 100644 --- a/src/w/IReadWriteDoomObject.java +++ b/src/w/IReadWriteDoomObject.java @@ -1,5 +1,5 @@ package w; -public interface IReadWriteDoomObject extends IReadableDoomObject, IWritableDoomObject{ +public interface IReadWriteDoomObject extends IReadableDoomObject, IWritableDoomObject { } diff --git a/src/w/IReadableDoomObject.java b/src/w/IReadableDoomObject.java index 7e6cd847..8ac679eb 100644 --- a/src/w/IReadableDoomObject.java +++ b/src/w/IReadableDoomObject.java @@ -11,8 +11,7 @@ * @author Velktron * */ - public interface IReadableDoomObject { - - public void read(DataInputStream f) throws IOException ; + + public void read(DataInputStream f) throws IOException; } diff --git a/src/w/IWadLoader.java b/src/w/IWadLoader.java index db0e0992..1aee8502 100644 --- a/src/w/IWadLoader.java +++ b/src/w/IWadLoader.java @@ -2,10 +2,19 @@ import data.Defines; import doom.SourceCode.W_Wad; -import static doom.SourceCode.W_Wad.*; -import java.io.IOException; +import static doom.SourceCode.W_Wad.W_CacheLumpName; +import static doom.SourceCode.W_Wad.W_CacheLumpNum; +import static doom.SourceCode.W_Wad.W_CheckNumForName; +import static doom.SourceCode.W_Wad.W_GetNumForName; +import static doom.SourceCode.W_Wad.W_InitMultipleFiles; +import static doom.SourceCode.W_Wad.W_LumpLength; +import static doom.SourceCode.W_Wad.W_ReadLump; +import static doom.SourceCode.W_Wad.W_Reload; import java.nio.ByteBuffer; import java.util.function.IntFunction; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; import rr.patch_t; import utils.GenericCopy.ArraySupplier; import v.graphics.Lights; @@ -15,6 +24,8 @@ public interface IWadLoader { + static final Logger LOGGER = Loggers.getLogger(IWadLoader.class.getName()); + /** * W_Reload Flushes any of the reloadable lumps in memory and reloads the * directory. @@ -105,14 +116,7 @@ public interface IWadLoader { * @param */ @W_Wad.C(W_CacheLumpNum) - public abstract T CacheLumpNum(int lump, int tag, - Class what); - - // MAES 24/8/2011: superseded by auto-allocating version with proper - // container-based caching. - @Deprecated - public abstract void CacheLumpNumIntoArray(int lump, int tag, - Object[] array, Class what) throws IOException; + public abstract T CacheLumpNum(int lump, int tag, Class what); /** * Return a cached lump based on its name, as raw bytes, no matter what. @@ -303,12 +307,11 @@ default byte[] LoadPlaypal() { final int minLength = PAL_NUM_COLORS * PAL_NUM_STRIDES; if (playpal.length < minLength) { throw new IllegalArgumentException(String.format( - "Invalid PLAYPAL: has %d entries instead of %d. Try -noplaypal mode", - playpal.length, minLength)); + "Invalid PLAYPAL: has %d entries instead of %d. Try -noplaypal mode", + playpal.length, minLength)); } - System.out.print("VI_Init: set palettes.\n"); - System.out.println("Palette: " + playpal.length / PAL_NUM_STRIDES + " colors"); + LOGGER.log(Level.FINE, String.format("VI_Init: set palettes: %d colors", playpal.length / PAL_NUM_STRIDES)); InjectLumpNum(pallump, new DoomBuffer(ByteBuffer.wrap(playpal))); return playpal; @@ -329,12 +332,11 @@ default byte[][] LoadColormap() { final int minLength = Lights.COLORMAP_STD_LENGTH_15; if (colormap.length < minLength) { throw new IllegalArgumentException(String.format( - "Invalid COLORMAP: has %d entries, minimum is %d. Try -nocolormap mode", - colormap.length, minLength)); + "Invalid COLORMAP: has %d entries, minimum is %d. Try -nocolormap mode", + colormap.length, minLength)); } - System.out.print("VI_Init: set colormaps.\n"); - System.out.println("Colormaps: " + colormap.length); + LOGGER.log(Level.FINE, String.format("VI_Init: set colormaps: %d", colormap.length)); final byte[] tmp = new byte[length]; ReadLump(lump, tmp); diff --git a/src/w/IWritableDoomObject.java b/src/w/IWritableDoomObject.java index 17fa2df1..85d421d9 100644 --- a/src/w/IWritableDoomObject.java +++ b/src/w/IWritableDoomObject.java @@ -4,6 +4,6 @@ import java.io.IOException; public interface IWritableDoomObject { - - public void write(DataOutputStream dos) throws IOException ; + + public void write(DataOutputStream dos) throws IOException; } diff --git a/src/w/InputStreamSugar.java b/src/w/InputStreamSugar.java index e2373691..8a856d4b 100644 --- a/src/w/InputStreamSugar.java +++ b/src/w/InputStreamSugar.java @@ -4,12 +4,12 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; - import utils.C2JUtils; /** @@ -22,7 +22,6 @@ * * @author Maes */ - public class InputStreamSugar { public static final int UNKNOWN_TYPE = 0x0; @@ -32,7 +31,7 @@ public class InputStreamSugar { public static final int NETWORK_FILE = 0x2; public static final int ZIP_FILE = 0x4; // Zipped file - + public static final int BAD_URI = -1; // Bad or unparseable /** @@ -45,7 +44,6 @@ public class InputStreamSugar { * @param type * @return */ - public static final InputStream createInputStreamFromURI(String resource, ZipEntry entry, int type) { @@ -53,27 +51,26 @@ public static final InputStream createInputStreamFromURI(String resource, URL u; // No entry specified or no zip type, try everything BUT zip. - if (entry == null || !C2JUtils.flags(type,ZIP_FILE)) { + if (entry == null || !C2JUtils.flags(type, ZIP_FILE)) { is = getDirectInputStream(resource); } else { // Entry specified AND type specified to be zip // We might want to open even a zip file without looking // for any particular entry. - if (entry != null && C2JUtils.flags(type,ZIP_FILE)) { - + if (entry != null && C2JUtils.flags(type, ZIP_FILE)) { + ZipInputStream zis; // Try it as a NET zip file try { - u = new URL(resource); + u = new URI(resource).toURL(); zis = new ZipInputStream(u.openStream()); } catch (Exception e) { // Local zip file? try { // Open resource as local file-backed zip input stream, // and search proper entry. - zis= new ZipInputStream(new FileInputStream(resource)); - } - catch (Exception e1) { + zis = new ZipInputStream(new FileInputStream(resource)); + } catch (Exception e1) { // Well, it's not that either. // At this point we almost ran out of options // Try a local file and that's it. @@ -81,15 +78,16 @@ public static final InputStream createInputStreamFromURI(String resource, return is; } } - + // All OK? - is=getZipEntryStream(zis, entry.getName()); - if (is!=null) return is; + is = getZipEntryStream(zis, entry.getName()); + if (is != null) { + return is; } } + } // At this point, you'll either get a stream or jack. - return getDirectInputStream(resource); } @@ -102,15 +100,15 @@ public static final InputStream createInputStreamFromURI(String resource, * @param entryname * @return */ - - private static InputStream getZipEntryStream(ZipInputStream zis,String entryname) { - + private static InputStream getZipEntryStream(ZipInputStream zis, String entryname) { + ZipEntry ze = null; try { while ((ze = zis.getNextEntry()) != null) { // Directories cannot be opened - if (ze.isDirectory()) + if (ze.isDirectory()) { continue; + } if (ze.getName().equals(entryname)) { return zis; @@ -120,17 +118,17 @@ private static InputStream getZipEntryStream(ZipInputStream zis,String entryname // Get jack return null; } - + // Get jack return null; } - + private final static InputStream getDirectInputStream(String resource) { InputStream is = null; URL u; try { // Is it a net resource? - u = new URL(resource); + u = new URI(resource).toURL(); is = u.openStream(); } catch (Exception e) { // OK, not a valid URL or no network. We don't care. @@ -156,19 +154,19 @@ private final static InputStream getDirectInputStream(String resource) { * @param is * @param pos * The desired position - * @param URI + * @param uri * Information which can help reopen a stream, e.g. a filename, URL, * or zip file. * @peram entry If we must look into a zipfile entry * @return the skipped stream. Might be a totally different object. * @throws IOException */ - public static final InputStream streamSeek(InputStream is, long pos, - long size,String URI, ZipEntry entry, int type) + long size, String uri, ZipEntry entry, int type) throws IOException { - if (is == null) + if (is == null) { return is; + } // If we know our actual position in the stream, we can aid seeking // forward @@ -182,7 +180,6 @@ public static final InputStream streamSeek(InputStream is, long pos, * return is; } catch (Exception e){ // We couldn't skip cleanly. * Swallow up and try normally. System.err.println("Couldn't skip"); } } */ - // This is a more reliable method, although it's less than impressive in // results. if (size > 0) { @@ -192,19 +189,18 @@ public static final InputStream streamSeek(InputStream is, long pos, // The stream is at a position before or equal to // our desired one. We can attempt skipping forward. if (guesspos > 0 && guesspos <= pos) { - long skipped=0; - long mustskip=pos-guesspos; + long skipped = 0; + long mustskip = pos - guesspos; // Repeat skipping until proper amount reached - while (skipped getAllEntries(ZipInputStream zis) throws IOException { - ArrayList zes = new ArrayList(); + ArrayList zes = new ArrayList<>(); ZipEntry z; @@ -268,7 +263,6 @@ public static List getAllEntries(ZipInputStream zis) * @param z * @return */ - public static long getSizeEstimate(InputStream is, ZipEntry z) { if (is instanceof FileInputStream) { try { @@ -279,8 +273,9 @@ public static long getSizeEstimate(InputStream is, ZipEntry z) { } if (is instanceof FileInputStream) { - if (z != null) + if (z != null) { return z.getSize(); + } } // Last ditch @@ -295,4 +290,4 @@ public static long getSizeEstimate(InputStream is, ZipEntry z) { } } -} \ No newline at end of file +} diff --git a/src/w/JadDecompress.java b/src/w/JadDecompress.java index 05508279..e8b9e7b8 100644 --- a/src/w/JadDecompress.java +++ b/src/w/JadDecompress.java @@ -1,13 +1,20 @@ package w; +import java.util.logging.Level; +import java.util.logging.Logger; +import mochadoom.Loggers; + public class JadDecompress { + private static final Logger LOGGER = Loggers.getLogger(JadDecompress.class.getName()); + public final static int WINDOW_SIZE = 4096; public final static int LOOKAHEAD_SIZE = 16; - public final static int LENSHIFT = 4; /* this must be log2(LOOKAHEAD_SIZE) */ + public final static int LENSHIFT = 4; + /* this must be log2(LOOKAHEAD_SIZE) */ public static void decode(byte[] input, byte[] output) { /* * #ifdef JAGUAR decomp_input = input; decomp_output = output; @@ -24,7 +31,9 @@ public static void decode(byte[] input, byte[] output) { while (true) { /* get a new idbyte if necessary */ - if (getidbyte == 0) idbyte = 0xFF & input[input_ptr++]; + if (getidbyte == 0) { + idbyte = 0xFF & input[input_ptr++]; + } getidbyte = (getidbyte + 1) & 7; if ((idbyte & 1) != 0) { @@ -35,10 +44,12 @@ public static void decode(byte[] input, byte[] output) { len = ((0xFF & input[input_ptr++]) & 0xf) + 1; - if (len == 1) + if (len == 1) { break; - for (i = 0; i < len; i++) + } + for (i = 0; i < len; i++) { output[output_ptr++] = output[source_ptr++]; + } } else { output[output_ptr++] = input[input_ptr++]; } @@ -47,7 +58,7 @@ public static void decode(byte[] input, byte[] output) { } - System.out.printf("Expanded %d to %d\n", input_ptr, output_ptr); + LOGGER.log(Level.INFO, String.format("Expanded %d to %d", input_ptr, output_ptr)); } } diff --git a/src/w/WadLoader.java b/src/w/WadLoader.java index e247480a..60e96781 100644 --- a/src/w/WadLoader.java +++ b/src/w/WadLoader.java @@ -1,4 +1,4 @@ -// Emacs style mode select -*- C++ -*- +// Emacs style mode select -*- Java -*- // ----------------------------------------------------------------------------- // // $Id: WadLoader.java,v 1.64 2014/03/28 00:55:32 velktron Exp $ @@ -19,7 +19,6 @@ // Handles WAD file header, directory, lump I/O. // // ----------------------------------------------------------------------------- - package w; import static data.Defines.PU_CACHE; @@ -29,6 +28,7 @@ import static doom.SourceCode.W_Wad.W_CheckNumForName; import i.DummySystem; import i.IDoomSystem; +import i.Strings; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.DataInputStream; @@ -41,6 +41,7 @@ import java.util.List; import java.util.function.IntFunction; import java.util.logging.Level; +import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import mochadoom.Loggers; @@ -51,6 +52,8 @@ public class WadLoader implements IWadLoader { + private static final Logger LOGGER = Loggers.getLogger(WadLoader.class.getName()); + protected IDoomSystem I; ///// CONSTRUCTOR @@ -64,443 +67,421 @@ public WadLoader() { zone = new HashMap<>(); wadfiles = new ArrayList<>(); this.I = new DummySystem(); + + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + CloseAllHandles(); + })); } - - - //// FIELDS - - /** Location of each lump on disk. */ - public lumpinfo_t[] lumpinfo; - - public int numlumps; - - /** - * MAES: probably array of byte[]??? void** lumpcache; - * - * Actually, loaded objects will be deserialized here as the general type - * "CacheableDoomObject" (in the worst case they will be byte[] or - * ByteBuffer). - * - * Not to brag, but this system is FAR superior to the inline unmarshaling - * used in other projects ;-) - */ - - private CacheableDoomObject[] lumpcache; - - private boolean[] preloaded; - - /** Added for Boom compliance */ - private List wadfiles; - - /** - * #define strcmpi strcasecmp MAES: this is just capitalization. However we - * can't manipulate String object in Java directly like this, so this must - * be a return type. - * - * TODO: maybe move this in utils? - */ - - public String strupr(String s) { - return s.toUpperCase(); - } - - /* ditto */ - public void strupr(char[] s) { - for (int i = 0; i < s.length; i++) { - s[i] = Character.toUpperCase(s[i]); - } - } - - // - // LUMP BASED ROUTINES. - // - - // - // W_AddFile - // All files are optional, but at least one file must be - // found (PWAD, if all required lumps are present). - // Files with a .wad extension are wadlink files - // with multiple lumps. - // Other files are single lumps with the base filename - // for the lump name. - // - // If filename starts with a tilde, the file is handled - // specially to allow map reloads. - // But: the reload feature is a fragile hack... - - int reloadlump; - - // MAES: was char* - String reloadname; + + //// FIELDS + /** Location of each lump on disk. */ + public lumpinfo_t[] lumpinfo; + + public int numlumps; + + /** + * MAES: probably array of byte[]??? void** lumpcache; + * + * Actually, loaded objects will be deserialized here as the general type + * "CacheableDoomObject" (in the worst case they will be byte[] or + * ByteBuffer). + * + * Not to brag, but this system is FAR superior to the inline unmarshaling + * used in other projects ;-) + */ + private CacheableDoomObject[] lumpcache; + + private boolean[] preloaded; + + /** Added for Boom compliance */ + private List wadfiles; + + /** + * #define strcmpi strcasecmp MAES: this is just capitalization. However we + * can't manipulate String object in Java directly like this, so this must + * be a return type. + * + * TODO: maybe move this in utils? + */ + public String strupr(String s) { + return s.toUpperCase(); + } + + /* ditto */ + public void strupr(char[] s) { + for (int i = 0; i < s.length; i++) { + s[i] = Character.toUpperCase(s[i]); + } + } + + // + // LUMP BASED ROUTINES. + // + // + // W_AddFile + // All files are optional, but at least one file must be + // found (PWAD, if all required lumps are present). + // Files with a .wad extension are wadlink files + // with multiple lumps. + // Other files are single lumps with the base filename + // for the lump name. + // + // If filename starts with a tilde, the file is handled + // specially to allow map reloads. + // But: the reload feature is a fragile hack... + int reloadlump; + + // MAES: was char* + String reloadname; + /** * This is where lumps are actually read + loaded from a file. - * + * * @param filename * @throws Exception */ - - private void AddFile(String uri,ZipEntry entry,int type) throws Exception { - wadinfo_t header = new wadinfo_t(); - int lump_p; // MAES: was lumpinfo_t* , but we can use it as an array - // pointer. - InputStream handle,storehandle; - long length; - int startlump; - - filelump_t[] fileinfo = new filelump_t[1]; // MAES: was * - filelump_t singleinfo = new filelump_t(); - - // handle reload indicator. - if (uri.charAt(0) == '~') { - uri = uri.substring(1); - reloadname = uri; - reloadlump = numlumps; - } + private void AddFile(String uri, ZipEntry entry, int type) throws Exception { + wadinfo_t header = new wadinfo_t(); + int lump_p; // MAES: was lumpinfo_t* , but we can use it as an array + // pointer. + InputStream handle, storehandle; + long length; + int startlump; + + filelump_t[] fileinfo = new filelump_t[1]; // MAES: was * + filelump_t singleinfo = new filelump_t(); + + // handle reload indicator. + if (uri.charAt(0) == '~') { + uri = uri.substring(1); + reloadname = uri; + reloadlump = numlumps; + } // open the resource and add to directory - // It can be any streamed type handled by the "sugar" utilities. - - try { - handle = InputStreamSugar.createInputStreamFromURI(uri,entry,type); - } catch (Exception e) { - I.Error(" couldn't open resource %s \n", uri); - return; - } - + // It can be any streamed type handled by the "sugar" utilities. + try { + handle = InputStreamSugar.createInputStreamFromURI(uri, entry, type); + } catch (Exception e) { + I.Error(" couldn't open resource %s \n", uri); + return; + } + // Create and set wadfile info - wadfile_info_t wadinfo=new wadfile_info_t(); - wadinfo.handle= handle; - wadinfo.name=uri; - wadinfo.entry=entry; - wadinfo.type=type; - - // System.out.println(" adding " + filename + "\n"); - - // We start at the number of lumps. This allows appending stuff. - startlump = this.numlumps; - - String checkname=(wadinfo.entry!=null?wadinfo.entry.getName():uri); - // If not "WAD" then we check for single lumps. - if (!C2JUtils.checkForExtension(checkname,"wad")) { - - fileinfo[0] = singleinfo; - singleinfo.filepos = 0; - singleinfo.size = InputStreamSugar.getSizeEstimate(handle,wadinfo.entry); - - // Single lumps. Only use 8 characters - singleinfo.actualname=singleinfo.name = C2JUtils.removeExtension(uri).toUpperCase(); - - // MAES: check out certain known types of extension - if (C2JUtils.checkForExtension(uri,"lmp")) - wadinfo.src=wad_source_t.source_lmp; - else - if (C2JUtils.checkForExtension(uri,"deh")) - wadinfo.src=wad_source_t.source_deh; - else - if (C2JUtils.checkForExtension(uri,null)) - wadinfo.src=wad_source_t.source_deh; - - numlumps++; - - } else { - // MAES: 14/06/10 this is historical, for this is the first time I - // implement reading something from RAF into Doom's structs. - // Kudos to the JAKE2 team who solved this problem before me. - // MAES: 25/10/11: In retrospect, this solution, while functional, was - // inelegant and limited. - - DataInputStream dis=new DataInputStream(handle); - - // Read header in one go. Usually doesn't cause trouble? - header.read(dis); - - if (header.identification.compareTo("IWAD") != 0) { - // Homebrew levels? - if (header.identification.compareTo("PWAD") != 0) { - I.Error("Wad file %s doesn't have IWAD or PWAD id\n",checkname); - } else wadinfo.src=wad_source_t.source_pwad; - - // modifiedgame = true; - } else wadinfo.src=wad_source_t.source_iwad; - - length = header.numlumps; - // Init everything: - fileinfo = malloc(filelump_t::new, filelump_t[]::new, (int) length); - - dis.close(); - - handle=InputStreamSugar.streamSeek(handle,header.infotableofs,wadinfo.maxsize,uri,entry,type); - - // FIX: sometimes reading from zip files doesn't work well, so we pre-cache the TOC - byte[] TOC=new byte[(int) (length*filelump_t.sizeof())]; - - int read=0; - while (read maxsize) { + maxsize = lumpinfo[i].position + lumpinfo[i].size; + } + } - // Bye bye, old lumpinfo! - lumpinfo = newlumpinfo; - - // MAES: lum_p was an alias for lumpinfo[startlump]. I know it's a - // bit crude as an approximation but heh... - - lump_p = startlump; - - // MAES: if reloadname is null, handle is stored...else an invalid - // handle? - storehandle = (reloadname != null) ? null : handle; - - // This iterates through single files. - int fileinfo_p = 0; - - - for (int i = startlump; i < numlumps; i++, lump_p++, fileinfo_p++) { - lumpinfo[lump_p].handle = storehandle; - lumpinfo[lump_p].position = fileinfo[fileinfo_p].filepos; - lumpinfo[lump_p].size = fileinfo[fileinfo_p].size; - // Make all lump names uppercase. Searches should also be uppercase only. - lumpinfo[lump_p].name = fileinfo[fileinfo_p].name.toUpperCase(); - lumpinfo[lump_p].hash =lumpinfo[lump_p].name.hashCode(); - // lumpinfo[lump_p].stringhash = name8.getLongHash(strupr(lumpinfo[lump_p].name)); - // LumpNameHash(lumpinfo[lump_p].name); - lumpinfo[lump_p].intname = name8.getIntName(strupr(lumpinfo[lump_p].name)); - //System.out.println(lumpinfo[lump_p]); - lumpinfo[lump_p].wadfile=wadinfo; // MAES: Add Boom provenience info - } - - - - if (reloadname != null) - handle.close(); - } - - /** Try to guess a realistic wad size limit based only on the number of lumps and their - * STATED contents, in case it's not possible to get an accurate stream size otherwise. - * Of course, they may be way off with deliberately malformed files etc. - * - * @param header - * @param lumpinfo2 - * @return - */ - - private long estimateWadSize(wadinfo_t header, lumpinfo_t[] lumpinfo) { - - long maxsize=header.infotableofs+header.numlumps*16; - - for (int i=0;imaxsize){ - maxsize=lumpinfo[i].position+lumpinfo[i].size; - } - } - return maxsize; } /* (non-Javadoc) * @see w.IWadLoader#Reload() - */ - @Override - @SuppressWarnings("null") - public void Reload() throws Exception { - wadinfo_t header = new wadinfo_t(); - int lumpcount; - int lump_p; // Maes: same as in W_WADload - int i; - DataInputStream handle = null; - int length; - filelump_t[] fileinfo; - - if (reloadname == null) - return; + */ + @Override + @SuppressWarnings("null") + public void Reload() throws Exception { + wadinfo_t header = new wadinfo_t(); + int lumpcount; + int lump_p; // Maes: same as in W_WADload + int i; + DataInputStream handle = null; + int length; + filelump_t[] fileinfo; + + if (reloadname == null) { + return; + } - try { - handle = new DataInputStream(new BufferedInputStream(new FileInputStream(reloadname))); - } catch (Exception e) { - I.Error("W_Reload: couldn't open %s", reloadname); - } + try { + handle = new DataInputStream(new BufferedInputStream(new FileInputStream(reloadname))); + } catch (Exception e) { + I.Error("W_Reload: couldn't open %s", reloadname); + } - header.read(handle); - // Actual number of lumps in file... - lumpcount = (int) header.numlumps; - header.infotableofs = header.infotableofs; - length = lumpcount; - fileinfo = new filelump_t[length]; - - handle.reset(); - handle.skip(header.infotableofs); + header.read(handle); + // Actual number of lumps in file... + lumpcount = (int) header.numlumps; + header.infotableofs = header.infotableofs; + length = lumpcount; + fileinfo = new filelump_t[length]; - // MAES: we can't read raw structs here, and even less BLOCKS of - // structs. + handle.reset(); + handle.skip(header.infotableofs); - DoomIO.readObjectArrayWithReflection(handle,fileinfo, length); + // MAES: we can't read raw structs here, and even less BLOCKS of + // structs. + DoomIO.readObjectArrayWithReflection(handle, fileinfo, length); - /* + /* * for (int j=0;j zes=InputStreamSugar.getAllEntries(zip); + // Get entries + BufferedInputStream is = new BufferedInputStream( + InputStreamSugar.createInputStreamFromURI(s, null, type) + ); + ZipInputStream zip = new ZipInputStream(is); + List zes = InputStreamSugar.getAllEntries(zip); zip.close(); - for (ZipEntry zz:zes){ + for (ZipEntry zz : zes) { // The name of a zip file will be used as an identifier - if (!zz.isDirectory()) - this.AddFile(s,zz, type); + if (!zz.isDirectory()) { + this.AddFile(s, zz, type); + } } } - /* (non-Javadoc) - * @see w.IWadLoader#InitFile(java.lang.String) - */ - @Override - public void InitFile(String filename) throws Exception { - String[] names = new String[1]; - - names[0] = filename; - // names[1] = null; - InitMultipleFiles(names); - } - - /* (non-Javadoc) - * @see w.IWadLoader#NumLumps() - */ - @Override - public final int NumLumps() { - return numlumps; - } - - /** - * W_CheckNumForName2 Returns -1 if name not found. - * - * A slightly better implementation, uses string hashes - * as direct comparators (though 64-bit long descriptors - * could be used). It's faster than the old method, but - * still short from the HashMap's performance by - * an order of magnitude. - * + @Override + public void InitFile(String filename) throws Exception { + String[] names = new String[1]; + + names[0] = filename; + // names[1] = null; + InitMultipleFiles(names); + } + + @Override + public final int NumLumps() { + return numlumps; + } + + /** + * W_CheckNumForName2 Returns -1 if name not found. + * + * A slightly better implementation, uses string hashes + * as direct comparators (though 64-bit long descriptors + * could be used). It's faster than the old method, but + * still short from the HashMap's performance by + * an order of magnitude. + * * @param name * @return - * - * UNUSED + * + * UNUSED public int CheckNumForName2(String name) { @@ -522,18 +503,17 @@ public int CheckNumForName2(String name) { // TFB. Not found. return -1; } */ - - /** - * Old, shitty method for CheckNumForName. It's an overly literal - * translation of how the C original worked, which was none too good - * even without the overhead of converting a string to - * its integer representation. It's so bad, that it's two orders - * of magnitude slower than a HashMap implemetation, and one from - * a direct hash/longname comparison with linear search. - * - * @param name - * @return - * + /** + * Old, shitty method for CheckNumForName. It's an overly literal + * translation of how the C original worked, which was none too good + * even without the overhead of converting a string to + * its integer representation. It's so bad, that it's two orders + * of magnitude slower than a HashMap implemetation, and one from + * a direct hash/longname comparison with linear search. + * + * @param name + * @return + * public int CheckNumForName3(String name) { @@ -564,498 +544,323 @@ public int CheckNumForName3(String name) { return -1; } */ - /* (non-Javadoc) - * @see w.IWadLoader#GetLumpinfoForName(java.lang.String) - */ + @Override + public lumpinfo_t GetLumpinfoForName(String name) { - @Override - public lumpinfo_t GetLumpinfoForName(String name) { + int v1; + int v2; + // lumpinfo_t lump_p; - int v1; - int v2; - // lumpinfo_t lump_p; + int lump_p; + // make the name into two integers for easy compares + // case insensitive + name8 union = new name8(strupr(name)); - int lump_p; - // make the name into two integers for easy compares - // case insensitive - name8 union = new name8(strupr(name)); + v1 = union.x[0]; + v2 = union.x[1]; - v1 = union.x[0]; - v2 = union.x[1]; + // scan backwards so patch lump files take precedence + lump_p = numlumps; - // scan backwards so patch lump files take precedence - lump_p = numlumps; + while (lump_p-- != 0) { + int a = name8.stringToInt(lumpinfo[lump_p].name, 0); + int b = name8.stringToInt(lumpinfo[lump_p].name, 4); + if ((a == v1) && (b == v2)) { + return lumpinfo[lump_p]; + } + } - while (lump_p-- != 0) { - int a = name8.stringToInt(lumpinfo[lump_p].name, 0); - int b = name8.stringToInt(lumpinfo[lump_p].name, 4); - if ((a == v1) && (b == v2)) { - return lumpinfo[lump_p]; - } - } + // TFB. Not found. + return null; + } - // TFB. Not found. - return null; - } - - /* (non-Javadoc) - * @see w.IWadLoader#GetNumForName(java.lang.String) - */ - - @Override - public int GetNumForName(String name) { - int i; + @Override + public int GetNumForName(String name) { + int i; - i = CheckNumForName(name.toUpperCase()); + i = CheckNumForName(name.toUpperCase()); - if (i == -1) { - Exception e = new Exception(); - e.printStackTrace(); - System.err.println("Error: " + name + " not found"); - System.err.println("Hash: " - + Long.toHexString(name8.getLongHash(name))); - I.Error("W_GetNumForName: %s not found!", name); - } + if (i == -1) { + I.Error("W_GetNumForName: %s not found! hash: %s", name, Long.toHexString(name8.getLongHash(name))); + } - return i; - } + return i; + } - /* (non-Javadoc) - * @see w.IWadLoader#GetNameForNum(int) - */ @Override - public String GetNameForNum(int lumpnum) { - if (lumpnum>=0 && lumpnum= 0 && lumpnum < this.numlumps) { return this.lumpinfo[lumpnum].name; } return null; } - - // - // W_LumpLength - // Returns the buffer size needed to load the given lump. - // - /* (non-Javadoc) + + // + // W_LumpLength + // Returns the buffer size needed to load the given lump. + // + /* (non-Javadoc) * @see w.IWadLoader#LumpLength(int) - */ - @Override - public int LumpLength(int lump) { - if (lump >= numlumps) - I.Error("W_LumpLength: %i >= numlumps", lump); - - return (int) lumpinfo[lump].size; - } - - @Override - public final byte[] ReadLump(int lump){ - lumpinfo_t l=lumpinfo[lump]; - byte[] buf=new byte[(int) l.size]; - ReadLump(lump, buf,0); - return buf; - - } - - @Override - public final void ReadLump(int lump, byte[] buf) { - ReadLump(lump, buf, 0); - } - + */ + @Override + public int LumpLength(int lump) { + if (lump >= numlumps) { + I.Error("W_LumpLength: %d >= numlumps", lump); + } + + return (int) lumpinfo[lump].size; + } + + @Override + public final byte[] ReadLump(int lump) { + lumpinfo_t l = lumpinfo[lump]; + byte[] buf = new byte[(int) l.size]; + ReadLump(lump, buf, 0); + return buf; + + } + + @Override + public final void ReadLump(int lump, byte[] buf) { + ReadLump(lump, buf, 0); + } + /** * W_ReadLump Loads the lump into the given buffer, which must be >= * W_LumpLength(). SKIPS CACHING - * + * * @throws IOException */ + @Override + public final void ReadLump(int lump, byte[] buf, int offset) { + int c = 0; + lumpinfo_t l; + InputStream handle = null; + + if (lump >= this.numlumps) { + I.Error("W_ReadLump: %d >= numlumps", lump); + return; + } - @Override - public final void ReadLump(int lump, byte[] buf, int offset) { - int c=0; - lumpinfo_t l; - InputStream handle = null; + l = lumpinfo[lump]; - if (lump >= this.numlumps) { - I.Error("W_ReadLump: %i >= numlumps", lump); - return; - } + if (l.handle == null) { + // reloadable file, so use open / read / close + try { + // FIXME: reloadable files can only be that. Files. + handle = InputStreamSugar.createInputStreamFromURI(this.reloadname, null, 0); + } catch (Exception e) { + I.Error("W_ReadLump: couldn't open %s, due to: %s", reloadname, e.getMessage()); + } + } else { + handle = l.handle; + } - l = lumpinfo[lump]; + try { - if (l.handle == null) { - // reloadable file, so use open / read / close - try { - // FIXME: reloadable files can only be that. Files. - handle = InputStreamSugar.createInputStreamFromURI(this.reloadname,null,0); - } catch (Exception e) { - e.printStackTrace(); - I.Error("W_ReadLump: couldn't open %s", reloadname); - } - } else - handle = l.handle; - - try { - - handle=InputStreamSugar.streamSeek(handle,l.position, - l.wadfile.maxsize,l.wadfile.name,l.wadfile.entry,l.wadfile.type); - - // read buffered. Unfortunately that interferes badly with - // guesstimating the actual stream position. - BufferedInputStream bis=new BufferedInputStream(handle,8192); - - while (c T CacheLumpNum(int lump, int tag, Class what) { - - if (lump >= numlumps) { - I.Error("W_CacheLumpNum: %i >= numlumps", lump); - } + // read buffered. Unfortunately that interferes badly with + // guesstimating the actual stream position. + BufferedInputStream bis = new BufferedInputStream(handle, 8192); - // Nothing cached here... - // SPECIAL case : if no class is specified (null), the lump is re-read anyway - // and you get a raw doombuffer. Plus, it won't be cached. - - if ((lumpcache[lump] == null)||(what==null)) { - - // read the lump in - - // System.out.println("cache miss on lump "+lump); - // Fake Zone system: mark this particular lump with the tag specified - // ptr = Z_Malloc (W_LumpLength (lump), tag, &lumpcache[lump]); - // Read as a byte buffer anyway. - ByteBuffer thebuffer = ByteBuffer.wrap(ReadLump(lump)); - - // Class type specified - - if (what != null) { - try { - // Can it be uncached? If so, deserialize it. - - if (implementsInterface(what, w.CacheableDoomObject.class)) { - // MAES: this should be done whenever single lumps - // are read. DO NOT DELEGATE TO THE READ OBJECTS THEMSELVES. - // In case of sequential reads of similar objects, use - // CacheLumpNumIntoArray instead. - thebuffer.rewind(); - lumpcache[lump] = (CacheableDoomObject) what.newInstance(); - lumpcache[lump].unpack(thebuffer); - - // Track it for freeing - Track(lumpcache[lump],lump); - - if (what == patch_t.class) { - ((patch_t) lumpcache[lump]).name = this.lumpinfo[lump].name; - } - } else { - // replace lump with parsed object. - lumpcache[lump] = (CacheableDoomObject) thebuffer; - - // Track it for freeing - Track((CacheableDoomObject)thebuffer,lump); - } - } catch (Exception e) { - System.err.println("Could not auto-instantiate lump " - + lump + " of class " + what); - e.printStackTrace(); - } + while (c < l.size) { + c += bis.read(buf, offset + c, (int) (l.size - c)); + } - } else { - // Class not specified? Then gimme a containing DoomBuffer! - DoomBuffer db = new DoomBuffer(thebuffer); - lumpcache[lump] = db; - } - } else { - // System.out.println("cache hit on lump " + lump); - // Z.ChangeTag (lumpcache[lump],tag); - } - - return (T) lumpcache[lump]; - } - - /** A very useful method when you need to load a lump which can consist - * of an arbitrary number of smaller fixed-size objects (assuming that you - * know their number/size and the size of the lump). Practically used - * by the level loader, to handle loading of sectors, segs, things, etc. - * since their size/lump/number relationship is well-defined. - * - * It possible to do this in other ways, but it's extremely convenient this way. - * - * MAES 24/8/2011: This method is deprecated, Use the much more convenient - * and slipstreamed generic version, which also handles caching of arrays - * and auto-allocation. - * - * @param lump The lump number to load. - * @param tag Caching tag - * @param array The array with objects to load. Its size implies how many to read. - * @return - */ - - @Override - @Deprecated - public void CacheLumpNumIntoArray(int lump, int tag, Object[] array, - Class what) throws IOException { - - if (lump >= numlumps) { - I.Error("W_CacheLumpNum: %i >= numlumps", lump); - } + // Well, that's a no-brainer. + //l.wadfile.knownpos=l.position+c; + if (c < l.size) { + LOGGER.log(Level.SEVERE, String.format("W_ReadLump: only read %d of %d on lump %d %d", c, l.size, + lump, l.position)); + } - // Nothing cached here... - if ((lumpcache[lump] == null)) { + if (l.handle == null) { + handle.close(); + } else { + l.handle = handle; + } - // read the lump in + I.BeginRead(); + // ??? I_EndRead (); - //System.out.println("cache miss on lump " + lump); - // Read as a byte buffer anyway. - ByteBuffer thebuffer = ByteBuffer.wrap(ReadLump(lump)); - // Store the buffer anyway (as a DoomBuffer) - lumpcache[lump] = new DoomBuffer(thebuffer); - - // Track it (as ONE lump) - Track(lumpcache[lump],lump); + } catch (Exception e) { + I.Error("W_ReadLump: could not read lump %d, due to: %s", lump, e.getMessage()); + } + } - } else { - //System.out.println("cache hit on lump " + lump); - // Z.ChangeTag (lumpcache[lump],tag); - } + /** + * The most basic of the Wadloader functions. Will attempt to read a lump + * off disk, based on the specific class type (it will call the unpack() + * method). If not possible to call the unpack method, it will leave a + * DoomBuffer object in its place, with the raw byte contents. + */ + @Override + @SuppressWarnings("unchecked") + public T CacheLumpNum(int lump, int tag, Class what) { - // Class type specified. If the previously cached stuff is a - // "DoomBuffer" we can go on. - - if ((what != null) && (lumpcache[lump].getClass() == DoomBuffer.class)) { - try { - // Can it be uncached? If so, deserialize it. FOR EVERY OBJECT. - ByteBuffer b = ((DoomBuffer) (lumpcache[lump])).getBuffer(); - b.rewind(); - - for (int i = 0; i < array.length; i++) { - if (implementsInterface(what, w.CacheableDoomObject.class)) { - ((CacheableDoomObject) array[i]).unpack(b); - } - } - // lumpcache[lump]=array; - } catch (Exception e) { - System.err.println("Could not auto-unpack lump " + lump - + " into an array of objects of class " + what); - e.printStackTrace(); - } + if (lump >= numlumps) { + I.Error("W_CacheLumpNum: %d >= numlumps", lump); + } - } - - - - return; - } - - /** A very useful method when you need to load a lump which can consist - * of an arbitrary number of smaller fixed-size objects (assuming that you - * know their number/size and the size of the lump). Practically used - * by the level loader, to handle loading of sectors, segs, things, etc. - * since their size/lump/number relationship is well-defined. - * - * It possible to do this in other (more verbose) ways, but it's - * extremely convenient this way, as a lot of common and repetitive code - * is only written once, and generically, here. Trumps the older - * method in v 1.43 of WadLoader, which is deprecated. - * - * @param lump The lump number to load. - * @param num number of objects to read * - * @return a properly sized array of the correct type. - */ - + // Nothing cached here... + // SPECIAL case : if no class is specified (null), the lump is re-read anyway + // and you get a raw doombuffer. Plus, it won't be cached. + if ((lumpcache[lump] == null) || (what == null)) { + // read the lump in + // System.out.println("cache miss on lump "+lump); + // Fake Zone system: mark this particular lump with the tag specified + // ptr = Z_Malloc (W_LumpLength (lump), tag, &lumpcache[lump]); + // Read as a byte buffer anyway. + ByteBuffer thebuffer = ByteBuffer.wrap(ReadLump(lump)); + + // Class type specified + if (what != null) { + try { + // Can it be uncached? If so, deserialize it. + // MAES: this should be done whenever single lumps + // are read. DO NOT DELEGATE TO THE READ OBJECTS THEMSELVES. + // In case of sequential reads of similar objects, use + // CacheLumpNumIntoArray instead. + thebuffer.rewind(); + lumpcache[lump] = what.getDeclaredConstructor().newInstance(); + lumpcache[lump].unpack(thebuffer); + + // Track it for freeing + Track(lumpcache[lump], lump); + + if (what == patch_t.class) { + ((patch_t) lumpcache[lump]).name = this.lumpinfo[lump].name; + } + } catch (Exception e) { + LOGGER.log(Level.SEVERE, + String.format("Could not auto-instantiate lump %d of class %s", lump, String.valueOf(what)), e); + } + + } else { + // Class not specified? Then gimme a containing DoomBuffer! + DoomBuffer db = new DoomBuffer(thebuffer); + lumpcache[lump] = db; + } + } + + return (T) lumpcache[lump]; + } + + /** A very useful method when you need to load a lump which can consist + * of an arbitrary number of smaller fixed-size objects (assuming that you + * know their number/size and the size of the lump). Practically used + * by the level loader, to handle loading of sectors, segs, things, etc. + * since their size/lump/number relationship is well-defined. + * + * It possible to do this in other (more verbose) ways, but it's + * extremely convenient this way, as a lot of common and repetitive code + * is only written once, and generically, here. Trumps the older + * method in v 1.43 of WadLoader, which is deprecated. + * + * @param lump The lump number to load. + * @param num number of objects to read * + * @return a properly sized array of the correct type. + */ @Override - public T[] CacheLumpNumIntoArray(int lump, int num, ArraySupplier what, IntFunction arrGen){ - if (lump >= numlumps) { - I.Error("CacheLumpNumIntoArray: %i >= numlumps", lump); - } + public T[] CacheLumpNumIntoArray(int lump, int num, ArraySupplier what, IntFunction arrGen) { + if (lump >= numlumps) { + I.Error("CacheLumpNumIntoArray: %d >= numlumps", lump); + } /** * Impossible condition unless you hack generics somehow * - Good Sign 2017/05/07 */ - /*if (!implementsInterface(what, CacheableDoomObject.class)){ + /*if (!implementsInterface(what, CacheableDoomObject.class)){ I.Error("CacheLumpNumIntoArray: %s does not implement CacheableDoomObject", what.getName()); }*/ - - // Nothing cached here... - if ((lumpcache[lump] == null) && (what != null)) { - //System.out.println("cache miss on lump " + lump); - // Read as a byte buffer anyway. - ByteBuffer thebuffer = ByteBuffer.wrap(ReadLump(lump)); - T[] stuff = malloc(what, arrGen, num); - - // Store the buffer anyway (as a CacheableDoomObjectContainer) - lumpcache[lump] = new CacheableDoomObjectContainer<>(stuff); - - // Auto-unpack it, if possible. + // Nothing cached here... + if ((lumpcache[lump] == null) && (what != null)) { + //System.out.println("cache miss on lump " + lump); + // Read as a byte buffer anyway. + ByteBuffer thebuffer = ByteBuffer.wrap(ReadLump(lump)); + T[] stuff = malloc(what, arrGen, num); + + // Store the buffer anyway (as a CacheableDoomObjectContainer) + lumpcache[lump] = new CacheableDoomObjectContainer<>(stuff); + // Auto-unpack it, if possible. try { thebuffer.rewind(); lumpcache[lump].unpack(thebuffer); } catch (IOException e) { - Loggers.getLogger(WadLoader.class.getName()).log(Level.WARNING, String.format( + LOGGER.log(Level.WARNING, String.format( "Could not auto-unpack lump %s into an array of objects of class %s", lump, what ), e); } - - // Track it (as ONE lump) - Track(lumpcache[lump],lump); - } else { - //System.out.println("cache hit on lump " + lump); - // Z.ChangeTag (lumpcache[lump],tag); - } + + // Track it (as ONE lump) + Track(lumpcache[lump], lump); + } if (lumpcache[lump] == null) { return null; } - + @SuppressWarnings("unchecked") final CacheableDoomObjectContainer cont = (CacheableDoomObjectContainer) lumpcache[lump]; return cont.getStuff(); - } - - public CacheableDoomObject CacheLumpNum(int lump) - { - return lumpcache[lump]; - } - - - /** Tells us if a class implements a certain interface. - * If you know of a better way, be my guest. - * - * @param what - * @param which - * @return - */ - - protected boolean implementsInterface(Class what, Class which) { - Class[] shit = what.getInterfaces(); - for (int i = 0; i < shit.length; i++) { - if (shit[i].equals(which)) - return true; - } + } + + public CacheableDoomObject CacheLumpNum(int lump) { + return lumpcache[lump]; + } + + @Override + public byte[] CacheLumpNameAsRawBytes(String name, int tag) { + return ((DoomBuffer) this.CacheLumpNum(this.GetNumForName(name), tag, null)).getBuffer().array(); + } + + @Override + public byte[] CacheLumpNumAsRawBytes(int num, int tag) { + return ((DoomBuffer) this.CacheLumpNum(num, tag, null)).getBuffer().array(); + } + + @Override + public DoomBuffer CacheLumpName(String name, int tag) { + return this.CacheLumpNum(this.GetNumForName(name), tag, DoomBuffer.class); + } + + @Override + public DoomBuffer CacheLumpNumAsDoomBuffer(int lump) { + return this.CacheLumpNum(lump, 0, DoomBuffer.class); + } - return false; - } - /* (non-Javadoc) - * @see w.IWadLoader#CacheLumpNameAsRawBytes(java.lang.String, int) - */ + @Override + public patch_t CachePatchName(String name) { + return this.CacheLumpNum(this.GetNumForName(name), PU_CACHE, patch_t.class); + + } + + @Override + public patch_t CachePatchName(String name, int tag) { + return this.CacheLumpNum(this.GetNumForName(name), tag, patch_t.class); + } - @Override - public byte[] CacheLumpNameAsRawBytes(String name, int tag) { - return ((DoomBuffer) this.CacheLumpNum(this.GetNumForName(name), tag, - null)).getBuffer().array(); - } - - /* (non-Javadoc) - * @see w.IWadLoader#CacheLumpNumAsRawBytes(int, int) - */ + @Override + public patch_t CachePatchNum(int num) { + return this.CacheLumpNum(num, PU_CACHE, patch_t.class); + } @Override - public byte[] CacheLumpNumAsRawBytes(int num, int tag) { - return ((DoomBuffer) this.CacheLumpNum(num, tag, - null)).getBuffer().array(); - } - - - /* (non-Javadoc) - * @see w.IWadLoader#CacheLumpName(java.lang.String, int) - */ - - @Override - public DoomBuffer CacheLumpName(String name, int tag) { - return this.CacheLumpNum(this.GetNumForName(name), tag, - DoomBuffer.class); - - } - - @Override - public DoomBuffer CacheLumpNumAsDoomBuffer(int lump) { - return this.CacheLumpNum(lump, 0, - DoomBuffer.class); - } - - - /* (non-Javadoc) - * @see w.IWadLoader#CachePatchName(java.lang.String) - */ - - @Override - public patch_t CachePatchName(String name) { - return this.CacheLumpNum(this.GetNumForName(name), PU_CACHE, - patch_t.class); - - } - - /* (non-Javadoc) - * @see w.IWadLoader#CachePatchName(java.lang.String, int) - */ - - @Override - public patch_t CachePatchName(String name, int tag) { - return this.CacheLumpNum(this.GetNumForName(name), tag, - patch_t.class); - } - - /* (non-Javadoc) - * @see w.IWadLoader#CachePatchNum(int, int) - */ - - @Override - public patch_t CachePatchNum(int num) { - return this.CacheLumpNum(num, PU_CACHE, patch_t.class); - } - - /* (non-Javadoc) - * @see w.IWadLoader#CacheLumpName(java.lang.String, int, java.lang.Class) - */ - @Override @W_Wad.C(W_CacheLumpName) - public T CacheLumpName(String name, int tag, Class what) { - return this.CacheLumpNum(this.GetNumForName(name.toUpperCase()), tag, what); - } - - // - // W_Profile - // - /* USELESS + public T CacheLumpName(String name, int tag, Class what) { + return this.CacheLumpNum(this.GetNumForName(name.toUpperCase()), tag, what); + } + + // + // W_Profile + // + /* USELESS char[][] info = new char[2500][10]; int profilecount; @@ -1100,315 +905,277 @@ void Profile() throws IOException { } f.close(); } */ - - /* (non-Javadoc) - * @see w.IWadLoader#isLumpMarker(int) - */ - @Override - public boolean isLumpMarker(int lump){ - return (lumpinfo[lump].size==0); - } - - /* (non-Javadoc) + + @Override + public boolean isLumpMarker(int lump) { + return (lumpinfo[lump].size == 0); + } + + /* (non-Javadoc) * @see w.IWadLoader#GetNameForLump(int) - */ - @Override - public String GetNameForLump(int lump){ - return lumpinfo[lump].name; - } - - // /////////////////// HASHTABLE SYSTEM /////////////////// - - // - // killough 1/31/98: Initialize lump hash table - // - - /** - * Maes 12/12/2010: Some credit must go to Killough for first - * Introducing the hashtable system into Boom. On early releases I had - * copied his implementation, but it proved troublesome later on and slower - * than just using the language's built-in hash table. Lesson learned, kids: - * don't reinvent the wheel. - * - * TO get an idea of how superior using a hashtable is, on 1000000 random - * lump searches the original takes 48 seconds, searching for precomputed - * hashes takes 2.84, and using a HashMap takes 0.2 sec. - * - * And the best part is that Java provides a perfectly reasonable implementation. - * - */ - - HashMap doomhash; - - protected void InitLumpHash() { - - doomhash = new HashMap(numlumps); - - //for (int i = 0; i < numlumps; i++) - // lumpinfo[i].index = -1; // mark slots empty - - // Insert nodes to the beginning of each chain, in first-to-last - // lump order, so that the last lump of a given name appears first - // in any chain, observing pwad ordering rules. killough + */ + @Override + public String GetNameForLump(int lump) { + return lumpinfo[lump].name; + } + + // /////////////////// HASHTABLE SYSTEM /////////////////// + // + // killough 1/31/98: Initialize lump hash table + // + /** + * Maes 12/12/2010: Some credit must go to Killough for first + * Introducing the hashtable system into Boom. On early releases I had + * copied his implementation, but it proved troublesome later on and slower + * than just using the language's built-in hash table. Lesson learned, kids: + * don't reinvent the wheel. + * + * TO get an idea of how superior using a hashtable is, on 1000000 random + * lump searches the original takes 48 seconds, searching for precomputed + * hashes takes 2.84, and using a HashMap takes 0.2 sec. + * + * And the best part is that Java provides a perfectly reasonable implementation. + * + */ + HashMap doomhash; + + protected void InitLumpHash() { + doomhash = new HashMap<>(numlumps); + + //for (int i = 0; i < numlumps; i++) + // lumpinfo[i].index = -1; // mark slots empty + // Insert nodes to the beginning of each chain, in first-to-last + // lump order, so that the last lump of a given name appears first + // in any chain, observing pwad ordering rules. killough for (int i = 0; i < numlumps; i++) { // hash function: - doomhash.put(lumpinfo[i].name.toUpperCase(), new Integer(i)); + doomhash.put(lumpinfo[i].name.toUpperCase(), Integer.valueOf(i)); } } - /* - * (non-Javadoc) - * - * @see w.IWadLoader#CheckNumForName(java.lang.String) - */ @Override @SourceCode.Compatible @W_Wad.C(W_CheckNumForName) - public int CheckNumForName(String name/* , int namespace */) { - final Integer r = doomhash.get(name); - // System.out.print("Found "+r); + public int CheckNumForName(String name/* , int namespace */) { + final Integer r = doomhash.get(name); + if (r != null) { + return r; + } + return -1; + } - if (r != null) { - return r; - } + @Override + public int[] CheckNumsForName(String name) { + list.clear(); + + // Dumb search, no chained hashtables I'm afraid :-/ + // Move backwards, so list is compiled with more recent ones first. + for (int i = numlumps - 1; i >= 0; i--) { + if (name.compareToIgnoreCase(lumpinfo[i].name) == 0) { + list.add(i); + } + } - // System.out.print(" found "+lumpinfo[i]+"\n" ); - return -1; - } + final int num = list.size(); + int[] result = new int[num]; + for (int i = 0; i < num; i++) { + result[i] = list.get(i); + } + + // Might be empty/null, so check that out. + return result; + } + + private final ArrayList list = new ArrayList<>(); - /* - * (non-Javadoc) - * - * @see w.IWadLoader#CheckNumForName(java.lang.String) - */ @Override - public int[] CheckNumsForName(String name) { - list.clear(); - - // Dumb search, no chained hashtables I'm afraid :-/ - // Move backwards, so list is compiled with more recent ones first. - for (int i = numlumps - 1; i >= 0; i--) { - if (name.compareToIgnoreCase(lumpinfo[i].name) == 0) { - list.add(i); - } - } + public lumpinfo_t GetLumpInfo(int i) { + return this.lumpinfo[i]; + } - final int num = list.size(); - int[] result = new int[num]; - for (int i = 0; i < num; i++) { - result[i] = list.get(i); - } + @Override + public void CloseAllHandles() { + List d = new ArrayList<>(); - // Might be empty/null, so check that out. - return result; - } - - private final ArrayList list=new ArrayList(); - - @Override - public lumpinfo_t GetLumpInfo(int i) { - return this.lumpinfo[i]; - } - - @Override - public void CloseAllHandles(){ - ArrayList d=new ArrayList(); - - for (int i=0;i 8) - { - marked[num_marked] = lump.clone(); - // System.err.printf("Marked %s as %d for %s\n",lump.name,num_marked,namespace); - marked[num_marked++].namespace = namespace; // killough 4/17/98 - result++; - } - } - else - lumpinfo[num_unmarked++] = lump.clone(); // else move down THIS list - } - - // Append marked list to end of unmarked list - System.arraycopy(marked, 0, lumpinfo, num_unmarked, num_marked); - - numlumps = num_unmarked + num_marked; // new total number of lumps - - if (mark_end) // add end marker - { - lumpinfo[numlumps].size = 0; // killough 3/20/98: force size to be 0 - //lumpinfo[numlumps].wadfile = NULL; - lumpinfo[numlumps].namespace = li_namespace.ns_global; // killough 4/17/98 - lumpinfo[numlumps++].name=end_marker; - } - - return result; - } - - public final static boolean IsMarker(String marker, String name) - { - // Safeguard against nameless marker lumps e.g. in Galaxia.wad - if (name==null || name.length()==0) return false; - boolean result= name.equalsIgnoreCase(marker) || - // doubled first character test for single-character prefixes only - // FF_* is valid alias for F_*, but HI_* should not allow HHI_* - (marker.charAt(1) == '_' && name.charAt(0) == marker.charAt(0) && - name.substring(1).equalsIgnoreCase(marker)); - - return result; - } - - @Override - public void UnlockLumpNum(int lump) { - lumpcache[lump]=null; - } - - @Override - public void InjectLumpNum(int lump, CacheableDoomObject obj){ - lumpcache[lump]=obj; - } - - //// Merged remnants from LumpZone here. + for (int i = 0; i < this.lumpinfo.length; i++) { + if (!d.contains(lumpinfo[i].handle)) { + d.add(lumpinfo[i].handle); + } + } + + int count = 1; + + for (InputStream e : d) { + try { + e.close(); + //System.err.printf("%s file handle closed",e.toString()); + count++; + } catch (IOException e1) { + LOGGER.log(Level.SEVERE, String.format("Could not close file handle (%d/%d)", count, d.size()), e1); + } + } + //System.err.printf("%d file handles closed",count); + } + + public static final int ns_global = 0; + public static final int ns_flats = 1; + public static final int ns_sprites = 2; + + /** + * Based on Boom's W_CoalesceMarkedResource + * Sort of mashes similar namespaces together so that they form + * a continuous space (single start and end, e.g. so that multiple + * S_START and S_END as well as special DEUTEX lumps mash together + * under a common S_START/S_END boundary). Also also sort of performs + * a "bubbling down" of marked lumps at the end of the namespace. + * + * It's convenient for sprites, but can be replaced by alternatives + * for flats. + * + * killough 4/17/98: add namespace tags + * + * @param start_marker + * @param end_marker + * @param namespace + * @return + */ + public int CoalesceMarkedResource(String start_marker, + String end_marker, li_namespace namespace) { + int result = 0; + lumpinfo_t[] marked = new lumpinfo_t[numlumps]; + // C2JUtils.initArrayOfObjects(marked, lumpinfo_t.class); + int num_marked = 0, num_unmarked = 0; + boolean is_marked = false, mark_end = false; + lumpinfo_t lump; + + // Scan for specified start mark + for (int i = 0; i < numlumps; i++) { + lump = lumpinfo[i]; + if (IsMarker(start_marker, lump.name)) // start marker found + { // If this is the first start marker, add start marker to marked lumps + if (num_marked == 0) { + marked[num_marked] = new lumpinfo_t(); + marked[num_marked].name = new String(start_marker); + marked[num_marked].size = 0; // killough 3/20/98: force size to be 0 + marked[num_marked].namespace = li_namespace.ns_global; // killough 4/17/98 + marked[num_marked].handle = lump.handle; + // No real use for this yet + marked[num_marked].wadfile = lump.wadfile; + num_marked = 1; + //System.err.printf("%s identified as FIRST starter mark for %s index %d\n",lump.name, + // start_marker,i); + } + is_marked = true; // start marking lumps + } else if (IsMarker(end_marker, lump.name)) // end marker found + { + // System.err.printf("%s identified as end mark for %s index %d\n",lump.name, + // end_marker,i); + mark_end = true; // add end marker below + is_marked = false; // stop marking lumps + } else if (is_marked || lump.namespace == namespace) { + // if we are marking lumps, + // move lump to marked list + // sf: check for namespace already set + + // sf 26/10/99: + // ignore sprite lumps smaller than 8 bytes (the smallest possible) + // in size -- this was used by some dmadds wads + // as an 'empty' graphics resource + if (namespace != li_namespace.ns_sprites || lump.size > 8) { + marked[num_marked] = lump.clone(); + // System.err.printf("Marked %s as %d for %s\n",lump.name,num_marked,namespace); + marked[num_marked++].namespace = namespace; // killough 4/17/98 + result++; + } + } else { + lumpinfo[num_unmarked++] = lump.clone(); // else move down THIS list + } + } + + // Append marked list to end of unmarked list + System.arraycopy(marked, 0, lumpinfo, num_unmarked, num_marked); + + numlumps = num_unmarked + num_marked; // new total number of lumps + + if (mark_end) // add end marker + { + lumpinfo[numlumps].size = 0; // killough 3/20/98: force size to be 0 + //lumpinfo[numlumps].wadfile = NULL; + lumpinfo[numlumps].namespace = li_namespace.ns_global; // killough 4/17/98 + lumpinfo[numlumps++].name = end_marker; + } + + return result; + } + + public final static boolean IsMarker(String marker, String name) { + // Safeguard against nameless marker lumps e.g. in Galaxia.wad + if (name == null || name.length() == 0) { + return false; + } + return name.equalsIgnoreCase(marker) + || // doubled first character test for single-character prefixes only + // FF_* is valid alias for F_*, but HI_* should not allow HHI_* + (marker.charAt(1) == '_' && name.charAt(0) == marker.charAt(0) + && name.substring(1).equalsIgnoreCase(marker)); + } + + @Override + public void UnlockLumpNum(int lump) { + lumpcache[lump] = null; + } + + @Override + public void InjectLumpNum(int lump, CacheableDoomObject obj) { + lumpcache[lump] = obj; + } + + //// Merged remnants from LumpZone here. HashMap zone; - /** Add a lump to the tracking */ - - public void Track(CacheableDoomObject lump, int index){ - zone.put(lump, index); - } - - @Override - public void UnlockLumpNum(CacheableDoomObject lump){ - // Remove it from the reference - Integer lumpno=zone.remove(lump); - - - // Force nulling. This should trigger garbage collection, - // and reclaim some memory, provided you also nulled any other - // reference to a certain lump. Therefore, make sure you null - // stuff right after calling this method, if you want to make sure - // that they won't be referenced anywhere else. - - if (lumpno!=null) { - lumpcache[lumpno]=null; - //System.out.printf("Lump %d %d freed\n",lump.hashCode(),lumpno); - } - } + /** Add a lump to the tracking */ + public void Track(CacheableDoomObject lump, int index) { + zone.put(lump, index); + } + + @Override + public void UnlockLumpNum(CacheableDoomObject lump) { + // Remove it from the reference + Integer lumpno = zone.remove(lump); + + // Force nulling. This should trigger garbage collection, + // and reclaim some memory, provided you also nulled any other + // reference to a certain lump. Therefore, make sure you null + // stuff right after calling this method, if you want to make sure + // that they won't be referenced anywhere else. + if (lumpno != null) { + lumpcache[lumpno] = null; + //System.out.printf("Lump %d %d freed\n",lump.hashCode(),lumpno); + } + } @Override public boolean verifyLumpName(int lump, String lumpname) { - + // Lump number invalid - if (lump<0 || lump>numlumps-1) return false; - - String name=GetNameForLump(lump); - + if (lump < 0 || lump > numlumps - 1) { + return false; + } + + String name = GetNameForLump(lump); + // Expected lump name not found - if (name==null || lumpname.compareToIgnoreCase(name)!=0) return false; - + if (name == null || lumpname.compareToIgnoreCase(name) != 0) { + return false; + } + // Everything should be OK now... return true; } @Override - public int GetWadfileIndex(wadfile_info_t wad1) { + public int GetWadfileIndex(wadfile_info_t wad1) { return wadfiles.indexOf(wad1); } @@ -1417,7 +1184,6 @@ public int GetNumWadfiles() { return wadfiles.size(); } - } //$Log: WadLoader.java,v $ @@ -1649,4 +1415,4 @@ public int GetNumWadfiles() { //Eclpise and see what gives from there. // //A good place to start is the testers/ directory, where you can get an idea of -//how a few of the implemented stuff works. \ No newline at end of file +//how a few of the implemented stuff works. diff --git a/src/w/filelump_t.java b/src/w/filelump_t.java index 22bbdf77..9019637e 100644 --- a/src/w/filelump_t.java +++ b/src/w/filelump_t.java @@ -9,64 +9,62 @@ * @author Maes * */ +public class filelump_t implements IReadableDoomObject, IWritableDoomObject { -public class filelump_t implements IReadableDoomObject, IWritableDoomObject { - public long filepos; - public long size; // Is INT 32-bit in file! - public String name; // Whatever appears inside the wadfile + public long filepos; + public long size; // Is INT 32-bit in file! + public String name; // Whatever appears inside the wadfile public String actualname; // Sanitized name, e.g. after compression markers - - public boolean big_endian=false; // E.g. Jaguar - public boolean compressed=false; // Compressed lump - - public void read(DataInputStream f) throws IOException{ + + public boolean big_endian = false; // E.g. Jaguar + public boolean compressed = false; // Compressed lump + + public void read(DataInputStream f) throws IOException { // MAES: Byte Buffers actually make it convenient changing byte order on-the-fly. // But RandomAccessFiles (and inputsteams) don't :-S - if (!big_endian){ - filepos=DoomIO.readUnsignedLEInt(f); - size=DoomIO.readUnsignedLEInt(f); + if (!big_endian) { + filepos = DoomIO.readUnsignedLEInt(f); + size = DoomIO.readUnsignedLEInt(f); } else { - filepos=f.readInt(); - size=f.readInt(); + filepos = f.readInt(); + size = f.readInt(); } - + // Names used in the reading subsystem should be upper case, // but check for compressed status first - name=DoomIO.readNullTerminatedString(f,8); - - - char[] stuff= name.toCharArray(); - + name = DoomIO.readNullTerminatedString(f, 8); + + char[] stuff = name.toCharArray(); + // It's a compressed lump if (stuff[0] > 0x7F) { - this.compressed=true; - stuff[0]&=0x7F; + this.compressed = true; + stuff[0] &= 0x7F; } - - actualname=new String(stuff).toUpperCase(); - - + + actualname = new String(stuff).toUpperCase(); + } - public static int sizeof(){ - return (4+4+8); + public static int sizeof() { + return (4 + 4 + 8); } @Override public void write(DataOutputStream dos) throws IOException { - if (!big_endian){ + if (!big_endian) { DoomIO.writeLEInt(dos, (int) filepos); DoomIO.writeLEInt(dos, (int) size); } else { - dos.writeInt((int) filepos); - dos.writeInt((int) size); + dos.writeInt((int) filepos); + dos.writeInt((int) size); } DoomIO.writeString(dos, name, 8); - + } - -} \ No newline at end of file + +} diff --git a/src/w/li_namespace.java b/src/w/li_namespace.java index 7dbd5f4d..34272d86 100644 --- a/src/w/li_namespace.java +++ b/src/w/li_namespace.java @@ -1,14 +1,13 @@ package w; /** killough 4/17/98: namespace tags, to prevent conflicts between resources */ - public enum li_namespace { - ns_global, - ns_sprites, - ns_flats, - ns_colormaps, - ns_prboom, - ns_demos, - ns_hires //e6y - } // haleyjd 05/21/02: renamed from "namespace" + ns_global, + ns_sprites, + ns_flats, + ns_colormaps, + ns_prboom, + ns_demos, + ns_hires //e6y +} // haleyjd 05/21/02: renamed from "namespace" diff --git a/src/w/lumpinfo_t.java b/src/w/lumpinfo_t.java index 42268ea3..c9c0b5fb 100644 --- a/src/w/lumpinfo_t.java +++ b/src/w/lumpinfo_t.java @@ -26,47 +26,47 @@ enum { wad_source_t source; int flags; //e6y } lumpinfo_t; */ +public class lumpinfo_t implements Cloneable { -public class lumpinfo_t implements Cloneable{ - public String name; - public InputStream handle; - public long position; - public long size; - // A 32-bit hash which should be enough for searching through hashtables. - public int hash; - // A 64-bit hash that just maps an 8-char string to a long num, good for hashing - // or for direct comparisons. - //public long stringhash; - // Intepreting the first 32 bits of their name as an int. Used in initsprites. - public int intname; - // public int next; - //public int index; - - // For BOOM compatibility - public li_namespace namespace; - public wadfile_info_t wadfile; - - public int hashCode(){ - return hash; - } - - public String toString(){ - return (name +" "+ Integer.toHexString(hash)); - } - - public lumpinfo_t clone(){ - lumpinfo_t tmp=new lumpinfo_t(); - tmp.name=name; // Well... a reference will do. - tmp.handle=handle; - tmp.position=position; - tmp.size=size; - tmp.hash=hash; - tmp.intname=intname; - tmp.namespace=namespace; - tmp.wadfile=wadfile; - - return tmp; - - } - + public String name; + public InputStream handle; + public long position; + public long size; + // A 32-bit hash which should be enough for searching through hashtables. + public int hash; + // A 64-bit hash that just maps an 8-char string to a long num, good for hashing + // or for direct comparisons. + //public long stringhash; + // Intepreting the first 32 bits of their name as an int. Used in initsprites. + public int intname; + // public int next; + //public int index; + + // For BOOM compatibility + public li_namespace namespace; + public wadfile_info_t wadfile; + + public int hashCode() { + return hash; } + + public String toString() { + return (name + " " + Integer.toHexString(hash)); + } + + public lumpinfo_t clone() { + lumpinfo_t tmp = new lumpinfo_t(); + tmp.name = name; // Well... a reference will do. + tmp.handle = handle; + tmp.position = position; + tmp.size = size; + tmp.hash = hash; + tmp.intname = intname; + tmp.namespace = namespace; + tmp.wadfile = wadfile; + + return tmp; + + } + +} diff --git a/src/w/name8.java b/src/w/name8.java index 7180daaa..65016ff3 100644 --- a/src/w/name8.java +++ b/src/w/name8.java @@ -1,24 +1,25 @@ package w; public class name8 { - private byte[] s; - static byte[] ss=new byte[9]; - public int[] x; + + private byte[] s; + static byte[] ss = new byte[9]; + public int[] x; public long hash; - - public name8(String name){ - s=new byte[9]; - x=new int[2]; + + public name8(String name) { + s = new byte[9]; + x = new int[2]; // in case the name was a full 8 chars this.s[8] = 0; - - byte[] tmp=name.getBytes(); - System.arraycopy(tmp, 0, this.s, 0, Math.min(8,tmp.length)); - this.x[0]=byteArrayToInt(s,0); - this.x[1]=byteArrayToInt(s,4); - this.hash=byteArrayToLong(s,0); + + byte[] tmp = name.getBytes(); + System.arraycopy(tmp, 0, this.s, 0, Math.min(8, tmp.length)); + this.x[0] = byteArrayToInt(s, 0); + this.x[1] = byteArrayToInt(s, 4); + this.hash = byteArrayToLong(s, 0); } - + /** Returns a 64-bit number that maps directly to the ASCII * 8-bit representation of a fixed-length 8 char string. * It's for all effects and purposes a unique 64-bit hash, and can be used to @@ -27,53 +28,50 @@ public name8(String name){ * @param name * @return */ - - public static long getLongHash(String name){ + public static long getLongHash(String name) { // in case the name was a full 8 chars - for (int i=0;i