Hacker News new | ask | show | jobs
by codedokode 10 days ago
Let's say you scroll text. I believe rendering one line of text (that became visible) on each frame, and reusing previously rendered lines is faster than rendering all text on every frame. Text rendering is not an easy task.

And as I have written above, you can offload compositing (memcpy) to any GPU from 90s while rendering letters is a harder task. Even with glyph cache you need to manage it, upload updates to GPU etc. So much easier to not use GPU for this.

1 comments

I don't believe that reusing previously rendered lines is faster than rendering all text on every frame. I don't know why you keep repeating this when I've already explained why I think it isn't true; you haven't presented any counterarguments. In case you just didn't understand what I was saying, I'll explain it more plainly.

Text rendering can be made arbitrarily complex, but in most cases it is not. In Russian, most Spanish, most Japanese, Ukrainian, or English, code points map 1:1 to glyphs, and figuring out where each glyph belongs on a line is a matter of running a prefix sum over their advances. AVX-512 prefix sum on 32-element vectors is about 2 nanoseconds per 32-element vector, so you need about 5 nanoseconds of layout time per line and about 200 nanoseconds for the whole screen, say 250ns to include the time to check for exceptional cases and figure out where each line belongs on the screen. This gives you a display list of some 3000 glyphs at various places on the screen.

If you rerender 2 megapixels from that display list at, say, 5 gigapixels per second on the CPU, it's going to take 400μs, which is 400,000ns. (I think the evidence I've shown above strongly suggests that this is doable on my laptop here, although it isn't a proof.)

If, instead, you copy 2 megapixels from one place to another in RAM, you can only do that at about 2.5 gigapixels per second, so reusing previously rendered lines will take more like 800μs.

That is slower than 400μs.

It is not faster than 400μs.

If you, instead, pass the display list to the GPU to texture-map from the font atlas, well, this GPU has a theoretical peak texture fill rate of 38.4 gigatexels per second, so it will take more like 52 μs. On the GPU, you can't really reuse the previously rendered lines.

Again, 800μs is slower than 52 μs. It's not faster.

The GPU doesn't really mind rendering 3000 quads instead of two or three. The difference is down in the range of [correction!] microseconds; this GPU can in theory do one triangle per clock at 1.2GHz, so each quad takes about 1.7 nanoseconds, and you can do 3000 of them in 5μs, about 10% of the total. But this is running concurrently with the fill rate, so it doesn't increase the 52μs.

The key thing to note, though, is that even the 800μs you would get by foolishly reusing previously rendered lines is still pretty small compared to the frame time, which at 60fps (what my laptop can actually run at) is 16667μs, 20 times longer. If you parcel that out among the 3000 or so glyphs on the screen, you have almost 5.6μs to do all the text layout calculations for each glyph: kerning, ligatures, shaping, whatever.

It's true that you need to manage the texture atlas, glyph cache, etc., although multichannel SDF fonts can provide reasonable antialiased results at a fairly wide range of pixel sizes, which can reduce this load quite a lot.

I believe your calculations have errors.

First, the data is sent to the monitor from a framebuffer. With compositors like Wayland, every window has its own buffer, and when it is damaged (updated), the compositors copies (memcpy) the damaged part from window buffer into the framebuffer using CPU or GPU. As I understand, this part cannot be skipped and the application renders window content into a window buffer so there always will be a memcpy stage to have it actually displayed.

For example, if the button changed its color, the program updates button image in window buffer, reports the damaged rectangle and the compositor copies that change into the framebuffer to become visible.

Actually compositors use two buffers to prevent tearing, and switch between them on every update so the things might be more complicated.

So with this model in mind, updating one line of text in a window buffer is faster than updating the whole buffer.

Furthermore, to render the text you need to memcpy the glyphs from glyph cache into their locations. So rendering whole window of text boils down to lot of small memcpys.

Also, you mention AVX-512 but I don't think my CPU has it. And when doing lot of 256-bit SIMD the CPU starts throttling to 1GHz-level speed. Also, you mentioned display lists but that requires extra memory compared to my approach.

Also, I decided to try to actually benchmark rendering text from a glyph atlas. Luckily, LLMs can write such code in matter of minutes, so I wrote it: https://pastebin.com/7baP4tWv

