Dear Diary (Updates)

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Andrew Davie

I'm going to try and keep a development blog. Watch this space...


I've been working on the 'blitter' - the software sprite draw. The challenge is/was mostly to have it working efficiently both on the title/menu screen (which is 32 pixel asymmetrical mirrored playfield), and on the normal game screen (a 40 pixel asymmetrical NON-mirrored playfield). The former uses PF1/PF2/PF2(m)/PF1(m) with a 6-sprite overlay, and the latter uses PF0/PF1/PF2/PF0/PF1/PF2 with just regular sprites GRP0 and GRP1 overlaid. It's been tricky to get the one routine to do both, but I'm close.

There's a discontinuity in the center about which the software sprites themselves flip (I don't want them to). But it's close, as I said.

I want to have the routine working both on menu and game screens so I can use it wherever I want. For example, I'd like the menu/title screen to have a bunch of large letters (as we see here) starting in random positions and 'floating' into their correct position. This would be kind of inline with the basic game concept, which would be cool.

Andrew Davie

I fixed the blitter (the software playfield sprite system) - it's now working properly for the menu screen layout (32 wide, asymmetric, mirrored PF).  I did a preliminary mockup background for the title screen - it's meant to be a sort of iceberg patch. I think it looks mostly OK.


That's it for today. I did a LOT of cleanup, removing redundant stuff and generally "picking up the rubbish" in the various directories. I've also refined, somewhat, the toolset and how it operates - which directories it uses, where files are placed, etc.

Andrew Davie

I installed the SaveKey code today. It took me quite some effort to get installed/working in GridLock; now it's straightforward because I can essentially copy/paste sections of code. I might write it up soon, as the initialisation bit is pretty cool.

Andrew Davie

Had a really frustrating bug for the last couple of days and progress has been slow. Essentially I installed the SaveKey stuff OK by basically copy/paste code from other projects. But when I tried to clean up the SK variables (by removing redundant ones) the game simply crashed. I couldn't understand it, and I couldn't isolate the problem.

Eventually, though, I did find it. That old DSPTR error was hidden in some code - where originally I had the "TO ARM" variables at address 0, it all worked with a hi/lo write of DSPTR. But when I inserted the SK variables before the "TO ARM" variables, those latter variables no longer had a HI/LO of 0. So things were very screwed indeed.

I fixed that, and it's all working nicely now. I also went back through a number of earlier projects and found the exact same error in the source code, so I fixed those too.  One of those projects was "Wen Hop?" which is actually quite remarkable - that whip-like weapon is pretty unique.

Binary attached of that, just so it's easy for you to look-see.

A shout out to @JetSetIlly for his recent update to the Gopher emulator. In particular, the SaveKey EEPROM area is now very intuitive - it can automatically show only those "pages" which have been modified at runtime. What this means, essentially, is that when I run my game and want to look at the SaveKey data... it's quick and automatic. Screenshot attached...



Andrew Davie

Well, I seem to have morphed into working on a karate game. Uh, not really - but it turns out that I have a sprite sheet for karate animations handy, and they're wide enough to be useful for testing the sprite matrix stuff. Not that I've actually worked on THAT side of things.

Anyway, I've posted some examples of the draw and played around with colours - and it's looking pretty good. The sprite system has been working on the menu screen - that's the asymmetrical mirrored playfield (32 pixels wide) PF1/PF2/PF2m/PF1m.  As an aside, I use the 32-wide because that's the limitation of my 6-sprite + playfield menu system. I do know it's possible to have the 6-sprite + PF at 40 pixels; it was done by ZackAttack in his work with me on Elite. But in any case, THIS implementation has 32.

So, I thought now that the menu version of the sprite draw is working, I'd move back to the 40 pixel asymmetrical, NON-mirrored playfield (PF0/PF1/PF2/PF0/PF1/PF2) version. I was expecting a fair bit of work to get that functional TOO (with the same draw/blit code) but actually it was a 30 second fix; just a minor offset in the position of the 'cut' between left and right parts of the screen.

So, now I have a fully functional draw that works for both the mirrored and for non-mirrored case. It's quite complex code, but seems to run sufficiently fast. I'm able to have around 4 of the large karate guys doing stuff on screen at the same time.

