Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Games development on ELKS #871

Open
toncho11 opened this issue Nov 17, 2020 · 197 comments
Open

Games development on ELKS #871

toncho11 opened this issue Nov 17, 2020 · 197 comments
Labels

Comments

@toncho11
Copy link
Contributor

toncho11 commented Nov 17, 2020

Let's take this example of Snake compiled by Turbo C:

https://github.com/ashmew2/snake-game/blob/master/Final.cpp

  • One needs to replace DOS.h calls with ELKS libc or syscalls. Here it looks like only delay, sound and nosound are used. We can omit sound for now.
  • One needs to compile conio.h. An implementation exists based on ncurses, but then one needs to port ncusrses too. But actually only kbhit, clrscr and getch are used in this game! So 3 out 8 functions from conio.h.
  • And finally one needs to rewrite the needed functions from graphics.h. Functions needed for this game are: fillpoly, drawpoly, settextstyle, outtextstyle, outtextxy, setfillstyle, floodfill, setcolor, rectangle

@ghaerr Maybe graphics.h can be mapped to Nano-X? But on 8086 computers Naxo-X looks slow for games. For example

@toncho11 toncho11 added the bug Defect in the product label Nov 17, 2020
@pawosm-arm
Copy link
Contributor

The topic of porting graphic libraries and 90's games to ELKS should be preceded by a more substantial discussion regarding the graphics in ELKS in general. I never had occasion to work with nx before meeting ELKS (my past experience with NuttX from which nx originated never went beyond the nsh command line sessions), so I can't really say how good or bad this library is. I just have impression that I already saw things more mature than nx, like Photon on QNX or DirectFB on Linux. Even things like GUILib for multiplatform SDL library seemed more mature despite all of its limitations. And there is also John Elliott's SdSDL library for SDL which emulates GSX and VDI graphics that originates from CP/M and DOS (before MS Windows). And that was the direction I was looking for: John Elliot's fork of GSX/VDI-based GEM (the mighty FreeGEM) works really lovely on both of my XT machines (one 8088, one 8086 based), far better than nx on ELKS on the same machines, though I suspect the secret is in the underlying OS: there's no multitasking in DOS, hence GEM can consume all of the CPU time for handling mouse-driven graphics operations. Yet anyway, it only shows that doing GUI on XT is possible and the user experience does not need to suffer. BTW, Windows 3.0 was the last version of MS Windows that could be installed on 8086 and it offered some kind of multitasking, still being capable of providing good enough user experience.

One more thing I remember from the past. My very first Linux back in the 90s (some very early version of RedHat) was installed on some very low end i386 machine equipped with ISA 8-bit VGA graphics card (probably the same I've installed during ELKS times into my Turbo XT to replace Hercules mono graphics card that was installed into it originally). Running X at 640x480x16 offered terrible user experience and 16-color palette looked awful. Yet I managed to force X server to run with 320x200x256 mode and it really started to fly! The user experience was amazing. I guess two factors were playing their role here: lower resolution and a whole byte per pixel which simplified all of the graphic operations. I think it's one of the possible directions nx on ELKS could also explore. In the end, those demos don't really display much of the content on screen. See how GEOS looks like on C64, it's low resolution and it's still really cool (speaking of GEOS, it was ported to 8086 XT's too, yet to my disappointment its final XT-compatible version was working much slower than FreeGEM).

@tkchia tkchia added the enhancement New feature label Nov 17, 2020
@tkchia
Copy link
Collaborator

tkchia commented Nov 17, 2020

Hello @toncho11, hello @pawosm-arm,

Well, the graphics stuff aside --- I think @ghaerr can comment further on that --- it is obvious that porting Turbo C++ specific code to, well, anything that is not Turbo C++, is going to take some effort. I do not see this as a bug per se: there is no real urgent need for ELKS to be compatible with a non-standard programming interface (even if it will be a "nice thing to have").

@pawosm-arm
Copy link
Contributor

I remember the times when porting from Turbo C++ was all about getting rid of '#include <conio.h>' :)

@tkchia
Copy link
Collaborator

tkchia commented Nov 17, 2020

Hello @toncho11 , hello @pawosm-arm,

I remember the times when porting from Turbo C++ was all about getting rid of '#include <conio.h>' :)

Well, I guess there are different ways of doing the porting task. :-|

In case you missed it: on the MS-DOS front, I have been working on a libi86 project. It aims to implement, for gcc-ia16, non-standard C library extensions that are present in the Open Watcom C runtime and (to some degree) the Turbo C++ runtime.

I am currently keeping this library separate from the underlying C library (newlib-ia16) that implements the core C99 and POSIX functionality.

(<conio.h> support is mostly complete (for MS-DOS, that is). As for graphics, both Open Watcom and Turbo C++ have very rich graphics libraries, and it is not very easy to "just reimplement" them. And that is even without having to worry about multi-tasking or multi-window interfaces...)

If there is real demand, perhaps I can look into extending the scope of libi86 to also work on ELKS, in addition to MS-DOS.

Thank you!

@pawosm-arm
Copy link
Contributor

I wonder how far we can go with this... It's like with Fuzix for Z80 machines where ability to run CP/M programs was considered.

@Mellvik
Copy link
Contributor

Mellvik commented Nov 17, 2020 via email

@toncho11
Copy link
Contributor Author

Nice digression. We need that 👍

By the way is it possible to change the priority of a process in ELKS? There is a nice sys call, but no nice command? Maybe this will make a game run a bit faster.

While we wait for @ghaerr I think making a layer that allows for quick porting of turbo C programs and games will be interesting. I mean I want to use ELKS and have software for it. Ok some people are focused only on the kernel and they do not care about userland, but not me.

@pawosm-arm
Copy link
Contributor

@toncho11 I think the 'bug' label here is slightly misleading.

@Mellvik,

Interesting digression @pawosm-arm, I'm curious: anything in particular from cp/m you're interested in?

Although interesting, this digression should not grow here as it barely touches the matter of this ticket.
As for CP/M, having beefed up Spectrum +3 in a workable condition I've got a native machine to run CP/M Plus with all of the stuff I remember from the 80s. I also have Spectrum Next that also can boot CP/M Plus yet comparing to +3, the support for on-board peripherals isn't complete which leaves me with a sense of disappointment.

It may be worthwhile remembering that cp/m and fuzix ran on a different and incompatible architecture (from x86), and most programs were written in assembler. Still, I have 3 operating cp/m machines...

I'm slightly confused here. Both Fuzix and CP/M were originally targeting Z80 machines hence the idea of running CP/M software in Fuzix wasn't that terrible (considering simplicity of CP/M). And this simplicity was a key here: I suspect providing similar compatibility layer in ELKS to enable running 8088/8086 DOS programs would be more difficult.

In case of CP/M, attempts to support other architectures (e.g. CP/M-86 or CP/M-68k) never gained popularity due to competition from the natively developed operating systems that were better suited to those machines.

Anyway, there is some trace of the feature I've mentioned here in Fuzix's git repo: https://github.com/EtchedPixels/FUZIX/blob/master/Applications/cpm/runcpm.c

EOOT.

@ghaerr
Copy link
Owner

ghaerr commented Nov 18, 2020

Hello everyone,

Well, there's a lot that got discussed today, here's a few of my thoughts...

one needs to rewrite the needed functions from graphics.h. Functions needed for this game are: fillpoly, drawpoly, settextstyle, outtextstyle, outtextxy, setfillstyle, floodfill, setcolor, rectangle

Yes, defining a distinct set of graphics functions, preferably across more than just one game, is a great way to start. Then, the entire function-set can be analyzed a bit and a graphics engine/library used as an API-bridge. Having done a heck of a lot of graphics engine programming, I also highly recommend keeping things simple in the beginning, and adding complexity only after getting the initial game(s) initially drawing. For instance, fill, draw poly and rectangle are pretty basic, but floodfill can get complicated. Text output is a whole 'nother discussion, but if a fixed-size font can be used, things are simplified considerably.

Maybe graphics.h can be mapped to Nano-X? But on 8086 computers Naxo-X looks slow for games.

Yes, a lot of the graphics could be mapped to Nano-X, but it will likely be too slow. The biggest reasons for this (to be covered in more detail later) are 1) the lower level routines are written in C, not ASM, and 2) Nano-X has an additional layer of overlapping window management and clipping support.

I have a number of graphics translation libraries for various embedded systems like Arduino, but what is really needed here is an (older) 8086 graphics library with direct, fast EGA support.

I never had occasion to work with nx before meeting ELKS (my past experience with NuttX from which nx originated never went beyond the nsh command line sessions), so I can't really say how good or bad this library is. I just have impression that I already saw things more mature than nx, like Photon on QNX or DirectFB on Linux. Even things like GUILib for multiplatform SDL library seemed more mature.

Actually, Nano-X originated from NanoGUI, which itself was based on some very early code by David I. Bell, the same guy that interestingly enough wrote sash and a lot of the basic command line utilities used in ELKS. I took that code back in the 1990's and started the Microwindows Project, whose original goal was to implement the Win32 GDI as well as an Xlib-like API onto Linux framebuffer systems (those with video cards implementing a flat frame buffer rather than the complicated and slow original EGA/VGA card hardware). Back in 1999, version 0.86 was the last version small enough to run on 8086 systems, and I ported it to ELKS. So we're running a code snapshot from 21 years ago. The landmine game is particularly old-fashioned looking; it was written by David Bell himself and a contributed port to Microwindows was made over 20 years ago. There are lots of other much better-looking Nano-X graphics, but most all are too big to run on ELKS,. The name was changed from Microwindows to Nano-X when Microsoft sent a cease and desist letter. Check out what Nano-X looks like today; unfortunately its all way too big for ELKS.

But I digress. Back to @pawosm-arm's points, SDL, DirectFB, etc - are all too large for ELKS. Since the ELKS applications (not the kernel) will be writing directly to the EGA, what we should seriously consider would be an older, fast EGA library. Those libraries would likely use a different assembler than ia16-gcc-as (which is gcc compatible and AT&T syntax). Another option would be to use the EGA draw routines from Nano-X written in ASM (elkcmd/nano-X/drivers/asmplan4.s), but they would need to be ported from the BCC/AS86 assembler, and the speed would likely improve considerably. Nano-X is written as three layers (driver, engine and API), and the driver and engine could be used without the window-management API overhead, which would help. Its all a bit complicated, but doable.

By the way is it possible to change the priority of a process in ELKS? There is a nice sys call, but no nice command? Maybe this will make a game run a bit faster.

There's no way to change the priority of a process in ELKS (yet); but when a single program is running, which is usually the case, there's no need for it - the system runs the single process as fast as can be, only taking timer interrupts, which increment a few counters, and then the interrupted process is immediately continued.

@toncho11
Copy link
Contributor Author

toncho11 commented Nov 18, 2020

There is another solution:

Alfonso Martone found a way to convert DOS Turbo-C programs to enable these to run with ELKS. For this he developed the exe2elks DOS utility program and a small libc without DOS system calls. You compile your C program with this small libc library instead of the standard Turbo-C libc. Then you use the exe2elks utility to convert the generated executable in the DOS EXE format to a 16bit OMAGIC aout file as required by ELKS.

So if we accept that the Turbo C graphics.h is not using DOS system calls (I actually do not know) then we could compile a game with Turbo C and:

  • either use implementations of all the I/O libraries that do not use DOS calls as Alfonso does
  • the game comes as an object file from Turbo C that does not contain the IO libraries and we continue with ia16 gcc compiler on Linux which links the implementations

So again:

  • custom script that compiles the game core and links the graphics.h to an object file using Turbo C
  • link the rest from ia16 gcc using @tkchia versions of conio.h and dos.h.