Results in a VM without a GPU:

Buffer 3840 x 2160 px, grid 295 cols x 90 rows = 26550 letters/frame, 10 runs, avg per frame: 7.832 ms, time per letter: 295.0 ns, letters/second: 3390088, pixels/second: 1059.086 Mpx/s.

I also godbolt'ed the hot loop in case you are curious about the assembly - it seems to use 128-bit SIMD and unrolled the single glyph rendering loop: https://godbolt.org/z/1Gh1McKE8

Thanks! This is very interesting; I'll take a look.
I get 760 megapixels per second running your code, so your machine runs it a little faster than mine. 0.76 or 1.06 gigapixels per second is definitely slower than my ballpark of 5 gigapixels per second, both on a single core, although it's still enough to hit 400fps on my 1920×1080 laptop and close to 120fps at the 4K resolution you're testing. But there are two easily fixable reasons why it's so slow.

It looks like GCC is failing to vectorize your blend() call in the inner loop, which is one key factor that limits your fill rate. In the listing file, I see `movzbl (%rdx,%rax), %r13d; imull $65793, %r13d, %r13d` generated from blend() with `gcc -Wa,-adhlns=codedokode.lst $(pkg-config --cflags freetype2) -O2 -g -c codedokode.c`, using Debian GCC 12.2.0-14. That multiplier is 0x010101, converting grayscale to BGRA. If you want to alpha-blend your pixels, as blend() suggests, you definitely need to vectorize that. That's not rocket science. It's more or less why we got MMX back in the Pentium Pro days. You can see my code for doing it, using GCC vector extensions rather than SSE intrinsics, at https://gitlab.com/kragen/bubbleos/-/blob/master/spikes/veca....

Also, as you can easily see, your code has 2× overdraw, visiting the whole framebuffer roughly from beginning to end twice:

  /* Render the whole text grid into the framebuffer. Every cell is blended
   * (no early-out on zero alpha) so the cost per letter is constant. */
  static void render_text(uint32_t *buf)
  {
      for (size_t i = 0; i < BUF_PIXELS; i++) {
          buf[i] = BG_COLOR;
      }

      for (int row = 0; row < ROWS; row++) {
          for (int col = 0; col < COLS; col++) {
              const int idx = text[row][col] - FIRST_CHAR;
              const int x0 = col * CELL_W;
              const int y0 = row * LINE_H;

              for (int y = 0; y < CELL_H; y++) {
                  uint32_t *dst = buf + (size_t)(y0 + y) * SCREEN_W + x0;
                  const uint8_t *src = glyph_cache[idx][y];
                  for (int x = 0; x < CELL_W; x++)
                      dst[x] = blend(/* dst[x] */BG_COLOR, FG_COLOR, src[x]);
              }
          }
      }
  }
That means two cache misses per cache line in the framebuffer. So every pixel has to travel from the CPU cache out to SDRAM once when it's set, then a second time from SDRAM back into the cache when setting some other pixels in its cache line results in a cache miss, and then a third time back from cache to SDRAM.

I think that if you want to get pixel fill rates exceeding memcpy() on the CPU, you'll need to fix those two problems. You aren't going to get memcpy()-exceeding rates with that strategy! But, if you fix them, you probably will.

> First, the data is sent to the monitor from a framebuffer. With compositors like Wayland, every window has its own buffer, and when it is damaged (updated), the compositors copies (memcpy) the damaged part from window buffer into the framebuffer using CPU or GPU. As I understand, this part cannot be skipped and the application renders window content into a window buffer so there always will be a memcpy stage to have it actually displayed.

I don't know much about Wayland, but this is definitely not true when you're rendering fullscreen on the GPU. I've heard there are ways to allocate your memory buffers such that you get zero-copy scanout in the fullscreen case (GBM_BO_USE_SCANOUT | GBM_BO_USE_LINEAR or DRM) but I haven't tried Wayland.

> Furthermore, to render the text you need to memcpy the glyphs from glyph cache into their locations. So rendering whole window of text boils down to lot of small memcpys.