So next, I need to improve the visuals on the main game kernel (40 pix) - stuff like the palette, and disabling some of the lemming scrolling. Or not. I'm not sure yet now I think about it. A scrolling background for a fighting game would be OK, too.  I'm doing all this, by the way, in a git branch - so it will be easy to revert back to the squarebergs core whenever needed. I have, however, found and fixed quite a few things so perhaps this will be the new core - at which point I'll copy it to another project in anticipation of a future karate game.

The terrible image attached is the sprite draw running on the main game kernel screen (40 pix). It's terrible because I haven't written the correct palette down the screen (it's dynamic and has to be changed on every scanline on every frame).  But I can clearly see the sprites are correct without any discontinuity as I move them about the screen.

The whole point of my 'dear diary' is to show things as/when I feel like updating the blog; not just the finished/polished versions of things.


 

Andrew Davie

#5
I now have the sprite draw (non-matrix; just a strip at this stage) working on the 40-pix PF with the scrolling background. I used the graphics from Lemmings for now - but in essence we can put any background there and have the sprites drawn over the top.


I really need to start working on that sprite matrix code, so the fighter frames are complete and not cut in half. 

Binary attached.

Andrew Davie

Gonna bite the bullet and get started on the matrix sprites. Gotta get my arse in gear, as we say here. So there are a couple of things to do.  First is to modify the tool (sp.py) which does all the sprite animation isolation from the sprite sheet and then encodes each frame into c-structures (just 8-bit wide strips, essentially). That needs to create multiple strips as required, for each frame, rather than just the first. I figure I can re-use the original format and just treat multiple-strip-wide sprites as multiple sprite strips that must be drawn together.  That's going to take me probably a day to get working.

Meanwhile, sprites need a few things - center points are critical for proper and easy frame display. But also at some point I need/want collision boxes. I plan to do both of these by somehow having a 'companion' set of images or sprite sheets which let me draw stuff on layers (such as a pixel in the 'center layer' lets me automatically draw the center point for each frame), and perhaps a few collision 'layers' which lets me define collision boxes.

That's all going to be way more tricky; PIL/Pillow the python image processing library I use does not support layers much if at all. So I'm forced to either use separate files (companions) or maybe move towards a library that supports Gimp xcf format.  But, probalbly going to be difficult/messy. I'm gonna have to think about that one.

Putting this here to put pressure on myself to get something done sooner rather than later.

Andrew Davie

#7
Well, that went quickly!  Barely an hour later and I have a functional 'matrix sprite draw'. The way I did it was kept the original sprite draw code essentially unchanged; draw a vertical strip of 8-pixel wide sprite data. But I changed the call to it to parse the new sprite data format and call the draw multiple times, one for each strip.

The format I chose for the data is basically the number of columns (strips of 8-pixel wide data), and then for each column a y-offset and column height. The idea is that each column does not have to be the full height of the entire sprite matrix; top and bottom blank rows are stripped -- giving savings in code size.

It went really smoothly. Funny how you put off some things for so long and in the end it's relatively simple. So much for the "impossible task" that I was putting off for so long.

What you're looking at in the video is that a frame is now more than 8-pixels wide; in effect the system can now draw arbitrary-width, arbitrary-height sprites. Draw what you want, run it through the tool, and it will display. That's all you do.


Next up -- defining center points efficiently.

Andrew Davie

It took me a lot of head scratching, but I now have the center point offsets working properly. In the video I show how I use GIMP to define the center points. Essentially the sprite sheet contains all the frames, and I have a separate layer for the center points. I put a pixel wherever I want on each frame, and export that layer to the appropriate file (just with a name extension 'centerpoints'). From there on it's all automatic - the tool(s) split the sprite sheet into individual frames, scan for the center points and add all that to the c structures ready for display. It's really quick.

The head scratching was because I have a manifest file which was originally designed to allow me to manually enter center points and keep them even when new graphics came along. It worked so well that it over-rode whatever center points I defined with the new method!

Anyway, now in the binary you see the frame is basically shifting around the static center point which is mostly defined on the tip of a hand for all the frames. Mostly.

The video attempts to show a bit of the workflow and tools used.



Andrew Davie

Today I did some work on the sprite conversion tool, fixing up a few issues with the custom naming of frames and the manifest.txt file. Then I went through and put correct center points on all the fighter frames I'm using as the test sprite set. And THEN I did a quick and dirty animation sequence, just to see how it would look. Remembering everything is placeholder and not hand-cleaned or optimised; just a super hi-res sprite sheet downconverted to rough size I wanted. And then run through the tool.

So, it's reasonable. Has potential. Clearly, if things are moving they will look better than static frames, because the static frames are painfully low-resolution. I had a hard time making the GridLock cars look good. I expect a fighting game would look.... chunky, but maybe OK.



Andrew Davie

OK, a few interesting things. One shocking, maybe....

Firstly since I have the fundamentals of a fighting game here, I thought I'd move my current WIP over to a new project and allow that to keep progressing towards a fighting game. I called it 'wotef' for hopefully obvious reasons.

Secondly, I decided to install an AI code assistant - I chose Jetbrains AI just because I do like pyCharm and somewhat trust the company. So, got it installed and not knowing how to use it, I just entered into chat...

Quote@colour.c analyse this file and comment on potential code improvements

It returned a whole heap of stuff, which was a bit daunting - and I've just reviewed the very first one and it is indeed a bug. Some of the other stuff looks on target, too. So I fixed the first and will review the rest. But... gosh... it's a bit daunting actually.

Here's the entirety of the reply...

QuoteHere are focused, practical suggestions to improve colour.c. I'll keep the Atari 2600/CDFJ constraints in mind (tight cycles, RAM-mapped I/O, TV system quirks).

High-impact fixes and cleanups
- Potential bug in background fill loop:
  - You build a 32-bit packed value bg but assign it to bkCol where bkCol is unsigned char*. That writes only the low 8 bits repeatedly, not four bytes at a time.
  - Options:
    - If you intended 32-bit writes, cast to uint32_t* and ensure alignment and correct loop bound:
      - Caution: On 2600/CDFJ memory layout and alignment can be special. Only do this if unaligned 32-bit writes are safe.
    - Otherwise stick to byte writes (safe and clear) and unroll for speed if needed.

  Example safe version:
  ```c
  // C
  unsigned char *bkCol = RAM + _BUF_COLUBK;
  unsigned char bgCol = flashTime ? ARENA_COLOUR : 0;

  for (int j = 0; j < _ARENA_SCANLINES; ++j) {
      bkCol[j] = bgCol;
  }
  ```

  If you really want 32-bit blasting and it's supported:
  ```c
  // C
  uint32_t bg32 = (bgCol << 24) | (bgCol << 16) | (bgCol << 8) | bgCol;
  uint32_t *bk32 = (uint32_t *)(RAM + _BUF_COLUBK);
  for (int i = 0; i < _ARENA_SCANLINES / 4; ++i) {
      bk32 = bg32;
  }
  // Handle remainder if _ARENA_SCANLINES not multiple of 4
  for (int r = (_ARENA_SCANLINES & ~3); r < _ARENA_SCANLINES; ++r) {
      bkCol[r] = bgCol;
  }
  ```
  Make sure _ARENA_SCANLINES is divisible by 4 or handle remainder.

- Operator precedence in setICCPalette random color generation:
  - Current: palette[0] = (rangeRandom(16) << 4) | rangeRandom(5) + 4;
  - Due to precedence, this is (hiNibble) | (rangeRandom(5) + 4). That's fine if intended, but often you want high nibble random, low nibble random in [4..8]:
    - If you intended "low = random(5) + 4 then OR", add parentheses:
      ```c
      // C
      palette[0] = (rangeRandom(16) << 4) | (rangeRandom(5) + 4);
      ```
    - If you intended low nibble random in [4..8], keep as above. If you intended [4..8] inclusive, random(5)+4 gives [4..8] indeed.

- Flash logic clarity and safety:
  - doFlash uses compound expression that mutates flashTime inside condition and reads ARENA_COLOUR--:
    ```c
    if (
      mm_tv_type == SECAM ||
      (flashTime = ARENA_COLOUR-- & 0xF) == 1)
        ARENA_COLOUR = 1;
    ```
  - This is dense and a bit risky for future maintenance. Consider rewriting for readability and to avoid relying on sequencing:

  ```c
  // C
  void doFlash(void) {
      if (!flashTime) return;

      if (flashTime < 0) {
          if (++flashTime == 0) {
              ARENA_COLOUR = 1;
          }
          return;
      }

      // flashTime > 0
      flashTime--;
      if (flashTime == 0) {
  #if ENABLE_SECAM
          if (mm_tv_type == SECAM) {
              ARENA_COLOUR = 1;
              return;
          }
  #endif
          unsigned char lum = ARENA_COLOUR & 0xF;
          ARENA_COLOUR--; // side effect remains, if intended
          if (lum == 1) {
              ARENA_COLOUR = 1;
          }
      }
  }
  ```
  - Double-check the intent of decrementing ARENA_COLOUR on the last tick. If the decrement is only used to extract low nibble, compute lum first without side-effect and apply the decrement only if needed.

- Roller handling consistency:
  - Two different "roller" behaviors exist (toggle in setPalette via roller ^= 1, and ">1 wrap" in rollICC / comments for iCC):
    - Document and unify intended range of roller. If setPalette needs {0,1} toggle, keep as is; if you need 0..2 cycling elsewhere, consider a separate variable for 3-phase rollers to avoid accidental cross-effects.

- Magic constants and bounds:
  - adjustBrightness clamps to 0..14. If 15 is reserved, comment why 14 is the max.
  - setBrightness increments offset by 2 with bounds ±14. Given clamp uses ±14, this is consistent; add a comment that TIA luminance 0..14 is valid.

- SECAM conversion edge cases:
  - secamConvert changes black to white when luminance >= 4. That's an interesting heuristic. Consider a comment explaining the visual rationale, and whether this should depend on gameplay context.

- Global state clarity:
  - Globals: roller, firstCol, palette, flashTime, luminanceOffset.
  - Consider prefixing with g_ (e.g., gRoller) or moving into a struct to make side-effects explicit. In constrained environments you may keep globals but a naming convention helps.

Performance and code-size tweaks
- Avoid repeated convertColour calls per scanline when using the same palette entries:
  - In setPalette you already compute c0,c1,c2 once. Good. Ensure convertColour is cheap; it does a TV-type switch each time. If TV type doesn't change during frame rendering, you can hoist mm_tv_type into a local and possibly branch once.

  ```c
  // C
  const int tv = mm_tv_type;
  char c0 = convertColour(palette[roller]);
  // ...
  ```

- rollAlong array can be static const and of unsigned char; also avoid recomputing the index rollAlong[roller + 1] with an out-of-bounds risk:
  - The current rollAlong has 4 elements: {1,2,0,1}; with roller in {0,1}, roller+1 is safe. Add an assert or comment stating roller is 0/1.
  - If you ever switch to 0..2 roller, adjust mapping accordingly.

Robustness and readability
- Types:
  - Prefer fixed-width types for hardware color bytes: uint8_t for colours, int8_t for signed luminanceOffset, int16_t for counters if needed. This documents intent and avoids compiler-dependent sizes.

  ```c
  // C
  #include <stdint.h>
  static int8_t luminanceOffset = 0;
  static uint8_t flashTime = 1; // if non-negative only; else keep int
  ```

- Function naming:
  - setICCPalette takes a 2D palette buffer and mutates it when firstCol is true. That's surprising for a function named "set...". Consider separating "init ICC palette randomness" from "apply ICC palette to RAM" or rename to initAndApplyICCPalette.

- Comment stale code:
  - There's commented-out palette code. If kept for reference, add a brief comment header explaining why it's retained and when to switch modes (pCC vs iCC).

- Explicit parentheses:
  - In convertColour PAL branch, consider making the mapping intent explicit:
    ```c
    // C
    // Map hue via __XLATE, keep luminance nibble
    colour = (EXTERNAL(__XLATE)[colour >> 4] & 0xF0) | (colour & 0x0F);
    ```

Small correctness touches
- setFlash2 assigns ARENA_COLOUR = convertColour(colour); That means flash colour respects current TV mapping and brightness, good. If flash should be "pure" hardware colour bypassing brightness dial, consider whether adjustBrightness should be skipped for flashes.

- rollICC currently wraps at >1. The comment suggests it once referenced RAM[_SK_CHRONOCOLOUR]. If you restore that dependency later, keep rollICC consistent with the consumer functions.

Potential refactors
- Centralize TV color conversion:
  - convertColour does SECAM conversion and PAL hue translation, then calls adjustBrightness. If you sometimes need raw hardware values, expose a convertColourNoBrightness helper, or an adjust flag.

- Make ICC title palette handling consistent:
  - icc_title_palette is a 1x3 static array, but setICCPalette assumes a dynamic palette buffer to write to. If icc_title_palette is intended as a seed/constant, don't mutate it; instead write into a working buffer.

  ```c
  // C
  static unsigned char icc_work_palette[1][3];
  void setICCPalette(unsigned char palette[][3]) {
      // or use icc_work_palette directly
  }
  ```

Style and safety
- Use braces for single-line ifs in logic-heavy code (doFlash, setBrightness) to avoid footguns during future edits.
- Document units for "time" in flashTime (frames, ticks?) and meaning of negative values.

Example tightened versions of a few functions
```c
// C
void setICCPalette(unsigned char palette[][3]) {
    if (firstCol) {
        FLASH(0xD2, 10);
        for (int i = 0; i < 3; i++) {
            unsigned char hi = (unsigned char)(rangeRandom(16) << 4);
            unsigned char lo = (unsigned char)(rangeRandom(5) + 4); // [4..8]
            palette[0] = (unsigned char)(hi | lo);
        }
        firstCol = false;
    }

    int roll = roller;
    unsigned char *p = RAM + _BUF_MENU_COLUPF;
    for (int line = 0; line < _ARENA_SCANLINES; line += 3) {
        for (int i = 0; i < 3; i++) {
            *p++ = (unsigned char)convertColour(palette[0][roll]);
            roll++;
            if (roll > 2) roll = 0;
        }
    }
}

unsigned char adjustBrightness(unsigned char colour) {
    int lum = (colour & 0x0F) + luminanceOffset;
    if (lum < 0) lum = 0;
    if (lum > 14) lum = 14; // TIA luminance range 0..14
    return (unsigned char)((colour & 0xF0) | lum);
}

int convertColour(unsigned char colour) {
    switch (mm_tv_type) {
#if ENABLE_SECAM
    case SECAM:
        colour = secamConvert(colour);
        break;
#endif
    case PAL:
    case PAL_60: {
        unsigned char hue = EXTERNAL(__XLATE)[colour >> 4];
        colour = (unsigned char)((hue & 0xF0) | (colour & 0x0F));
        break;
    }
    default:
        break;
    }
    return (int)adjustBrightness(colour);
}

void setPalette(void) {
    // Toggle two-phase roller
    roller ^= 1;

    unsigned char *bkCol = RAM + _BUF_COLUBK;
    unsigned char bgCol = flashTime ? ARENA_COLOUR : 0;

    for (int j = 0; j < _ARENA_SCANLINES; ++j) {
        bkCol[j] = bgCol;
    }

    static const unsigned char rollAlong[4] = {1, 2, 0, 1}; // roller must be 0/1
    char c0 = convertColour(palette[roller]);
    char c1 = convertColour(palette[rollAlong[roller]]);
    char c2 = convertColour(palette[rollAlong[roller + 1]]);

    unsigned char *pfCol = RAM + _BUF_COLUPF;
    for (int i = 0; i < _ARENA_SCANLINES; i += 3) {
        pfCol[0] = (unsigned char)c0;
        pfCol[1] = (unsigned char)c1;
        pfCol[2] = (unsigned char)c2;
        pfCol += 3;
    }
}
```

If you want, I can:
- Convert globals to fixed-width types in this file.
- Rewrite doFlash for clarity while preserving behavior.
- Add lightweight assertions/comments to document roller invariants and SECAM rules.

Andrew Davie

#11
Some more experience with JetBrains AI assistant. It's pretty good. It was suprisingly good at understanding the 6502 code sections, and even correctly commented all the cycle counts on the kernels for me. I'm a bit frightened by how "good" these AI assistants are getting.  Quite a few marginal bugs found in the code already. A few off-by ones, a few observations about behaviour that I fixed. One or two definite bugs that have been in the codebase for some time.

I guess I have to recommend it at this point.