Skip to content

OpenGL-based 2D Graphics implementation - #464

Draft
Jafaral wants to merge 11 commits into
uniconproject:masterfrom
Jafaral:opengl2d
Draft

Jafaral wants to merge 11 commits into
uniconproject:masterfrom
Jafaral:opengl2d

Conversation

@Jafaral

@Jafaral Jafaral commented May 24, 2024

Copy link
Copy Markdown
Member

No description provided.

@Jafaral

Jafaral commented Apr 10, 2026

Copy link
Copy Markdown
Member Author

@greptile review

@greptile-apps

greptile-apps Bot commented Apr 10, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 0/5

[Medium impact] The changes affect Unicon's graphics runtime and its optional OpenGL path.

This PR needs fixes before merging because common color calls can crash, native X11 support regresses, and Windows 3D initialization is missing.

Findings

  1. P1 Color calls crash without windows ▶
  2. P1 Native windows now require GLX ▶
  3. P1 Opaque colors become transparent ▶
  4. P1 Windows 3D defaults are missing ▶
  5. P1 Hidden windows keep old resources ▶
  6. P1 Dead code - default pattern never applied ▶
Fix with agent prompt
### Issue 1
src/runtime/rwindow.r:857-858
`parsecolor()` now reads `w->context->alpha` even when no window was supplied. Both `ColorValue("red")` and `PaletteKey("c1", "red")` allow `w == NULL`, so these calls now crash in ordinary OpenGL builds. The new integer branch in `PaletteKey()` also reads `w->window` before checking for null.

Check `w` before reading either field, and use full opacity when no drawing context exists.

### Issue 2
src/runtime/rxrsc.ri:627-630
`alc_display()` now requires GLX even for displays used only by native 2D windows. `GraphicsGL` is enabled whenever OpenGL was found at build time, not just with `--enable-opengl2d`.

If an X server does not provide GLX, plain `open(..., "g")` now fails even with the experimental renderer disabled. Move these checks to the path that requests an OpenGL window.

### Issue 3
src/runtime/rwindow.r:1076-1081
The numeric-opacity fallback also catches the named value `opaque`. For `"opaque red"`, `p` matches the table entry with value 100, but `tmpf` is zero because it came from `atof("opaque")`. The code then assigns zero to `alpha`, so shapes using that color can disappear in OpenGL windows.

Keep named opacity values separate from the numeric fallback.

### Issue 4
src/runtime/rmswin.ri:308-310
Removing `wopengl()` also removed the Windows call to `init_3dcontext()`. The X11 allocator now calls it, but Windows `alc_context()` still only sets native drawing fields. Setting `wc->rendermode` here leaves `dim`, `slices`, `rings`, and the selection fields without their required defaults.

A newly opened Windows 3D window can therefore crash in `DrawLine()`, which divides by `dim`. Initialize the Windows OpenGL context before applying attributes.

### Issue 5
src/runtime/rxwin.ri:3002-3009
The OpenGL branch allows changing `display` after a window has been created and hidden, but it only replaces `ws->display`. The existing `win`, `ctx`, and `pbuf` still belong to the old display. The next draw or close uses those old resources with the new connection, breaking drawing or causing X errors.

Reject display changes once these resources exist, or recreate all of them on the new display.

### Issue 6
src/runtime/ropengl2d.ri:3182-3186
`return Failed` on line 3178 exits the function before the intended fallback `strdup("black")` executes. When `wcr->patternname == NULL` in this branch, the function bails out with `Failed` rather than initialising the default pattern, and the two lines that follow are unreachable. The fix is to swap the `return Failed` to after the strdup - or remove it entirely if the intent is simply to set the default.

```suggestion
      if (wcr->patternname == NULL) {
         wcr->patternname = strdup("black");
         if (!wcr->patternname) return RunError;
         }
      s = wcr->patternname;
```

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds experimental OpenGL-based 2D drawing alongside the existing 3D renderer.

  • Unicon windows can render 2D graphics through OpenGL.