Yes, certainly you need to do memcpy or similar if you're copying pixels from the glyph cache into the framebuffer. But memcpy() is only slow when it misses cache. In this example, which is fairly typical in displaying only 95 distinct glyphs (though not in having 27000 of them on the screen at once), the glyph cache is less than 30KiB. That's a quarter the size of my L1d cache! So it doesn't have to pull data in from main-memory SDRAM (or, worse, VRAM!) to fill up the framebuffer the way it does if you're reusing previously rendered lines. It can use the main-memory bus's whole bandwidth to write to the framebuffer instead of having to also read it.

> Also, you mentioned display lists but that requires extra memory compared to my approach.

Yes, tens of kilobytes. This is not significant when the framebuffer is 8–32MiB.

The Riffle program I elicited from Claude last night renders text to pixels about twice as fast as your program on my laptop: https://news.ycombinator.com/item?id=50613058

But that's still slower than memcpy(), although it was 60% faster than memcpy() on the Xeon it was initially tested on. Hopefully I can fix that today!

I have not been able to fix it! I've tried a number of different approaches to minimize the glyph-compositing time, but nothing has worked.

So it's faster than memcpy only on hardware like Xeons, not on my Ryzen 5 3500U laptop. Rendering a 1080P frame of dense text on my laptop takes about 4 milliseconds on one core, half of which is compositing the glyphs with a procedural background. By contrast, memcpy takes only 0.8 milliseconds.

Moreover, I've decided that you're basically right about damage tracking, and I was wrong. As long as there's a framebuffer somewhere in the pipeline, and nothing is gratuitously clearing it, redrawing part of that framebuffer will take less work than redrawing all of it, because you don't have to memcpy the part you aren't changing.

And this is true whether the framebuffer is a SysV shared memory segment, a buffer of unified system RAM, VRAM on a discrete GPU card, GDDRAM in an LCD controller chip you're talking to over SPI, or particles of electret floating in the oil of a bistable e-paper electrophoretic display. The kind of work you save is different from one to the next, but damage rectangles save work in every case, even if it's just a little. Even in cases where it doesn't update the display faster, it often extends battery life.

In most of these scenarios, you can scroll the unchanged part of the screen by setting a couple of registers to scan out the pixels in a different order, as you said, so I was pretty much wrong about that too.

In particular, my example, "to scroll the contents of a browser window but not the browser chrome," can be handled by redrawing the browser chrome in a different position over part of the scrolled page. I'm not sure how you would design the graphics API to make this simple, but you can clearly do it.

Similarly, I think it is correct that "reusing previously rendered lines is faster than rendering all text on every frame". I was wrong about that.

> Also, as you can easily see, your code has 2× overdraw, visiting the whole framebuffer roughly from beginning to end twice:

Yes I did it for simplicity, as I wanted to get the estimate of how fast or slow can be CPU rendering. Probably I could clear the buffer by small tiles right before rendering text, so that cleared part stays in L1 cache and can be blended faster.

I glanced through your code but it also seems to copy the data from a glyph cache into the buffer, it just has more optimizations to skip some parts.

> I've heard there are ways to allocate your memory buffers such that you get zero-copy scanout in the fullscreen case (GBM_BO_USE_SCANOUT | GBM_BO_USE_LINEAR or DRM) but I haven't tried Wayland.

Maybe, but a maximized window usually leaves some space for task bars, status bars. Also, on a large monitor you typically do not open windows fullscreen. So the rendering goes through a window buffer in shared memory (on Wayland, and X applications often use SHM extension to achieve the same effect).

> In particular, my example, "to scroll the contents of a browser window but not the browser chrome," can be handled by redrawing the browser chrome in a different position over part of the scrolled page. I'm not sure how you would design the graphics API to make this simple, but you can clearly do it.

Yes it seems that nobody does it these days, so the best you can do is to have two buffers (for the toolbars and for the content) and ask the display compositor to combine them. Which it will do through a memcpy, but if the buffers are in VRAM, the GPU will do the copying.

However, while Wayland supports compositing window from subsurfaces, it doesn't support "scrolling" of a surface (displaying the content of a buffer with an offset and wrapping), so you need to redraw the whole buffer on scrolling.