printf should come from ia16 gcc I suppose.

What do you think? Are the differences in compiling linking and function parameters handling so different ?
This solution can solve the problem of speed because I believe Turbo C routines are already optimized.

@pawosm-arm
Copy link
Contributor

Actually, Nano-X originated from NanoGUI, which itself was based on some very early code by David I.

Argh, this name reuse, so common in Open Source world. Indeed nx graphics in NuttX and nx graphics in ELKS are completely different things of completely different origins. Both had the same purpose in common which is being lightweight, and that confused me. So porting nx from NuttX may be one more path to follow or avoid.

Anyway, ability to change resolution (and bytes per pixel) would be a great addition to current graphics layer in ELKS, but only if it doesn't overcomplicate the current codebase.

@pawosm-arm
Copy link
Contributor

Speaking of Turbo C++, it brings me some of my late school days memories, you can have a glimpse here, https://www.youtube.com/watch?v=N8z5kQFhJ9A yet note I'll probably pull it down soon, there's too much cringe in this :)

Anyway, looking forward, if you're serious about DOS compatibility in ELKS, IPX would be a nice addition, we had a lot of fun playing those early multiplayer games back in the 90's.

@ghaerr
Copy link
Owner

ghaerr commented Nov 18, 2020

@toncho11,

Alfonso Martone found a way to convert DOS Turbo-C programs to enable these to run with ELKS. For this he developed the exe2elks DOS utility program and a small libc without DOS system calls. You compile your C program with this small libc library instead of the standard Turbo-C libc.

I have to say, somewhat amazing piece of work by Alfonso. He's definitely provided the basics, that should, possibly without modifications, work today (we upgraded the ELKS a.out format slightly earlier this year, but still support the original a.out format, calling it "v0").

The bigger issue with this approach is that the development is all done on DOS, right? So TurboC is run on DOS to compile and link any TC program, along with the TC graphics library, and Alfonso's DOS-to-ELKS conversion libc which allows the program to run on ELKS without modification. It's a slick way to solve this problem. Perhaps you should try running his sample programs and see if/how they run on ELKS today, for a start.

@ghaerr ghaerr added discussion and removed bug Defect in the product labels Nov 18, 2020
@toncho11
Copy link
Contributor Author

toncho11 commented Nov 18, 2020

I compiled a minimal program that draws a rectangle with Turbo C and then applied exe2elks.
For the map file generated by Turbo C and required by exe2elks there are 3 options "Segments", "Publics" and "Detailed". I think I wen with "Segments".

It says "invalid argument" on ELKS.

@ghaerr
Copy link
Owner

ghaerr commented Nov 18, 2020

I compiled a minimal program that draws a rectangle with Turbo C and then applied exe2elks.
It says "invalid argument" on ELKS.

This is very likely due to the exe2elks output a.out binary format not being compatible with ELKS now. We will need to make some changes to exe2elks.c. I won't be able to compile it, since I don't have access to DOS. Take a quick look at exe2elks.c, and familiarize yourself with it. Make sure you can compile it up from scratch to exe2elks.exe. Please post the non-working minimal program binary, and then I'll help determine what fields in the "elks" struct we need to change. I don't think it will be much.

@toncho11
Copy link
Contributor Author

Here it is:
DEMO3.zip

@toncho11
Copy link
Contributor Author

If this is the correct disassembly:
DEMO3.txt

then it means that there are 19 int $0x21 DOS calls ... more than I have hoped.

@toncho11
Copy link
Contributor Author

toncho11 commented Nov 18, 2020

OK I see now ... probably I need to use the .bat file provided by Alfonso to set the proper options of tcc and tlink ... to generate a better executable ... I was using the IDE with .map file generation enabled.

@ghaerr
Copy link
Owner

ghaerr commented Nov 18, 2020

probably I need to use the .bat file provided by Alfonso to set the proper options of tcc and tlink ... to generate a better executable

Yes, the idea is to compile with TC but link with Alfonso's special library that replaces all the TC libc calls to int 21h with ELKS system calls, and then rewrite the .EXE MZ format to ELKS a.out format.

@toncho11
Copy link
Contributor Author

toncho11 commented Nov 18, 2020

Ok it is going to take much more time.
Turbo C loads a graphical driver. So that is why there were many int 21 calls I suppose. It access the disk and it loads the driver - a EGAVGA.BGI file in my case as I am using VGA card. The good news is that I can convert the .bgi to .obj with bgiobj.exe and use it while linking .

@toncho11
Copy link
Contributor Author

toncho11 commented Nov 19, 2020

This is a direct example of Alfonso:

HELLO.zip

It says "invalid argument". We need to fix that first before going deeper into the graphics library.

How do you disassemble it?
objdump -s -x -D -b binary -m i8086 hello
It does not print all the lines I think ?

@ghaerr
Copy link
Owner

ghaerr commented Nov 19, 2020

@toncho11,

I'm not exactly sure what the problem is with ELKS running that (v0 format a.out header) executable, but I have a workaround that works:

chmem -h can be run on the executable, setting the same heap size as the program says it wanted originally; chmem will then set the header to type v1 and it will run. This should work on any executables produced by Alfonso's tools for the time being. I'll look into and fix either ELKS or your elks2exec.c so this won't be required after v0.4.0.

Screen Shot 2020-11-19 at 4 28 28 PM

How do you disassemble it?

It appears we don't have a way to disassemble linked binaries... the objdump86 program should be able to work, but it seems to want to work on .o files only. I'll look into that later also, unless you can find a decent 8086 disassembler on the net somewhere. I would like to add disassembly capability directly into an ELKS command.

@toncho11
Copy link
Contributor Author

It is far more complicated ... I can not even compile a normal exe with the integrated bgi driver.

@pawosm-arm Do you know how to do that? How to compile from command line with graphics.lib, egavga.obj and registerbgidriver(EGAVGA_driver) ? I can not make it to work.

@toncho11
Copy link
Contributor Author

Interesting ... I tried to contact Alfonso ... but there is no working email ... nor any other contact information ...

@pawosm-arm
Copy link
Contributor

pawosm-arm commented Nov 20, 2020

@pawosm-arm Do you know how to do that? How to compile from command line with graphics.lib, egavga.obj and registerbgidriver(EGAVGA_driver) ? I can not make it to work.

Can you specify more details? Which 'command line': DOS, Linux, ELKS? (well, ELKS command line doesn't seem to have a linker). What kind of binary do you want to have in effect?

@ghaerr
Copy link
Owner

ghaerr commented Nov 20, 2020

I can not even compile a normal exe with the integrated bgi driver.

Compile or link error? You're using TC on DOS so there should be no issues having TC compiling TC programs, including those with graphics.h. Alfonso's trickery is all at the link stage, linking with additional libraries, right? You'll probably need to study TC a bit and understand what options it has for graphics programs, should there be compilation issues with it.

@bocke
Copy link

bocke commented Dec 28, 2024

I'm pretty sure it doesn't. I chose it for porting because it's small and simple. :)

It does something like this (for menu handling and scrolling):

	do
	{
		move(sy+i,sx);
		printw(">%.*s<",maxLen, menuItems[i]);
		keyMask = plat_ReadKeys(0);
		if(keyMask & INPUT_MOTION)
		{
			move(sy+i,sx);
			printw(" %.*s ",maxLen, menuItems[i]);
			switch(keyMask & INPUT_MOTION)
			{
				case INPUT_UP:
					if(!--i)
						i = numMenuItems-1;
					break;
					
				case INPUT_DOWN:
					if(numMenuItems == ++i)
						i = 1;
					break;
			}
		}
		keyMask &= (INPUT_SELECT | INPUT_BACKUP);

		move(sy+height,sx);
		printw(" %.*s ",maxLen, pScroller);
		if((pEnd - pScroller) < maxLen-1)
		{
			move(sy+height,sx+(pEnd-pScroller)+1);
			printw(" %.*s ",maxLen-(pEnd - pScroller)-1, scroller);
		}
		
		if(plat_TimeExpired(SCROLL_SPEED))
		{
			++pScroller;
			if(!*pScroller)
				pScroller = scroller;
		}
	} while(keyMask != INPUT_SELECT && keyMask != INPUT_BACKUP);

And thanks for the advice. It gave some ideas where to look into.

@bocke
Copy link

bocke commented Dec 28, 2024

I cleaned up all attron(WA_REVERSE) and color_set functions, so this is a bit simplified version.

@ghaerr
Copy link
Owner

ghaerr commented Dec 28, 2024

It does something like this (for menu handling and scrolling):

Looks pretty straightforward. If it's scrolling strangely, I would suggest looking at 'if(plat_TimeExpired(SCROLL_SPEED))' as that seems to increment a column (or not). The auto-scroll functionally actually seems kind of cool as written :)

[EDIT: Oh I see - you were saying it IS scrolling correctly. Nice!]

@bocke
Copy link

bocke commented Dec 28, 2024

No. It doesn't, unfortunately. At least not in elksemu.

I'll test in virtual machine and I might try installing on an older laptop like Rafael.

@ghaerr
Copy link
Owner

ghaerr commented Dec 28, 2024

No. It doesn't, unfortunately. At least not in elksemu.

In that case, the code in plat_TimeExpired is likely the culprit. This function is either hanging, causing problems with the menu, or always returning 0. If you hack it to always return 1, then the bottom line should scroll (quickly).

At least not in elksemu.

I'm on macOS, and elksemu won't even build on macOS. So I can't duplicate any of that.

@bocke
Copy link

bocke commented Dec 28, 2024

I just found out elks will boot on DOSBox-X. I did a test of 1440k floppy and it worked. Later I saw it's used elsewhere in the toolchain for testing.

I'm very familiar with DOSBox-X, so I might try that first. Now I'm building a disk image.

I might put executable on the fat formatted fd image and run from that.

@bocke
Copy link

bocke commented Dec 28, 2024

Floppy images work well in DOSBox. Hard drive images though have some problems. But in QEMU everything worked out of the box.

@ghaerr
Copy link
Owner

ghaerr commented Dec 28, 2024

I just found out elks will boot on DOSBox-X.

Yes, it's been used for quite some time to run the PC-98 images. Here's the configuration file I use. I'll check this in to the repo, it is used with 'dosbox.sh' which is already checked in.
dosbox-x.conf.zip

Hard drive images though have some problems.

If you can get that working, please update dosbox.sh and/or dosbox-x.conf, and I'll add that to the repo.

@bocke
Copy link

bocke commented Dec 28, 2024

If you can get that working, please update dosbox.sh and/or dosbox-x.conf, and I'll add that to the repo.

Deal. :) I gave up for now. But I will try again at some time.

@toncho11
Copy link
Contributor Author

@tyama501 is also working on a chess game in #2116

@bocke
Copy link

bocke commented Dec 28, 2024

Great! With the one Rafael ported that's three.

@tyama501
Copy link
Contributor

It is interesting to see battles with 2 chess game computers :)
(Maybe cc65-chess is stronger)

@bocke
Copy link

bocke commented Dec 30, 2024

I haven't had luck yet. I worked on cc65-chess yesterday but just got entangled with hacking curses code. For some reason anything I tried didn't work. :D

So today (sunday) I took a break and will try hacking on it in the next few days again.

@bocke
Copy link

bocke commented Jan 4, 2025

I actually made some progress in the new year. I implemented A_REVERSE and color_set with a little help in debugging from ChatGPT. Haven't got around to fix key bindings and scrolling text.

I also took time to test the game in Qemu and elksemu and the result looks and behaves the same. So, I confirm elksemu works right in Linux.

This is the last screenshot:
cc65-chess

Not yet ready for pull request, but we are getting there. :)