Review used source inspection; no build or runtime reproduction was performed.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Program opens a window] --> B{Requested drawing mode}
  B -->|Native 2D| C[Native drawing context]
  B -->|3D| D[OpenGL window]
  B -->|Experimental 2D enabled and selected| D
  D --> E[Window owns OpenGL resources]
  E --> F[Record drawing calls]
  F --> G[Replay scene on refresh or resize]
Loading

Reviews (2) · Last reviewed commit: "build: make OpenGL 2D an opt-in feature ..." · Reviewed by Greptile

Comment thread src/h/opengl.h Resolved
Comment thread src/runtime/ropengl2d.ri
Comment on lines +3177 to +3181
if (wcr->patternname == NULL) {
return Failed;
wcr->patternname = strdup("black");
if (!wcr->patternname) return RunError;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Dead code — default pattern never applied

return Failed on line 3178 exits the function before the intended fallback strdup("black") executes. When wcr->patternname == NULL in this branch, the function bails out with Failed rather than initialising the default pattern, and the two lines that follow are unreachable. The fix is to swap the return Failed to after the strdup — or remove it entirely if the intent is simply to set the default.

Suggested change
if (wcr->patternname == NULL) {
return Failed;
wcr->patternname = strdup("black");
if (!wcr->patternname) return RunError;
}
if (wcr->patternname == NULL) {
wcr->patternname = strdup("black");
if (!wcr->patternname) return RunError;
}
s = wcr->patternname;
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/runtime/ropengl2d.ri
Line: 3177-3181

Comment:
**Dead code — default pattern never applied**

`return Failed` on line 3178 exits the function before the intended fallback `strdup("black")` executes. When `wcr->patternname == NULL` in this branch, the function bails out with `Failed` rather than initialising the default pattern, and the two lines that follow are unreachable. The fix is to swap the `return Failed` to after the strdup — or remove it entirely if the intent is simply to set the default.

```suggestion
      if (wcr->patternname == NULL) {
         wcr->patternname = strdup("black");
         if (!wcr->patternname) return RunError;
         }
      s = wcr->patternname;
```

How can I resolve this? If you propose a fix, please make it concise.

Comment thread src/runtime/ropengl.ri Resolved
Comment thread src/runtime/ropengl2d.ri Resolved
Commit c6353a1 ("Allow OpenGL graphics without FreeType") moved
default font loading out of gl_alc_display() into the new
gl_alc_display_font(), but only rmswin.ri calls it.  On X11,
wd->glfonts stays NULL, init_2dcontext() logs "fonts not allocated",
alc_context() falls back to the X11 font, and drawstringhelper() then
dereferences wf->face on that X font, which crashes any text output
to a gl window (writes() to a 3D window, a 2D subwindow of one, or a
UNICONGL2D window).

Mirror the Windows path: load the font right after the display, and
treat a missing font as fatal only for non-3D GL windows.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
tests/graphics/gl/run.sh builds and runs small 3D, subwindow, text and
2D programs, saving each window with WriteImage(). It starts a private
Xvfb when DISPLAY is unset. 'run.sh -c A B' pixel-compares two runs,
e.g. a master build against a branch build, using ImageMagick.

t10_2d runs twice: natively and with UNICONGL2D=1.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
ropengl2d.ri defined 36 gl_* "window management" functions that did
nothing OpenGL-specific: each one only called the native function of
the same name with the same arguments (gl_wclose -> wclose,
gl_setwindowlabel -> setwindowlabel, ...), and gl_allowresize was a
copy of allowresize, identical on X11 and Windows.  Every use was
wrapped in an '#ifdef GraphicsGL / if (ws->is_gl) gl_X() else X()'
block.  OpenGL does not own windows; the native window system does.

Remove those functions and their prototypes, and call the native
functions directly.  Also remove wopengl(), which had no callers.

gl_setcursor and gl_rebind are kept for now: their Windows
counterparts do more than the GL copies.

No behavior change: tests/graphics/gl output is pixel-identical
before and after.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
OpenGL renders into windows; it does not create or manage them.  The
OpenGL 2D code still wrapped the native allocators from the outside:
fsys.r called gl_wopen() -> wopen(is_gl=1), which called
gl_alc_winstate() -> alc_winstate() and gl_alc_display() ->
alc_display(), and child_window_generic() did the same.

Follow the pattern alc_context() already uses (the native allocator
calls init_2dcontext()): the native code allocates, then calls an
OpenGL init hook for GL windows.

 - gl_init_winstate(ws) replaces gl_alc_winstate().
 - gl_init_display(wd, need_font) replaces gl_alc_display() and
   gl_alc_display_font().  It no longer free()s a display that is
   shared with other windows when the texture array allocation fails.
 - gl_free_display_resources(wd) replaces gl_free_display(), which
   had no callers.  The X11 free_display() now calls it when the last
   reference goes away.  It frees the FreeType faces, glyph bitmaps and
   font structs; GL textures go away with the contexts.
 - gl_wopen() is gone; fsys.r calls wopen(..., is_gl) directly.

Clone() changes:
 - A plain "g" child of a 3D window is a native window again, as on
   master.  3D and texture children, and 2D children of OpenGL 2D
   windows, still use OpenGL (GL_CHILD() in graphics.h).
 - Native child windows are mapped with my_wmap() again.  Without
   that, Clone(w, "g") of a plain 2D window crashed with a memory
   violation (tests/graphics/gl/t11_sub2d2d).
 - Fs_WinGL2D now comes from the new window, not the parent.
 - A GL child of a non-GL parent initializes the display for GL.

t12_reopen opens and closes OpenGL windows repeatedly.

tests/graphics/gl matches master except two known differences:
OpenGL 2D output itself, and WriteImage() of an OpenGL window with
child windows, which no longer includes the children (glReadPixels
reads only the window's own framebuffer; on screen they are the same).

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
If the default OpenGL (FreeType) font cannot be loaded, a 3D window is
still allowed to open and its context falls back to the native font.
drawstringhelper() then dereferenced wf->face of that native font
(NULL, since fonts are calloc()ed) and crashed.  Check for it and
report the new run-time error 156, "no OpenGL font available to draw
text".

Also make GL2D_DEBUG opt-in (-DGL2D_DEBUG) instead of always on, so
OpenGL windows no longer print glprintf() tracing such as
"fonts not allocated" to stderr.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
find_fontfile() located dat/fonts as findonpath("iconx")/../dat/fonts.
That fails whenever iconx is not on PATH (it is usually run through
the path patched into the icode header), and nothing installed
dat/fonts, so OpenGL 2D windows could not open and OpenGL text could
not be drawn outside a build tree that happened to be on PATH.

On UNIX, use unirootfile(UNICONX_EXE, "/../../dat/fonts"), the same
lookup used for ipl/ and uni/: the patched library root in an installed
Unicon, the build tree otherwise.  imain() has already located iconx,
so relfile() does not search PATH.  Other platforms keep the old lookup,
since relfile() exits if it cannot locate the program.  Declare
unirootfile() in mproto.h.

Install dat/fonts to $(ULROT)/dat/fonts, and ship it in the
unicon-runtime deb and the runtime rpm.  calibri*.ttf are not
installed: they are not referenced by the code and are not
redistributable.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
OpenGL 2D graphics is experimental, so it is now off by default and
enabled with --enable-opengl2d, which defines GraphicsGL2D and requires
OpenGL (3D graphics) and FreeType.  GraphicsGL keeps meaning 'OpenGL is
available': it is the OpenGL plumbing that 3D graphics uses, much of
which the OpenGL 2D work moved into shared code.

Without GraphicsGL2D, nothing can reach the OpenGL 2D renderer:
 - UNICONGL2D is ignored and open(..., "g") always makes a native window.
 - WAttrib(w, "rendermode=2d") fails; "3d" is still accepted.
 - Texture children and 2D children are native windows, as on master
   (GL_CHILD() is true only for 3D children).
 - &features does not list "OpenGL 2D graphics" (_GL2D_GRAPHICS,
   previously "OpenGL graphics" / _GL_GRAPHICS).

configure prints +OpenGL2D/-OpenGL2D in the Graphics3D summary line.
configure is updated with only the delta for this change; regenerating
it from scratch also picks up unrelated drift in the zlib/X11 checks.

Add an 'Ubuntu 24.04 OpenGL 2D' entry to the CI Linux matrix so the
opt-in code keeps building with -Werror, and update UTR22.

Both configurations: tests/graphics/gl passes, and the default build
matches master except WriteImage() of a 3D window with 3D children.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Comment thread src/runtime/rwindow.r Outdated
Comment on lines +857 to +858
#ifdef GraphicsGL
*a = (long) (w->context->alpha*65535.0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Color calls crash without windows

parsecolor() now reads w->context->alpha even when no window was supplied. Both ColorValue("red") and PaletteKey("c1", "red") allow w == NULL, so these calls now crash in ordinary OpenGL builds. The new integer branch in PaletteKey() also reads w->window before checking for null.

Check w before reading either field, and use full opacity when no drawing context exists.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/runtime/rwindow.r
Line: 857-858

Comment:
**Color calls crash without windows**

`parsecolor()` now reads `w->context->alpha` even when no window was supplied. Both `ColorValue("red")` and `PaletteKey("c1", "red")` allow `w == NULL`, so these calls now crash in ordinary OpenGL builds. The new integer branch in `PaletteKey()` also reads `w->window` before checking for null.

Check `w` before reading either field, and use full opacity when no drawing context exists.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment thread src/runtime/rxrsc.ri Outdated
Comment on lines +627 to +630
/* Check for GLX */
if (!glXQueryExtension(wd->display, &query, &query)) {
fprintf(stderr, "no visual extension\n");
return NULL;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Native windows now require GLX

alc_display() now requires GLX even for displays used only by native 2D windows. GraphicsGL is enabled whenever OpenGL was found at build time, not just with --enable-opengl2d.

If an X server does not provide GLX, plain open(..., "g") now fails even with the experimental renderer disabled. Move these checks to the path that requests an OpenGL window.

Knowledge Base Used: Runtime graphics and multimedia services

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/runtime/rxrsc.ri
Line: 627-630

Comment:
**Native windows now require GLX**

`alc_display()` now requires GLX even for displays used only by native 2D windows. `GraphicsGL` is enabled whenever OpenGL was found at build time, not just with `--enable-opengl2d`.

If an X server does not provide GLX, plain `open(..., "g")` now fails even with the experimental renderer disabled. Move these checks to the path that requests an OpenGL window.

**Knowledge Base Used:** [Runtime graphics and multimedia services](https://app.greptile.com/-/switch-tenant?tenant=unicon-project&next=%2Fcustom-context%2Fknowledge-base%2Funiconproject%2Funicon%2F-%2Fdocs%2Fruntime-graphics-multimedia.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment thread src/runtime/rwindow.r Outdated
Comment on lines +1076 to +1081
if (p && (((colrmod *)p) -> val) != 100)
alpha = ((colrmod *)p) -> val / 100.0;
/* save numeric diaphaneity value */
else {
if (tmpf >= 1.0) tmpf = 1.0;
alpha = tmpf;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Opaque colors become transparent

The numeric-opacity fallback also catches the named value opaque. For "opaque red", p matches the table entry with value 100, but tmpf is zero because it came from atof("opaque"). The code then assigns zero to alpha, so shapes using that color can disappear in OpenGL windows.

Keep named opacity values separate from the numeric fallback.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/runtime/rwindow.r
Line: 1076-1081

Comment:
**Opaque colors become transparent**

The numeric-opacity fallback also catches the named value `opaque`. For `"opaque red"`, `p` matches the table entry with value 100, but `tmpf` is zero because it came from `atof("opaque")`. The code then assigns zero to `alpha`, so shapes using that color can disappear in OpenGL windows.

Keep named opacity values separate from the numeric fallback.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment thread src/runtime/rmswin.ri
Comment on lines +308 to +310
#ifdef GraphicsGL
if (is_gl) {
wc->rendermode = is_3d;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Windows 3D defaults are missing

Removing wopengl() also removed the Windows call to init_3dcontext(). The X11 allocator now calls it, but Windows alc_context() still only sets native drawing fields. Setting wc->rendermode here leaves dim, slices, rings, and the selection fields without their required defaults.

A newly opened Windows 3D window can therefore crash in DrawLine(), which divides by dim. Initialize the Windows OpenGL context before applying attributes.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/runtime/rmswin.ri
Line: 308-310

Comment:
**Windows 3D defaults are missing**

Removing `wopengl()` also removed the Windows call to `init_3dcontext()`. The X11 allocator now calls it, but Windows `alc_context()` still only sets native drawing fields. Setting `wc->rendermode` here leaves `dim`, `slices`, `rings`, and the selection fields without their required defaults.

A newly opened Windows 3D window can therefore crash in `DrawLine()`, which divides by `dim`. Initialize the Windows OpenGL context before applying attributes.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment thread src/runtime/rxwin.ri Outdated
Comment on lines +3002 to +3009
if (ws->iconic != HiddenState) return Failed;

Protect(d = alc_display(s), return 0);
if (gl_init_display(d, !ws->is_3D) != Succeeded) {
free_display(d);
return 0;
}
ws->display = d;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Hidden windows keep old resources

The OpenGL branch allows changing display after a window has been created and hidden, but it only replaces ws->display. The existing win, ctx, and pbuf still belong to the old display. The next draw or close uses those old resources with the new connection, breaking drawing or causing X errors.

Reject display changes once these resources exist, or recreate all of them on the new display.

Knowledge Base Used: Runtime graphics and multimedia services

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/runtime/rxwin.ri
Line: 3002-3009

Comment:
**Hidden windows keep old resources**

The OpenGL branch allows changing `display` after a window has been created and hidden, but it only replaces `ws->display`. The existing `win`, `ctx`, and `pbuf` still belong to the old display. The next draw or close uses those old resources with the new connection, breaking drawing or causing X errors.

Reject display changes once these resources exist, or recreate all of them on the new display.

**Knowledge Base Used:** [Runtime graphics and multimedia services](https://app.greptile.com/-/switch-tenant?tenant=unicon-project&next=%2Fcustom-context%2Fknowledge-base%2Funiconproject%2Funicon%2F-%2Fdocs%2Fruntime-graphics-multimedia.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

ColorValue() and PaletteKey() are legal with no window, and a native
window never initialized alpha, so a GraphicsGL build crashed or stored
transparent colors. "opaque red" took the numeric path because
atof("opaque") is 0.

GLX was required for every X display, so a native window failed when
the server had no GLX. Setup now runs when an OpenGL window is opened.
A hidden OpenGL window can no longer point at a new display while its
drawable and context still belong to the old one.

Windows OpenGL windows get the 2D and 3D defaults, a WGL context for
2D as well as 3D, and the initial-attribute flag is cleared so later
changes are applied. The last close releases the display, including GL
fonts and textures. A failed alc_display() closes the X connection it
opened.

Cloned contexts own their selection-name lists. A failed render update
no longer leaves the re-entry flag set. The sky and snow texture names
are separate words.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant