Hacker News new | ask | show | jobs
by codedokode 13 days ago
I think immediate-mode UI is awful (does lot of useless work, redraws whole window on every mouse move). Also I think GPU support is not that important:

- first, GPU requires shaders compilation which is slow so you need CPU renderer anyway

- second, not all GPUs are supported, not all have drivers, some are buggy and many machines, like VM, do not have a GPU

- third, it probably uses lot of memory

You don't need a GPU to add one letter to a text field.

I did some tests in a GPU-less VM, using one x86-64 core. The test simply rendered black and white 4K frames. Rendering to memory gave numbers like 360 fps (and ~8GiB/s of RAM writes). Rendering to X server via SHM produced something about 80 fps, the X server used 50% of the core and the program used other 50%. But many users have much smaller screens, and you typically do not need to redraw whole window every frame.

So you can render everything on a CPU and, if the user has a GPU, use it to accelerate drawing rounded rectangles which make probably 90% of GUI.

3 comments

Pegging the CPU while scrolling - a common action that takes a full rerender - is not good enough in this day and age. Your best case scenario still doesn't achieve the minimum for a 4k120hz display. Take into account text with subpixel-antialiasing, and that resolutions scale to ok now and you'll quickly find CPU rendering unusably slow.

Shader compilation basically doesn't matter. The number of shaders needed for a GUI toolkit is tiny, and none are particularly complex. In my experience it doesn't appreciably add to the startup time.

I do agree there should still be CPU rendering for when the GPU doesn't work. It's a particularly useful feature for old or virtualised hardware.

Scrolling should not take a full render - you ideally only need to render a small stripe that becomes visible. For example, if you scroll at 720px/sec, at 120 fps you need to render only 6 px of height per frame. Must not be hard.

For example, if you are scrolling a PDF you could theoretically "scroll" (change start y offset) of the window buffer, render a newly visible stripe (those 6px) and re-render the toolbar 6px lower which otherwise would scroll with the window.

It seems nobody can do this nowadays, so another option is to use two layers - a document and a toolbar and offload the compositing to window compositor which might as well use GPU for that. So you have one buffer with a toolbar (never changes), and another buffer with a document, and when scrolling, you only draw the changed part and instruct the compositor to draw the document with an offset.

Surprisingly, it's often faster to do a full render than to copy pixels around in the framebuffer, for two reasons.

1. With discrete GPUs, which have their own VRAM (unlike integrated GPUs), reading the framebuffer is often much slower than reading main memory.

2. If you're copying pixels around in the framebuffer, the best you can do is memcpy speed, which spends half of the memory bus bandwidth on reading memory. But if you're computing fresh pixels to put in the framebuffer instead, you can go about twice that fast. Sometimes more than twice that fast. As a simple example, https://canonical.org/~kragen/sw/dev3/bgraify.c unpacks 1-bit-deep bitmaps with a palette of two 32-bit colors on one core at 26 gigabytes per second (on this Ryzen 5 3500U), while memcpy() on that same core can only reach about 10 gigabytes per second. (memcpy() on two cores reaches more like 18 gigabytes per second, so the naïve extrapolation is that you ought to be able to hit 36 gigabytes per second for something like a solid-color fill.)

I do not see where I suggested to copy the pixels with CPU. With compositors like Wayland, you have a buffer in memory that stores content of a window. Obviously writing a 6-pixel stripe into that buffer (and updating starting Y offset) is faster than over-writing the whole buffer. Now, if that buffer is directly accessibly by GPU, you do not need to copy nothing. And I assume that even poor discrete GPUs can copy that 6 rows with pixels from system RAM to their memory for compositing.

Also your URL shows 404 for me.

To scroll the content you do not need to copy anything. You can just tell the compositor: "first render rows 6-1000 from this buffer and after that rows 0-5". That would look like the content has scrolled 6px up without a single copied byte. This trick was used by game consoles on 80s.

I'm sorry about the URL; I've fixed it now. Let me know if it's still broken.

Yes, you can scroll by telling the GPU to use a different starting address for its framebuffer, but only if you're scrolling the whole screen. If you want to scroll the contents of a browser window but not the browser chrome, though, or one window but not another, you start needing to tell the GPU to composite things from a few different textures, or needing to copy things around in system RAM. If you push this work off on a software compositor like Wayland, you aren't saving any work; you're just changing which process does the work.

> you start needing to tell the GPU to composite things from a few different textures,

Yes, correct, you need to have two buffers - one for the document, another for the toolbar. In this case you need to do compositing. The good thing is that compositing here is just memcpy, and it can be done on CPU and almost on any GPU starting from 90s, no need for Vulkan support or NVIDIA proprietary driver. And compositing (memcpy) is faster than rendering complicated document from scratch. So instead of sending one large buffer to Wayland, you send two smaller buffers ("send" doesn't imply copying here as Wayland uses shared memory).

So in a perfect world, the application updates a small part of a buffer with a document in a shared memory, changes Y offset, and CPU or GPU rebulds the window that was scrolled by combining the document and toolbar buffers. Oh, even better, by copying only the document part into a framebuffer because toolbar did not change.

So for example, if you are scrolling a text document, with my approach you need to render only one line of text (that became visible) and you reuse previously drawn lines. But with "immediate mode" approach, all visible lines must be re-rendered every frame.

URL works now.

For anyone who is reading this later, I've concluded that I was basically wrong here: even when you can render pixels faster than you can copy them around the framebuffer, not rendering them is still faster and lower power, as long as there's a framebuffer. See https://news.ycombinator.com/item?id=50640236 and the demo program I elicited from Claude Opus 5.5 to test this: https://canonical.org/~kragen/sw/vriffle/
This saves you some work of drawing glyphs, but you now need to blit that whole buffer. So you've gone from a single color background fill and rendering a full page of text, to a offset framebuffer copy and then a small partial render. In terms of memory bandwidth I don't think you're coming out on top here.
Even without the GPU, you don't have to peg the CPU when scrolling a 4K 120Hz display. 3840 pixels/row × 2160 rows/frame × 120 frames/second × 4 bytes/pixel is 4 gigabytes per second. The laptop I'm typing this on can memcpy() to main memory at 10 gigabytes per second on one core and 17–19 gigabytes per second on two cores. So we're talking about more like a 25% CPU load if we can avoid extra copies, maybe better than that if most of the work is something like colormapping 8-bit grayscale font-glyph pixels.

(If you're mostly memcpying from a font that fits in cache, you should get a higher fill rate than this.)

Using a GPU is of course much better, but not necessary to reach the level of performance you're talking about.

Real applications don't use 8 bit grayscale font glyphs; there's colour glyphs and subpixel Antialiasing, and subpixel positioning. Commonly you're storing 3 channel alpha (or color), and 6 copies of each glyphs at different subpixel positions. You're not blitting these glyphs, you're blending them with the background. Font atlases do not fit in cache, especially at 4k. You also need to not just write the framebuffer, but also send it to the GPU. On some systems that can be done quickly, on others you're going over PCIe. And on top of all that, you have the data structures that are telling you what text to render where, which further fill the cache.

All that to say, your example of blitting a single color is very, very far away from the practical reality of rendering a GUI.

I elicited a demo application from Claude last night to test this. As a placeholder name, it's called Riffle. On the CPU, it does LCD subpixel antialiasing, subpixel positioning, kerning, the full-paragraph-optimization Knuth–Plass line breaking algorithm, Liang hyphenation, full text justification, Unicode, continuously variable font size, and continuously variable font weight, and it blends the glyphs with an animated procedural texture background, per color channel, i.e., with LCD subpixel antialiasing.

If you're not familiar with some of these algorithms, just know that, for the most part, they're significantly more demanding than the layout systems used by Real Applications (if a browser is a Real Application, anyway) and produce much better results.

On my 1080p display (¼ of 4K) Riffle runs in the range 120–300 frames per second on one of my four cores, at roughly 1 gigapixel per second. However, my LCD is only 60 fps.

I tried to record a video with OBS, but not only did the extra load slow Riffle down to only about 70fps, but OBS started missing most of the screen frames I was seeing when Riffle updated the screen rapidly, adding serious jank to the recording that wasn't there in real life. Worse, my attempts to compress the resulting file with ffmpeg to anything resembling a reasonable size made complete garbage out of the text. So you'll have to run it yourself if you want to see it.

On one core of the Xeon it was first tested on, it draws roughly 3.5 gigapixels per second, which is about 60% faster than memcpy and would be about 400 frames per second at 4K resolution. On my Ryzen 5 3500U laptop, it manages about 1.1 gigapixels per second, which is 55% slower than memcpy and barely over 120 frames per second. I'm hoping I can improve that today.

Although most of the algorithms I'm using produce much higher-quality output than Real Applications, I did do two things that compromise output quality slightly to get speed:

1. Compositing the dark antialiased text onto the light background is done with elementwise minimum rather than standard α-multiplication. This is an imperceptible difference visually, but roughly doubles the fill rate even without LCD subpixel compositing, which it provides for free.

2. The glyph atlas for each frame is generated from a piecewise-linear sampled approximation of the font SDF, which is generated at startup. (Initially, I was just rendering the frame directly from the SDF, but on the Xeon that was only hitting about 1 gigapixel per second.) At large font sizes this produces visible artifacts. However, it also provides continuously variable font size, weight, and outlining.

Again, I don't want to claim that rendering the UI on the CPU is better than doing it on the GPU. Doing it on the GPU is better! But doing it on the CPU is totally tolerable, very far from "pegging the CPU while scrolling [on] a 4k120hz display".

If you want to try it out, it's at https://canonical.org/~kragen/sw/riffle-packed.tar.gz.

It's a neat demo, but not applicable for a UI toolkit. Sure, if you render text poorly you can achieve much greater speeds. You don't need to look hard to see artifacts even at regular font sizes with this approach.

Do the same demo with proper font atlases and proper blending and you won't be seeing that same level of performance.

I don't think it's rendering text poorly, although this may be a question of taste. Look at the screenshots yourself: https://canonical.org/~kragen/sw/vriffle/

Despite the artifacts at regular font sizes I see with the current version of vriffle, its text rendering is dramatically superior to what mainstream UI toolkits provide, at least to my eye. Mainstream UI toolkits do not provide Knuth–Plass paragraph wrapping, any hyphenation at all, or any justification, and many of them do not even provide subpixel glyph positioning. Consequently, their text rendering quality more closely resembles that of an amateur desktop publishing flyer printed from a Macintosh SE than that of a properly typeset book. vriffle is closer to a properly typeset book, unless you set the text to be blurry or outlined or something.

The slight artifacts in its letterforms are smaller than the variability in inking you see in a book printed from hot lead. Mostly they have the effect of making DejaVu Serif look slightly more like a slab-serif font, which improves its readability at small point sizes.

Moreover, vriffle's approach provides continuously variable font sizes and font weights, which mainstream UI toolkits do not.

Finally, on my laptop, it's rendering 1080p frames in 3–5 milliseconds on one of the laptop's four cores, so at 60fps it's only using about 25% of one core, which is 6% of the CPU. This is a long way from pegging the CPU, and that's redoing the layout and rasterization from scratch on every frame, which you don't have to do if you're just rerendering to scroll. The compositing step is more like 1–2 milliseconds, but I think that's only because of a performance bug; with luck I'll be able to speed that up 4× today.

But, you might ask, what about the 4K display at 120fps we were originally talking about? That's 4 times the pixels twice as often, but that would still only be 50% of my CPU. And, as I understand it, this laptop's HDMI port isn't physically capable of more than 1080p output at 144Hz. If you were building a machine to drive a bigger display, I imagine you'd use a higher-end CPU to do it.

> I think immediate-mode UI is awful (does lot of useless work, redraws whole window on every mouse move). Also I think GPU support is not that important:

If you're concerned about efficiency, GPU support is very important. But IMGUI is not the efficiency enemy you think it is; while IMGUI libraries do need to traverse the hierarchy of visible objects on every mouse movement, there are generally only a few dozen rectangles and a few thousand letters and other graphical objects visible, so the work involved in traversing them is generally very small amount compared to copying a few million pixels into the framebuffer.

As an example, I currently have a browser viewing HN and an Emacs window open, and they total about 3000 characters (1523 mostly-blank characters and 206 words in Emacs, 335 words in HN, plus chrome), a couple dozen icons, and another dozen or so roundrects. But my screen is 2 million pixels.

So the amount of per-drawable work has to be almost three orders of magnitude larger before the per-pixel work isn't the dominant factor.

IMGUI libraries do have to do a bit more work to avoid redrawing all those pixels on every mouse movement, but many popular IMGUI libraries, such as React, do in fact do that work. It's a somewhat less simple job than for retained-mode GUI libraries like Qt (or the browser DOM), but the added complexity in the IMGUI library often pays off in simpler and more reliable apps.

> there are generally only a few dozen rectangles

Only in a hello world application. Every professional editor like GIMP has tons of tiny widgets. And redrawing one tiny widget on mouse over is faster than running the render function.

Also, you are assuming that running render function costs nothing while in real-world apps there will be layout calculations (because you don't want to position widgets manually), array iteration (for example, to display a sum and average of values from a 100K element array), text characters layout, calling helper functions, generating SVG for a 10K points graph, some genius might add reading from a file, etc.

Yes, writing good code is harder than bad code, especially for a LLM.

And if you are on the stage where you need widgets and layout calculation, why not add a dirty flag and damage rectangles as well, I cannot understand.

You say I'm talking about a hello-world application, but I'm talking about Firefox, Emacs, and my window manager. Firefox has 10 tabs visible, 21 icons in the toolbar, five bookmarks, and about 20 HTML elements. This still adds up to a few dozen rectangles, not thousands or even hundreds.

You say I'm assuming that the render function costs nothing. I thought it was clear that I was not assuming that; what I said in the comment that you're responding to is, "The amount of per-drawable work has to be almost three orders of magnitude larger before the per-pixel work isn't the dominant factor." But you may have responded before I added that; I forget if I added it in later. Here by "drawable" I mean talking about things like letters, not widgets that have their own render functions. Widgets that have their own render functions can take more than four orders of magnitude more time than the per-pixel work before the per-widget work becomes the dominant factor.

It's true, as you say, that people are capable of using up that margin by doing things like reading from a file, because writing good code is harder than writing bad code. But that's not really a question of immediate-mode vs. retained-mode. You can write bad code with retained-mode GUI libraries, too. In fact, my experience is that it's much harder to write good code with retained-mode GUI libraries.

As for layout calculations, the layout engine I elicited from Opus 5.5 for http://canonical.org/~kragen/sw/megilloom-sandbox lays out 60,000 lines of text per second, in JavaScript, and it supports table layout. (It caches the layout calculations so that it can remain responsive up to hundreds of thousands of lines.)

Some IMGUI libraries are capable of providing a dirty flag and damage rectangles without requiring every application to duplicate the error-prone cache-invalidation logic to do that. As Raph points out in this post, they're not a panacea. But they're not as bad as you are naïvely assuming them to be.

> the error-prone cache-invalidation logic

Because writing good code is harder than bad code.

Let me give an example. I vide-coded a program that renders white and gray frames and it can do it faster than 60fps on one core in a VM with no GPU. However, VS Code in that VM feels like it is running at 5 fps. The scrolling is slow and laggy. Why is that so? Probably because writing good code is harder. And probably they were thinking like you, that redrawing the whole screen is fast enough except in fact it is not.

Every time someone says that their framework is fast, they should test it in a VM without a GPU.

Generally speaking, what distinguishes good code from bad code is that it minimizes the number of error-prone things that must be done. As Frank Borman said, "A superior pilot uses his superior judgment to avoid situations which require the use of his superior skill."

I think VS Code is slow because it's a piece of shit, not because it uses an IMGUI library. I don't think it does use an IMGUI library; I think it uses src/vs/base/browser/ui which is all retained-mode.

VS Code runs in Node, which is fundamentally mostly a single-event-loop system, and in general it's very difficult for large single-event-loop systems to be reliably responsive, because literally any loop, anywhere in the system, that runs for too many iterations, will cause it to start janking. That's a problem with browser apps, too. Erlang-style actor systems have a much better chance, but they can still run into unexpected head-of-line blocking problems.

I have some experimental designs for software transactional memory systems which I hope will solve this problem...

I agree we need to minimize programming errors - by designing a good reactive retained mode framework.
Immediate mode UIs don't need to be redrawn on every mouse move: https://blickeditor.com/blog/caching-an-immediate-mode-ui?la...
When using Wayland, you have 2 buffers that you render your window into, and they already contain previous window content so why make a cache? Why not simply skip the parts that did not change?

The article you are referring to is interesting, but it looks like adding a hack instead of rewriting the code. They also did not make measurements for an older system without a working GPU.

> If rebuilding the UI takes a millisecond at most, how much should we care?

Because user runs multiple programs, and rendering UI doesn't always take milliseconds, and battery capacity is not infinite. Also programs using GPU typically use lot of extra memory, require slow shader compilation, GPUs often have buggy drivers.

Also it would be better if every program used same UI widgets (for example, GTK) rather than have their own set of widgets with missing features like IME support, different hot keys etc.

Also, what is the advantage of immediate mode UI over proper GUI reactive framework with convenient declarative syntax? I see no advantages.