@toncho11
Copy link
Contributor Author

toncho11 commented Jan 4, 2025

I actually made some progress in the new year. I implemented A_REVERSE and color_set with a little help in debugging from ChatGPT. Haven't got around to fix key bindings and scrolling text.

I also took time to test the game in Qemu and elksemu and the result looks and behaves the same. So, I confirm elksemu works right in Linux.

This is the last screenshot: cc65-chess

Not yet ready for pull request, but we are getting there. :)

Nice! Does it fit in 640KB memory?

@ghaerr
Copy link
Owner

ghaerr commented Jan 4, 2025

That looks and sounds great @bocke!

When you're ready to contribute, lets have you stick the game in its own directory under elkscmd/, and also use copies of the enhanced curses*.c you've updated. I can then look at them to determine how compatible they'll be with the existing set of elkscmd/tui programs that also use them. It sounds like after your PR will be a good time to convert the curses code into a library and stick it in libc, using your version as a starting point.

The only "big" problem coming up is going to be how to determine what the names of each of our different chess programs should be, as they need different names to all live together on a distribution disk! :)

@bocke
Copy link

bocke commented Jan 4, 2025

The binary is 22,8 kb at the moment. That includes curses1.c curses2.c curses3.c and unikey.c from elkscmd/tui.

Anyway, There might be some problem with getch from curses2.c. It seems autoscroll doesn't work because the input is blocking. Also, getch() seems to recognize the different arrow keys, but plat_ReadKeys for some reason doesn't. I have to check unikey stuff too.

@bocke
Copy link

bocke commented Jan 4, 2025

The only "big" problem coming up is going to be how to determine what the names of each of our different chess programs should be, as they need different names to all live together on a distribution disk! :)

I have a very stupid, but also very simple solution to that. 😁 Chess1, chess2, chess3. :)

@bocke
Copy link

bocke commented Jan 4, 2025

This is getch() we have:

int getch()
{
    int e, n;
    int mx, my, modkeys, status;
    char buf[32];

    fflush(stdout);
    if ((n = readansi(0, buf, sizeof(buf))) < 0)
        return -1;
    if ((e = ansi_to_unikey(buf, n)) != -1) {   // FIXME UTF-8 unicode != -1
        return e;
    }
    if ((n = ansi_to_unimouse(buf, n, &mx, &my, &modkeys, &status)) != -1) {
        mouse_button = n;
        switch (n) {
        case kMouseLeftDoubleClick:
            waitformouse();
            return n;
        case kMouseWheelDown:
        case kMouseWheelUp:
            return n;
        }
    }
    return -1;
}

What exactly makes the input blocking, I don't know. :) But I'll try to debug. I took a look at unikey.{c,h} and it doesn't look fun for debugging.

@bocke
Copy link

bocke commented Jan 4, 2025

Heh. Seems ChatGPT caught on possible reason for blocking.

From your code, we can see you already have:

ansi_to_unikey() which decodes arrow keys if given the full ESC [ sequence.
readansi() which reads bytes from the file descriptor until it recognizes an ANSI sequence.

However, under ELKS, the poll() call in readansi() is ignored because of:

#if !ELKS
... poll code ...
#endif

Thus, your code under ELKS effectively blocks on read(). It can also loop if read() returns -1 with EAGAIN, but there is no real timeout-based fallback. That typically means you block until input is available.

@bocke
Copy link

bocke commented Jan 4, 2025

It also recommends a potential solution:

#ifdef ELKS
        // Under ELKS, no poll => do a tiny sleep, then return -1 (no data)
        usleep(5000);  // 5 ms, for example
        return -1;     // Means “no key available”
#else

I'll check if this solves the blocking problem.

The problem is basically: program blocks until a key is pressed.

But the program is designed to do autoscrolling in the menu. Also computer player is supposed to play automatically. Same with the game where computer (AI) plays against itself. If the IO is blocked, you have to press a key for game to continue on every move.

@ghaerr
Copy link
Owner

ghaerr commented Jan 4, 2025

What exactly makes the input blocking, I don't know.

All the TUI programs require an initialization to work with the complicated unikey stuff. This is called tty_init and it's passed some flags, of which NoWait can be added so that it doesn't block. You'll note that curses.c initscr doesn't use that flag by default, but that nodelay will. Thus the behavior is suppose to be controlled by the curses API.

However, under ELKS, the poll() call in readansi() is ignored because of:

That's different. It's commented out because the system call poll is not implemented on ELKS.

It also recommends a potential solution:

I wouldn't recommend calling a delay routine when the problem itself is you don't want blocking. Add the curses nodelay call to your program which should reset the blocking behavior. Otherwise, change the tty_init to OR in the NoWait flag.

But the program is designed to do autoscrolling in the menu.

Got it. These differing cases are already handled by the library. What I don't get is why the program didn't come with a call to nodelay in it in the first place...

@ghaerr
Copy link
Owner

ghaerr commented Jan 4, 2025

It also recommends a potential solution:

The robot solution recommendation is actually the exact opposite of what you need: it is recommending adding a delay, while your whole problem is to remove all blocking or delays, and returning -1 immediately if no character is ready. LOL!!!

@ghaerr
Copy link
Owner

ghaerr commented Jan 4, 2025

Seems ChatGPT caught on possible reason for blocking.

No AI Coding here!!! Better to learn yourself and more fun anyways, especially when the wrong answers are being suggested.

shopping

@bocke
Copy link

bocke commented Jan 4, 2025

Well, I use AI for code analysis. It's not perfect, but it's much faster than understanding thousands of lines of code someone else wrote on your own. Especially if you have to dive deep into implementation details of multiple inter-connected projects.

I am not really a system programmer, so when the things get too low level, I have too use tools I have at my disposal. :) For example, when my brain is out of the solutions, I will pick someone else's brain. In this case AI. If I didn't consult AI, I would probably have to bother you and others in this topic. :) I mean, I don't mind that solution either, but I doubt anyone here has too much time on their disposal.

Anyway, no real damage here as I would see it's not working and try something else.

@bocke
Copy link

bocke commented Jan 4, 2025

And I think the author didn't use nodelay() because he used timeout(0).

@ghaerr
Copy link
Owner

ghaerr commented Jan 4, 2025

Anyway, no real damage here as I would see it's not working and try something else.

No problem - I was just kidding. I personally think that the AI hype is overblown, as was seen here, but
have to admit that I don't use it much. I'm glad it helps you. I would like to try prompting some image
creations though, that sounds fun. But you won't find me doing any AI-based programming, as I enjoy
the process of learning, as well as sometimes reading through lots and lots of code. I've been doing that
lately for the 8086 toolchain, and although tedious, I have learned much about how each tools works, which
for me is very gratifying.

@ghaerr
Copy link
Owner

ghaerr commented Jan 4, 2025

the author didn't use nodelay() because he used timeout(0).

Nice find. If nodelay works, then go ahead and add the curses timeout function, I wasn't aware of it,
as I've only built curses based on the actual needs of programs using it, to keep the bloat down.

@bocke
Copy link

bocke commented Jan 4, 2025

the author didn't use nodelay() because he used timeout(0).

Nice find. If nodelay works, then go ahead and add the curses timeout function, I wasn't aware of it, as I've only built curses based on the actual needs of programs using it, to keep the bloat down.

Nodelay works. :)

Such a simple solution. I spent too much time debugging this... 🙄

@ghaerr
Copy link
Owner

ghaerr commented Jan 4, 2025

Also, getch() seems to recognize the different arrow keys, but plat_ReadKeys for some reason doesn't.

Yes, getch uses the underlying magic of the unikey library code to decode ANSI input streams containing ESC chars, etc. So plat_ReadKeys needs to be recoded or reworked to do the same - possibly by just calling getch itself, unless it's trying to do its own decoding. I haven't looked at the source so I'm just guessing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

10 participants